From 969b257253bf60c394f0cfb09f15254a5b118aed Mon Sep 17 00:00:00 2001 From: Luis <42945842+ldiaz94@users.noreply.github.com> Date: Mon, 12 Oct 2026 15:20:41 +0100 Subject: [PATCH] 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. --- diff --git a/PLAN.md b/PLAN.md index 92a9695..ce72a65 100644 --- a/PLAN.md +++ b/PLAN.md @@ -20,6 +20,25 @@ listings show the steps below. ulam's `doc/codegen.md` measured the same rewrites in a compiler of the same kind; its gains are quoted. +**Where it stands.** Steps 1 to 6 are done and pushed. rat takes 504 +to 512 ms against 614 to 625 for the same workload built by the +milestone's first compiler, on a machine that drifts by 3%; pt built +with `-O2 -Cr` takes 424 ms on the same day, so rat is at 1.19 times, +inside the goal. Text is 1.5% smaller. Each step, with its commit: + +| Step | rat | Its kernel | +|---|---|---| +| 1. Prologue | -12% | | +| 2. Two words in rax, rdx | noise | calls returning two results, -9% | +| 3. Two results on the stack | -8% | | +| 4. Conditions as jumps | noise | a search leaving by break, -28% | +| 5. Shifts, constants right | noise | heap sort and list walk, -11% | +| 6. for loops | noise | matrix product -14%, sum -21% | + +Steps that left rat's time alone stayed for their kernels, which the +2% rule allows. Moves between registers bought size, not time: this +machine renames them away, as ulam found. + 1. **A prologue that does only what it must.** A register variable keeps a frame slot that is zeroed for nothing, and so do the slots the registers are saved in: `Str.decode`, whose four variables are diff --git a/conform/run/TwoWords.expect b/conform/run/TwoWords.expect index 84ef5a1..eff7390 100644 --- a/conform/run/TwoWords.expect +++ b/conform/run/TwoWords.expect @@ -8,3 +8,5 @@ 14 111 18 5 22 +2 3 +7 diff --git a/conform/run/TwoWords.raz b/conform/run/TwoWords.raz index 07f2ad0..4b5a514 100644 --- a/conform/run/TwoWords.raz +++ b/conform/run/TwoWords.raz @@ -45,6 +45,8 @@ if n > 0 then return 1, 2; end; end; +proc three(n: INT): (INT, INT, INT); begin return n, n + 1, n + 2; end; + proc main*; var x, y: I32; b: BOOL; v, p, q: INT; w: I64; h: proc(n: INT): (INT, INT); pv: ^INT; begin @@ -59,6 +61,9 @@ (* in order: the second result is the one left *) v, v := nested(4); Out.int(v); Out.ln; pv := ADR(q); pv^, p := nested(5); Out.int(q); Out.str(" "); Out.int(p); Out.ln; + (* three results, which come back in memory, some dropped *) + _, p, q := three(1); Out.int(p); Out.str(" "); Out.int(q); Out.ln; + p, _, _ := three(7); Out.int(p); Out.ln; end; end TwoWords. diff --git a/doc/compiler.md b/doc/compiler.md index 50e2ffd..8f16251 100644 --- a/doc/compiler.md +++ b/doc/compiler.md @@ -8,14 +8,14 @@ | File | Lines | Code | What | |---|---|---|---| -| `src/diag.pas` | 310 | 229 | Messages: positions, source excerpts, colour, counts | +| `src/diag.pas` | 316 | 233 | Messages: positions, source excerpts, colour, counts | | `src/scan.pas` | 886 | 747 | Symbols, literals, comments, positions | | `src/sym.pas` | 643 | 527 | Types, objects, scopes, layout | | `src/chunk.pas` | 318 | 246 | The compiled program: chunks, fixups, line notes | | `src/x64.pas` | 1,125 | 936 | The instruction encoder, jumps within a procedure, the assembler | -| `src/gen.pas` | 1,665 | 1,291 | The stack machine, for x86-64: values, operations, checks, calls, frames | -| `src/item.pas` | 1,535 | 1,277 | Items: types, constants, variables, operators, conversions, calls | -| `src/parse.pas` | 2,966 | 2,615 | Declarations, statements, expressions, built-ins, recovery, warnings | +| `src/gen.pas` | 1,666 | 1,291 | The stack machine, for x86-64: values, operations, checks, calls, frames | +| `src/item.pas` | 1,536 | 1,278 | Items: types, constants, variables, operators, conversions, calls | +| `src/parse.pas` | 2,967 | 2,612 | Declarations, statements, expressions, built-ins, recovery, warnings | | `src/link.pas` | 247 | 190 | Tree shaking, layout, patching, the places | | `src/elf.pas` | 435 | 352 | Static and dynamic ELF, symbol table, line numbers | | `src/raz.pas` | 197 | 147 | The command line | @@ -119,6 +119,141 @@ `ReturnJump`'s, and the frame is `EnterBody`'s and `EndProc`'s. It is not fast code. It is code whose every instruction you can account for, which is the point. + +## Better code, in one procedure + +`Str.decode` reads one UTF-8 character from a slice of bytes, and for +plain ASCII it is done by its third line. It is called once for each +character a program prints, so its first lines are worth looking at. +Here is what `raz -S lib/Str.raz` says of them, before the work of +v0.7.0: + +``` + 102 proc decode*(s: []U8): (I32, INT); + 0 push rbp + 1 mov rbp, rsp + 4 sub rsp, 96 + 11 xor eax, eax + 13 mov r10, -7 + 20 mov [rbp + r10 * 8 - 24], rax + 25 add r10, 1 + 29 jne 20 + 35 mov [rbp - 80], rbx + 39 xor ebx, ebx + 41 mov [rbp - 72], r12 + 45 xor r12d, r12d + 48 mov [rbp - 64], r13 + 52 xor r13d, r13d + 55 mov [rbp - 56], r14 + 59 xor r14d, r14d + 62 mov [rbp - 8], rdi + 66 mov [rbp - 24], rsi + 70 mov [rbp - 16], rdx + 105 if LEN(s) = 0 then return 0, 0; end; + 74 mov r8, [rbp - 16] + 78 cmp r8, 0 + 82 jne 118 + 88 xor r8d, r8d + 91 mov rcx, [rbp - 8] + 95 mov [rcx], r8d + 98 xor r8d, r8d + 101 mov rcx, [rbp - 8] + 105 mov [rcx + 8], r8 + 109 mov rax, [rbp - 8] + 113 jmp 807 + 106 c := I32(s[0]); + 118 xor r8d, r8d + 121 mov rax, r8 + 124 cmp rax, [rbp - 16] + 128 jae 825 + 134 add rax, [rbp - 24] + 138 mov r8, rax + 141 movzx r8d, byte [r8] + 145 movsxd r8, r8d + 148 mov rbx, r8 + 107 if c < 80H then return c, 1; + 151 cmp rbx, 128 + 158 jge 202 + 164 mov r8, rbx + 167 mov rcx, [rbp - 8] + 171 mov [rcx], r8d + 174 mov r8, 1 + 180 mov rcx, [rbp - 8] + 184 mov [rcx + 8], r8 + 188 mov rax, [rbp - 8] + 192 jmp 807 + 197 jmp 421 + 202 cmp rbx, 192 + 209 jge 256 +``` + +and after: + +``` + 102 proc decode*(s: []U8): (I32, INT); + 0 push rbp + 1 mov rbp, rsp + 4 sub rsp, 64 + 11 mov [rbp - 48], rbx + 15 xor ebx, ebx + 17 mov [rbp - 40], r12 + 21 xor r12d, r12d + 24 mov [rbp - 32], r13 + 28 xor r13d, r13d + 31 mov [rbp - 24], r14 + 35 xor r14d, r14d + 38 mov [rbp - 16], rdi + 42 mov [rbp - 8], rsi + 105 if LEN(s) = 0 then return 0, 0; end; + 46 mov r8, [rbp - 8] + 50 test r8, r8 + 53 jne 68 + 59 xor edx, edx + 61 xor eax, eax + 63 jmp 595 + 106 c := I32(s[0]); + 68 xor r8d, r8d + 71 cmp r8, [rbp - 8] + 75 jae 613 + 81 add r8, [rbp - 16] + 85 movzx r8d, byte [r8] + 89 movsxd r8, r8d + 92 mov rbx, r8 + 107 if c < 80H then return c, 1; + 95 cmp rbx, 128 + 102 jge 121 + 108 mov rdx, 1 + 113 mov rax, rbx + 116 jmp 595 + 121 cmp rbx, 192 + 128 jge 149 +``` + +What went, and the routine that took it away: + +1. **The loop at 11 to 29**, which zeroed seven quadwords: the frame + slots of the four variables, all of them in registers, and the slots + the registers are saved in, which are written before they are read. + Now a variable in a register has no slot, and only the locals in + memory are zeroed (`PlaceLocals`, `UseRegs`, `EnterBody`). +2. **The hidden pointer**: the two results went through `rcx` to the + caller's memory. Two words come back in `rax` and `rdx` now + (`InTwoRegs`), so `return 0, 0` is two instructions; and the caller + pops them straight into its variables (`mWords`, `MultiAssign`). +3. **`cmp r8, 0`** is `test r8, r8`, the same flags in fewer bytes + (`CmpI`). +4. **Copies through `rax`**: `s[0]`'s address is worked out in the + register it is used from (`IndexSlice`), and a result is put in `rax` + from where it is (`PopTo`). +5. **The `jmp 421` after `return`**, which nothing could reach: a branch + of an `if` that ends gets no jump past the others (`IfStatement`). + +What is left is worth knowing too. The slice's two words still go to +the frame, since only single values live in registers; `movzx` then +`movsxd` reads a byte and makes an `I32` of it in two steps where one +would do; and the four registers are saved and restored on every call, +though this path uses one of them. Each could go, at the cost of lines +a reader would have to follow. ## diag.pas: messages diff --git a/src/gen.pas b/src/gen.pas index 2fea262..9f41b3d 100644 --- a/src/gen.pas +++ b/src/gen.pas @@ -153,7 +153,7 @@ procedure KeepTemps; procedure BeginProc(sig: PType; params: PObj); -procedure LocalsFromScratch; +procedure ResetLocals; procedure UseRegs(mask: longint); procedure MarkCode(var m: TCodeMark); procedure Redo(const m: TCodeMark); @@ -539,20 +539,20 @@ { Operations } -function Log2(v: int64): longint; +function ExactLog2(v: int64): longint; var n: longint; begin n := 0; while (v > 1) and (v and 1 = 0) do begin v := v shr 1; inc(n) end; if v <> 1 then n := -1; - Log2 := n; + ExactLog2 := n; end; { r times v, a size: by a shift where v is a power of two, as it mostly is, since a shift takes one cycle and imul three } procedure MulI(r: longint; v: int64); begin - if Log2(v) > 0 then ShiftI(shShl, r, Log2(v)) + if ExactLog2(v) > 0 then ShiftI(shShl, r, ExactLog2(v)) else if v <> 1 then ImulI(r, v); end; @@ -651,7 +651,7 @@ and (stack[depth - 1].loc <> lConst) then Swap; c := TopConst(v); sh := -1; - if c and (op in [sTimes, sDiv, sMod]) then sh := Log2(v); + if c and (op in [sTimes, sDiv, sMod]) then sh := ExactLog2(v); if c and (sh >= 1) then begin Drop; r := Top; @@ -1272,6 +1272,7 @@ two results on the stack, the first under the second, and a single value on top } if res = nil then + { nothing comes back } else if res^.form = fSlice then begin Store(Mem(RBP, c.ret), RAX, 8); Store(Mem(RBP, c.ret + 8), RDX, 8); @@ -1383,7 +1384,7 @@ { The frame as BeginProc left it, with the parameters' slots only: the locals are given theirs again once their registers are chosen. } -procedure LocalsFromScratch; +procedure ResetLocals; begin frameTop := paramTop; frameMax := paramTop; permTop := paramTop; end; @@ -1520,7 +1521,7 @@ begin codeChunk := -1; if (depth <> 0) or (pushed <> 0) then Fatal('internal error: stack depth'); - if open then + if open then begin if BehindPointer(resType) then begin Load(RDI, Mem(RBP, retSlot), 8, false); MovRI(RCX, resType^.size); @@ -1531,8 +1532,8 @@ MovRI(RAX, 0); if InTwoRegs(resType) then MovRI(RDX, 0); MovqXR(0, RAX); - end - else DropJumpTo(exitL); + end; + end else DropJumpTo(exitL); FixLink(exitL); n := 0; for i := 0 to 4 do diff --git a/src/item.pas b/src/item.pas index 59f9491..f052432 100644 --- a/src/item.pas +++ b/src/item.pas @@ -106,6 +106,7 @@ procedure TempItem(var x: TItem; t: PType; off: int64); function ScalarSize(t: PType): longint; procedure ForStep(o: PObj; step: int64); +procedure ForCmp(o: PObj; const lim: TItem; op: TSym; var L: longint); procedure ForNext(o: PObj; const lim: TItem; step: int64; var exitL: longint; top, body: longint); procedure BeginProc(sig: PType; params: PObj); @@ -1329,7 +1330,7 @@ Assign(v, w); end; -{ For ForNext: pushes the variable o and the limit lim, a constant or +{ For a for loop: pushes the variable o and the limit lim, a constant or the slot it was put in, and jumps to L if the one is op the other, as the type of o compares } procedure ForCmp(o: PObj; const lim: TItem; op: TSym; var L: longint); diff --git a/src/parse.pas b/src/parse.pas index c8a4e39..5ec5446 100644 --- a/src/parse.pas +++ b/src/parse.pas @@ -1332,7 +1332,7 @@ so that a round of a loop by 1 takes one compare and one jump. } procedure ForStatement(const start: TPos; ind: longint); var - o: PObj; v, a, b, s, lim: TItem; step: int64; top, body, bodyL, exitL: longint; + o: PObj; v, a, b, s: TItem; step: int64; top, body, bodyL, exitL: longint; lp: TLoop; old: PLoop; begin Next; @@ -1364,12 +1364,7 @@ end; Expect(sDo); exitL := NoLabel; - MakeItem(v, o); - Value(v); - lim := b; - Value(lim); - if step > 0 then JumpCmp(sGtr, o^.typ^.signed, exitL) - else JumpCmp(sLss, o^.typ^.signed, exitL); + if step > 0 then ForCmp(o, b, sGtr, exitL) else ForCmp(o, b, sLss, exitL); bodyL := NoLabel; Jump(bodyL); top := pc; @@ -1592,13 +1587,11 @@ if y.mode = mWords then Swap; f := y.typ^.fields; for i := 0 to n - 1 do begin - if y.mode = mWords then begin - z := y; - z.mode := mStack; z.typ := f^.typ; - end; + z := y; + if y.mode = mWords then begin z.mode := mStack; z.typ := f^.typ end + else Field(z, f); if blanks[i] then Discard(z) else begin - if y.mode <> mWords then begin z := y; Field(z, f) end; CoerceExact(z, d[i].typ, 'several results go to variables of just their types'); Assign(d[i], z); end; @@ -1830,6 +1823,14 @@ or (o^.typ^.form = fSet) and (o^.typ^.size <= 8)); end; +{ The first local of the procedure being compiled. Locals are chained + by link in the order declared, the module's own first; before is the + last one declared before the procedure's, or nil if there was none. } +function FirstLocal(before: PObj): PObj; +begin + if before = nil then FirstLocal := curModule^.locals else FirstLocal := before^.link; +end; + { Puts the busiest variables of the procedure, whose parameters are params and whose locals follow before, in registers: read ahead from its "begin" to its end, a use counts 1, in a loop 4, in two 16, and @@ -1842,11 +1843,11 @@ isLoop: array[0..255] of boolean; n, i, k, d, loops, best: longint; o: PObj; st: TScanState; afterDot, wasSkipping: boolean; - function Find(name: longint): longint; + function Candidate(name: longint): longint; var j: longint; begin for j := 0 to n - 1 do if cand[j]^.name = name then exit(j); - Find := -1; + Candidate := -1; end; procedure Add(o: PObj); @@ -1858,7 +1859,7 @@ n := 0; o := params; while o <> nil do begin Add(o); o := o^.next end; - if before = nil then o := curModule^.locals else o := before^.link; + o := FirstLocal(before); while o <> nil do begin Add(o); o := o^.link end; if n > 0 then begin SaveScan(st); @@ -1881,9 +1882,9 @@ if id = nameAdr then begin Next; if tok = sLparen then Next; - if (tok = sIdent) and (Find(id) >= 0) then weight[Find(id)] := low(longint) div 2; - end else if not afterDot and (Find(id) >= 0) then begin - k := Find(id); + if (tok = sIdent) and (Candidate(id) >= 0) then weight[Candidate(id)] := low(longint) div 2; + end else if not afterDot and (Candidate(id) >= 0) then begin + k := Candidate(id); if loops > 2 then inc(weight[k], 64) else inc(weight[k], 1 shl (2 * loops)); end; end; @@ -1913,7 +1914,7 @@ for k := 0 to 4 do if o^.reg = VarRegs[k] then m := m or (1 shl k); o := o^.next; end; - if before = nil then o := curModule^.locals else o := before^.link; + o := FirstLocal(before); while o <> nil do begin if o^.cls = oVar then for k := 0 to 4 do if o^.reg = VarRegs[k] then m := m or (1 shl k); @@ -1929,8 +1930,8 @@ procedure PlaceLocals(params, before: PObj); var o: PObj; begin - LocalsFromScratch; - if before = nil then o := curModule^.locals else o := before^.link; + ResetLocals; + o := FirstLocal(before); while o <> nil do begin if (o^.cls = oVar) and (o^.reg = 0) then o^.val := AllocPerm(o^.typ^.size, o^.typ^.align); o := o^.link; @@ -1991,7 +1992,7 @@ until false; EndProc(p^.chunk, p^.openEnd); { its parameters and variables, for the trap report } - if before = nil then o := curModule^.locals else o := before^.link; + o := FirstLocal(before); q := params; while q <> nil do begin if VarKind(q) <> 0 then NoteVar(p^.chunk, q^.name, q^.val, VarKind(q));