raz / commit 46597e23

commit
46597e23432a6e82504fd8cd3c9b36c0b421289a
author
Luis <42945842+ldiaz94@users.noreply.github.com>
date
parent
c126e150
Register variables

A procedure keeps its busiest single values, up to five, in rbx and
r12 to r15, which calls leave alone. ChooseRegs reads the body ahead
and counts uses, a use in a loop 4, in two 16, leaving out what ADR
takes; a variable whose address is wanted after all, by a var
parameter, is put back in memory and the body compiled again (MarkCode,
Redo). The prologue saves the registers after the variables, zeroes
them and takes the parameters' values; the epilogue restores them. A
variable in one is noted on the stack (lHeld) and read in place where
only read (Peek): i < n is cmp rbx, r12, and an argument mov rdi, rbx.
The trap report: each procedure's record in the places says which it
saved and where; Rt carries the five registers out frame by frame
(liveRegs, restore). Budget raised to 8,500 by the owner's word.
rat on 26 MB of terminal output: 953 ms to 740 (-22%); Pretty 1,405 to
1,174 (-16%), Doc 454 to 393, a counting loop 997 to 700; the code is
the same size. 8,283 lines of code; bench 962k lines/s.

patch · log

12 files changed, +438 -92

CLAUDE.md modified +2 -1

@@ -55,7 +55,8 @@
5555 `Luis <42945842+ldiaz94@users.noreply.github.com>`, unsigned
5656 (`--no-gpg-sign`), no attribution trailer. Push to `main`. No pull
5757 requests unless asked.
58-- Budget: a soft limit of 8,000 lines of code (blank and comment lines
58+- Budget: a soft limit of 8,500 lines of code (raised from 8,000 by
59+ the owner's word, for register variables; blank and comment lines
5960 not counted), with the compiler documented and commented throughout,
6061 most of all where it is obscure or needs a compiler writer's
6162 knowledge; at least 400,000 lines of raz a second.

doc/compiler.md (history) modified +40 -12

@@ -1,6 +1,6 @@
11 # Reading the raz compiler
22
3-The compiler is eleven files of Free Pascal, under 8,100 lines of code.
3+The compiler is eleven files of Free Pascal, under 8,300 lines of code.
44 This guide walks through them in the order they are best read: from the
55 characters of a source file to the bytes of an executable. It assumes
66 you know the language from `doc/raz.md`, and enough x86-64 to read a
@@ -10,13 +10,13 @@
1010 |---|---|---|---|
1111 | `src/diag.pas` | 310 | 229 | Messages: positions, source excerpts, colour, counts |
1212 | `src/scan.pas` | 886 | 747 | Symbols, literals, comments, positions |
13-| `src/sym.pas` | 615 | 510 | Types, objects, scopes, layout |
14-| `src/chunk.pas` | 298 | 232 | The compiled program: chunks, fixups, line notes |
15-| `src/x64.pas` | 1,094 | 916 | The instruction encoder, jumps within a procedure, the assembler |
16-| `src/gen.pas` | 1,428 | 1,118 | The stack machine, for x86-64: values, operations, checks, calls, frames |
17-| `src/item.pas` | 1,400 | 1,168 | Items: types, constants, variables, operators, conversions, calls |
18-| `src/parse.pas` | 2,771 | 2,459 | Declarations, statements, expressions, built-ins, recovery, warnings |
19-| `src/link.pas` | 243 | 188 | Tree shaking, layout, patching, the places |
13+| `src/sym.pas` | 616 | 511 | Types, objects, scopes, layout |
14+| `src/chunk.pas` | 300 | 234 | The compiled program: chunks, fixups, line notes |
15+| `src/x64.pas` | 1,108 | 926 | The instruction encoder, jumps within a procedure, the assembler |
16+| `src/gen.pas` | 1,536 | 1,203 | The stack machine, for x86-64: values, operations, checks, calls, frames |
17+| `src/item.pas` | 1,412 | 1,178 | Items: types, constants, variables, operators, conversions, calls |
18+| `src/parse.pas` | 2,895 | 2,566 | Declarations, statements, expressions, built-ins, recovery, warnings |
19+| `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 |
2222
@@ -47,10 +47,12 @@
4747 needs it in a register, so that it can be an instruction's operand. A
4848 comparison, too, waits as a condition, so that `if` and `while` jump
4949 on it directly. Which register a value goes in is settled
50-by its depth, so there is no register allocator, and every access the
51-program writes is one instruction, in the order written. That is also
52-why `VOLATILE` costs the compiler nothing: it never does anything
53-clever to begin with.
50+by its depth, so there is no register allocator for values, and every
51+access the program writes is one instruction, in the order written.
52+That is also why `VOLATILE` costs the compiler nothing: it never does
53+anything clever to begin with. A procedure's busiest variables, up to
54+five, live in the registers that calls leave alone (`rbx` and `r12` to
55+`r15`), where nothing but their own assignments can change them.
5456
5557 The output is a set of *chunks*: one for each procedure, each module
5658 variable, each string. Code refers to other chunks through *fixups*,
@@ -351,6 +353,17 @@
351353 scratch space comes from `AllocTemp` and is given back by
352354 `ReleaseTemps`; `AllocPerm` reserves space for the whole procedure.
353355
356+Register variables: the parser chooses them (`ChooseRegs`, below) and
357+tells gen (`UseRegs`): the registers, as bits of `VarRegs`, and the
358+slots they are saved in, a quadword each after the variables. The
359+prologue saves them, zeroes them, and takes a parameter's value from
360+where it came; the epilogue restores them. A variable in one is an
361+item at `bReg`: `PushVar` notes it (`lHeld`) rather than copying it,
362+`Peek` reads it in place where the value is only read, so `i < n` is
363+`cmp rbx, r12`, and `PopVar` and `IncDecReg` write it. Rt finds the
364+values for the trap report from the saves: each procedure's record in
365+the places says which it saved, and where (`saveMask`, `saveAt`).
366+
354367 ## item.pas: items
355368
356369 An operand is an *item* (`TItem`), as in Wirth's compilers. Its `mode`
@@ -520,6 +533,18 @@
520533 parses its own arguments, since `SIZE` takes a type and `INC` a
521534 variable.
522535
536+**Register variables.** One pass can't know whether a variable's
537+address will be taken before its code is made, so `ChooseRegs` reads
538+the body ahead, as `InstancesFor` does, and counts each variable's
539+uses: 1 for each, 4 in a loop, 16 in two; one `ADR` takes is out. The
540+five busiest used at least three times get registers (`o^.reg`). An
541+address wanted after all, by a `var` parameter, say, comes to
542+`Address` (`item.pas`), which puts the variable back in memory and
543+sets `demoted`: `Body` then throws the procedure's code away
544+(`MarkCode`, `Redo`) and compiles its statements again. Its notes for
545+the trap report are made after, by `VarKind`, which marks a variable
546+in a register with the register's number.
547+
523548 ## link.pas: tree shaking and layout
524549
525550 `MarkLive` starts from the entry chunk and follows fixups, marking each
@@ -634,6 +659,9 @@
634659 with no `break`. So is a call standing on its own that drops a
635660 result (`drops`, kept by `OneStatement` and told by `Dropped`);
636661 `_ := f(x)` drops one on purpose. `-Werror` makes each an error.
662+- **Registers for variables.** Up to five of a procedure's single
663+ values, not reals, whose address is never taken, live in `rbx` and
664+ `r12` to `r15`; the trap report shows them as it shows the others.
637665 - **Several results** come back through a hidden pointer to the
638666 caller's slots; a code procedure returns two in rax and rdx.
639667 - **Reals.** A real constant is held as an F64. An `F32` in a register

lib/Rt.raz (history) modified +59 -6

@@ -35,12 +35,13 @@
3535 file whose path is at path in the names *)
3636 Place = record at, line, col, path: U32; end;
3737 (* A procedure, from address start to stop, called name, and its
38- count variables from first on *)
39- Proc = record start, stop, name, first, count: U32; end;
38+ count variables from first on; it saves the registers of its
39+ variables, bits of regs, a quadword each from saveAt in its frame *)
40+ Proc = record start, stop, name, first, count, saves: U32; saveAt: I32; end;
4041 (* A variable of a procedure, at off from its frame, shown by kind:
4142 1 a signed integer, 2 an unsigned one, 3 a BOOL, 4 an address,
4243 5 a real; plus its size times 16, and 256 if the frame holds its
43- address *)
44+ address, or 512 times 1 + i if it is in register i of regs *)
4445 Local = record name: U32; off: I32; kind: U32; end;
4546 (* What rt_sigaction and sigaltstack take *)
4647 Action = record
@@ -61,6 +62,9 @@
6162 The linker makes them. *)
6263 places: ^INT;
6364 line: [256]U8; (* the message being made *)
65+ (* rbx, r12, r13, r14 and r15 in the frame being told of, where the
66+ compiler keeps a procedure's busiest variables *)
67+ regs: [5]UINT;
6468 lineLen: INT;
6569 act: Action;
6670 alt: Stack;
@@ -159,7 +163,7 @@
159163 (* The paths and names, after the places, procedures and variables *)
160164 proc names: ^U8;
161165 begin
162- return ^U8(places + 5) + 16 * places[0] + 20 * places[3] + 12 * places[4];
166+ return ^U8(places + 5) + 16 * places[0] + 28 * places[3] + 12 * places[4];
163167 end;
164168
165169 (* Puts where the code at address a comes from, as file:line:col: and
@@ -251,6 +255,7 @@
251255 var a: ^U8; w: ^UINT; h: ^U16; s: ^U32; f: ^F32; d: ^F64; v: UINT; bits: INT;
252256 begin
253257 a := ^U8(bp) + INT(l^.off);
258+ if l^.kind shr 9 # 0 then a := ^U8(ADR(regs[INT(l^.kind shr 9) - 1])); end;
254259 w := ^UINT(a);
255260 if l^.kind & 256 # 0 then a := ^U8(w^); w := ^UINT(a); end;
256261 h := ^U16(a); s := ^U32(a); f := ^F32(a); d := ^F64(a);
@@ -285,14 +290,60 @@
285290 return 1;
286291 end;
287292
293+(* rbx, r12, r13, r14 and r15, into p[0] to p[4] *)
294+proc liveRegs(p: ^UINT);
295+code
296+ mov [rdi], rbx;
297+ mov [rdi + 8], r12;
298+ mov [rdi + 16], r13;
299+ mov [rdi + 24], r14;
300+ mov [rdi + 32], r15;
301+ ret;
302+end liveRegs;
303+
304+(* An address in the code of the procedure that calls it *)
305+proc here: UINT;
306+code
307+ mov rax, [rsp];
308+ ret;
309+end here;
310+
311+(* regs as the caller of p's frame at bp left them, where p saved them *)
312+proc restore(p: ^Proc; bp: UINT);
313+var i, j: INT; q: ^UINT;
314+begin
315+ if p = nil then return; end;
316+ j := 0;
317+ for i := 0 to 4 do
318+ if p^.saves shr i & 1 # 0 then
319+ q := ^UINT(^U8(bp) + INT(p^.saveAt) + 8 * j);
320+ regs[i] := q^;
321+ INC(j);
322+ end;
323+ end;
324+end;
325+
288326 (* Says the calls under way, a line each, from the one at address ip
289327 whose frame is at bp: where each is, and its variables, unless vars
290328 is false for the first. At most 20 lines; a frame that isn't the
291329 program's ends them. Calls of one procedure from one place, as in a
292330 recursion that overflowed the stack, are told once, and counted. *)
293331 proc calls(ip, bp: UINT; vars: BOOL);
294-var p, last: ^Proc; l: ^Local; i, n, same: INT; q: ^UINT; lastIp: UINT;
332+var p, last: ^Proc; l: ^Local; i, n, same: INT; q: ^UINT; lastIp, x, xip: UINT; saved: BOOL;
295333 begin
334+ (* the registers as they are, then as each frame from this one out
335+ to bp's found them *)
336+ liveRegs(ADR(regs[0]));
337+ x := framePtr();
338+ xip := here();
339+ while (x # bp) and (x & 7 = 0) and (x # 0) do
340+ restore(procAt(xip), x);
341+ q := ^UINT(x);
342+ if q[0] <= x then break; end;
343+ xip := q[1] - 1;
344+ x := q[0];
345+ end;
346+ saved := vars; (* not in a prologue: the frame has saved them *)
296347 n := 0;
297348 same := 0;
298349 last := nil;
@@ -311,7 +362,7 @@
311362 putStr(names() + INT(p^.name));
312363 put(" at ");
313364 where(ip);
314- l := ^Local(^U8(places + 5) + 16 * places[0] + 20 * places[3]) + INT(p^.first);
365+ l := ^Local(^U8(places + 5) + 16 * places[0] + 28 * places[3]) + INT(p^.first);
315366 if not vars or (p^.count = 0) then DEC(lineLen, 2); end; (* where's ": " *)
316367 for i := 0 to INT(p^.count) - 1 do
317368 if vars then
@@ -325,6 +376,8 @@
325376 INC(n);
326377 vars := true;
327378 end;
379+ if saved then restore(p, bp); end;
380+ saved := true;
328381 q := ^UINT(bp);
329382 if (bp & 7 # 0) or (q[0] <= bp) then break; end;
330383 ip := q[1] - 1; (* the call, by its return address *)

src/chunk.pas modified +2 -0

@@ -35,6 +35,8 @@
3535 ext: boolean; { bss: the address of a C symbol, its name }
3636 reals: boolean; { code: computes with reals, first at realsAt }
3737 realsAt: TPos;
38+ saveMask: longint; { code: the registers of variables it saves, as bits of gen's VarRegs }
39+ saveAt: longint; { ... at this offset from the frame, one quadword each }
3840 end;
3941
4042 { A place in the source whose code starts at a place in text: for

src/gen.pas modified +121 -13

@@ -56,16 +56,19 @@
5656
5757 { Where a variable is: its address is relative to the frame, to a
5858 chunk, to an address on the stack, or to one held in a frame slot }
59- TBase = (bFrame, bGlobal, bStack, bSlot);
59+ TBase = (bFrame, bGlobal, bStack, bSlot, bReg);
6060 TAdr = record
6161 base: TBase;
62- chunk: longint; { bGlobal: the chunk; bSlot: the frame slot }
62+ chunk: longint; { bGlobal: the chunk; bSlot: the frame slot; bReg: the register }
6363 off: int64; { added to the address }
6464 end;
6565
6666 { How an argument waits for its call: in a frame slot, or noted, as a
6767 constant or as the address of the frame or a chunk plus an offset }
68- TArgHow = (argSlot, argConst, argAdr);
68+ TArgHow = (argSlot, argConst, argAdr, argHeld);
69+
70+ { The code made so far, to go back to for a second try at a body }
71+ TCodeMark = record pc, fixups, lines, said: longint; end;
6972
7073 TCall = record
7174 sig: PType;
@@ -83,6 +86,12 @@
8386 ret: int64; { set by Call: the temporary an aggregate result is in }
8487 end;
8588
89+const
90+ { the registers a procedure keeps its busiest variables in: System V's
91+ callee-saved ones, so they live through calls; a procedure saves
92+ those it uses, and Rt finds them there for the trap report }
93+ VarRegs: array[0..4] of longint = (RBX, R12, R13, R14, R15);
94+
8695 var
8796 rtFail, argcChunk, argvChunk: longint;
8897 depth: longint; { the values on the stack }
@@ -116,6 +125,7 @@
116125 procedure CompareSeq(a, b: int64; shift: longint; eq: boolean);
117126 procedure ErrorText(tmp: int64);
118127 procedure IncDec(size: longint; signed, dec: boolean);
128+procedure IncDecReg(r, size: longint; signed, dec: boolean);
119129 procedure ZeroNew(size: int64);
120130 procedure Atomic(which: longint);
121131 procedure SysCall(n: longint);
@@ -148,6 +158,9 @@
148158 procedure KeepTemps;
149159
150160 procedure BeginProc(sig: PType; params: PObj);
161+procedure UseRegs(mask: longint; at: int64);
162+procedure MarkCode(var m: TCodeMark);
163+procedure Redo(const m: TCodeMark);
151164 procedure EnterBody(c, line: longint);
152165 procedure ResultTo(off: int64; size: longint);
153166 procedure CopyResult(off, size: int64);
@@ -165,6 +178,8 @@
165178 type
166179 { where a value on the stack is }
167180 TLoc = (lConst, { not loaded: val is the value }
181+ lHeld, { not loaded: in register val, a variable's own,
182+ which nothing in an expression can change }
168183 lAdr, { not loaded: the address of chunk, or of the frame
169184 if chunk is -1, plus val }
170185 lReg, { in its register }
@@ -198,7 +213,12 @@
198213 inReg: array[0..13] of longint;
199214 inSlot: array[0..13] of int64;
200215 inSize: array[0..13] of longint;
216+ inObj: array[0..13] of PObj;
201217 numIn: longint;
218+ procParams: PObj; { the parameters, for EnterBody }
219+ regMask: longint; { the registers of variables, as bits of VarRegs }
220+ saveAt: int64; { where they are saved, a quadword each }
221+ frameAt: array[0..2] of int64; { frameTop, frameMax, permTop after the declarations }
202222
203223 function KindOf(t: PType): TKind;
204224 begin
@@ -263,11 +283,19 @@
263283 if stack[i].loc <> lReg then begin
264284 r := Claim(i);
265285 if stack[i].loc = lConst then MovRI(r, stack[i].val)
286+ else if stack[i].loc = lHeld then MovRR(r, stack[i].val)
266287 else if stack[i].loc = lAdr then Lea(r, AdrMem(i, 0))
267288 else Load(r, Mem(RBP, stack[i].val), 8, false);
268289 stack[i].loc := lReg;
269290 end;
270291 Loaded := RegOf(i);
292+end;
293+
294+{ The register value i is in, only to be read: a variable's own, or
295+ its register }
296+function Peek(i: longint): longint;
297+begin
298+ if stack[i].loc = lHeld then Peek := stack[i].val else Peek := Loaded(i);
271299 end;
272300
273301 function Top: longint;
@@ -334,6 +362,7 @@
334362 function Place(const a: TAdr; r: longint): TMem;
335363 var ra: longint;
336364 begin
365+ if a.base = bReg then Fatal('internal error: a register has no address');
337366 case a.base of
338367 bFrame: Place := Mem(RBP, a.off);
339368 bGlobal: Place := MemRip(a.chunk, a.off);
@@ -342,7 +371,7 @@
342371 Place := AdrMem(depth - 1, a.off);
343372 Drop;
344373 end else begin
345- ra := Top;
374+ ra := Peek(depth - 1);
346375 Drop;
347376 Place := Mem(ra, a.off)
348377 end;
@@ -370,6 +399,10 @@
370399 procedure PushVar(const a: TAdr; size: longint; signed: boolean; k: TKind);
371400 var m: TMem; r: longint;
372401 begin
402+ if a.base = bReg then begin
403+ NewEntry(k, lHeld, a.chunk);
404+ exit;
405+ end;
373406 if a.base = bStack then begin m := Place(a, -1); r := Target end
374407 else begin r := Target; m := Place(a, r) end;
375408 Load(r, m, size, signed);
@@ -390,13 +423,18 @@
390423 procedure PopVar(const a: TAdr; size: longint);
391424 var r: longint; v: int64;
392425 begin
426+ if a.base = bReg then begin
427+ if TopConst(v) then MovRI(a.chunk, v) else MovRR(a.chunk, Peek(depth - 1));
428+ Drop;
429+ exit;
430+ end;
393431 if TopConst(v) and Fits32(v) then begin
394432 Drop;
395433 StoreI(Place(a, RCX), v, size);
396434 exit;
397435 end;
398436 if TopConst(v) then begin r := RAX; MovRI(RAX, v) end
399- else r := Top;
437+ else r := Peek(depth - 1);
400438 Drop;
401439 Store(Place(a, RCX), r, size);
402440 end;
@@ -533,7 +571,7 @@
533571 function Operands(var y: longint): longint;
534572 var v: int64;
535573 begin
536- if TopConst(v) then begin MovRI(RCX, v); y := RCX end else y := Top;
574+ if TopConst(v) then begin MovRI(RCX, v); y := RCX end else y := Peek(depth - 1);
537575 Drop;
538576 Operands := Top;
539577 end;
@@ -785,6 +823,18 @@
785823 Store(Mem(r, 0), RAX, size);
786824 end;
787825
826+{ INC or DEC of the variable in register r, by the value on top; a
827+ narrow one wraps at its width }
828+procedure IncDecReg(r, size: longint; signed, dec: boolean);
829+var y, op: longint; v: int64;
830+begin
831+ if dec then op := aluSub else op := aluAdd;
832+ if TopConst(v) and Fits32(v) then AluI(op, r, v)
833+ else begin y := Top; Alu(op, r, y) end;
834+ Drop;
835+ if size < 8 then Extend(r, size, signed);
836+end;
837+
788838 { The pointer on top, which NEW got, to size zero bytes unless nil }
789839 procedure ZeroNew(size: int64);
790840 var L, r: longint;
@@ -827,6 +877,7 @@
827877 for i := 0 to n - 1 do
828878 with stack[depth - n + i] do
829879 if loc = lConst then MovRI(SysRegs[i], val)
880+ else if loc = lHeld then MovRR(SysRegs[i], val)
830881 else if loc = lAdr then Lea(SysRegs[i], AdrMem(depth - n + i, 0))
831882 else Load(SysRegs[i], Mem(RBP, val), 8, false);
832883 for i := 1 to n do Drop;
@@ -864,8 +915,9 @@
864915 CcUnsigned: array[sEql..sGeq] of longint = (ccE, ccNE, ccB, ccBE, ccA, ccAE);
865916 var r, y: longint; v: int64;
866917 begin
867- if TopConst(v) then begin Drop; r := Top; CmpI(r, v) end
868- else begin r := Operands(y); Alu(aluCmp, r, y) end;
918+ { a comparison changes neither: a variable's register will do }
919+ if TopConst(v) then begin Drop; r := Peek(depth - 1); CmpI(r, v) end
920+ else begin y := Peek(depth - 1); Drop; r := Peek(depth - 1); Alu(aluCmp, r, y) end;
869921 Drop;
870922 if signed then Jcc(CcSigned[op], L) else Jcc(CcUnsigned[op], L);
871923 end;
@@ -1069,7 +1121,8 @@
10691121 i := depth - 1;
10701122 c.how[c.n] := argSlot;
10711123 if not c.isF[c.n] and (stack[i].loc = lConst) then c.how[c.n] := argConst
1072- else if stack[i].loc = lAdr then c.how[c.n] := argAdr;
1124+ else if stack[i].loc = lAdr then c.how[c.n] := argAdr
1125+ else if stack[i].loc = lHeld then c.how[c.n] := argHeld;
10731126 if c.how[c.n] = argSlot then begin
10741127 c.slots[c.n] := AllocTemp(8, 8);
10751128 Store(Mem(RBP, c.slots[c.n]), Top, 8);
@@ -1085,6 +1138,7 @@
10851138 begin
10861139 case c.how[i] of
10871140 argConst: MovRI(r, c.slots[i]);
1141+ argHeld: MovRR(r, c.slots[i]);
10881142 argAdr:
10891143 if c.adrChunk[i] < 0 then Lea(r, Mem(RBP, c.slots[i]))
10901144 else Lea(r, MemRip(c.adrChunk[i], c.slots[i]));
@@ -1202,10 +1256,12 @@
12021256 exitL := NoLabel;
12031257 numIn := 0;
12041258 resType := sig^.base;
1259+ procParams := params;
1260+ regMask := 0;
12051261 ni := 0; nf := 0; stackOff := 16;
12061262 if (resType <> nil) and IsAggregate(resType) then begin
12071263 retSlot := AllocPerm(8, 8);
1208- inReg[0] := RDI; inSlot[0] := retSlot; inSize[0] := 8;
1264+ inReg[0] := RDI; inSlot[0] := retSlot; inSize[0] := 8; inObj[0] := nil;
12091265 numIn := 1; ni := 1;
12101266 end;
12111267 p := params;
@@ -1217,6 +1273,7 @@
12171273 if f then begin inReg[numIn] := -1 - nf; inc(nf) end
12181274 else begin inReg[numIn] := IntRegs[ni]; inc(ni) end;
12191275 inSlot[numIn] := p^.val;
1276+ inObj[numIn] := p;
12201277 if p^.ind then inSize[numIn] := 8
12211278 else if p^.typ^.form in [fInt, fBool, fEnum, fSet, fReal] then inSize[numIn] := p^.typ^.size
12221279 else inSize[numIn] := 8;
@@ -1230,12 +1287,35 @@
12301287 paramTop := frameTop;
12311288 end;
12321289
1290+{ The procedure keeps variables in the registers of mask, saved at at;
1291+ the frame as it stands is where a second try at its body starts. }
1292+procedure UseRegs(mask: longint; at: int64);
1293+begin
1294+ regMask := mask;
1295+ saveAt := at;
1296+ frameAt[0] := frameTop; frameAt[1] := frameMax; frameAt[2] := permTop;
1297+end;
1298+
1299+procedure MarkCode(var m: TCodeMark);
1300+begin
1301+ m.pc := pc; m.fixups := numFixups; m.lines := numLines; m.said := SaidCount;
1302+end;
1303+
1304+{ For a second try at the body: the code as it was at m, and the frame
1305+ as UseRegs found it }
1306+procedure Redo(const m: TCodeMark);
1307+begin
1308+ pc := m.pc; numFixups := m.fixups; numLines := m.lines; Unsay(m.said);
1309+ frameTop := frameAt[0]; frameMax := frameAt[1]; permTop := frameAt[2];
1310+ exitL := NoLabel;
1311+end;
1312+
12331313 { The prologue, which is for the procedure's first line. Only the
12341314 locals are zeroed: the parameters are stored over their slots next,
12351315 and every temporary is written before it is read. The locals are all
12361316 declared by now, below the parameters' slots. }
12371317 procedure EnterBody(c, line: longint);
1238-var i, top: longint; n: int64;
1318+var i, top: longint; n: int64; p: PObj;
12391319 begin
12401320 BeginChunk(c);
12411321 codeChunk := c;
@@ -1257,9 +1337,31 @@
12571337 AluI(aluAdd, R10, 1);
12581338 JccBack(ccNE, top);
12591339 end;
1340+ { the registers of variables: saved, as a variable starts at zero,
1341+ a parameter taken from where it came }
1342+ chunks^[c].saveMask := regMask;
1343+ chunks^[c].saveAt := saveAt;
1344+ n := 0;
1345+ for i := 0 to 4 do
1346+ if regMask and (1 shl i) <> 0 then begin
1347+ Store(Mem(RBP, saveAt + 8 * n), VarRegs[i], 8);
1348+ MovRI(VarRegs[i], 0);
1349+ inc(n);
1350+ end;
12601351 for i := 0 to numIn - 1 do
12611352 if inReg[i] < 0 then MovsdMX(Mem(RBP, inSlot[i]), -1 - inReg[i])
1262- else Store(Mem(RBP, inSlot[i]), inReg[i], inSize[i]);
1353+ else if (inObj[i] <> nil) and (inObj[i]^.reg <> 0) then begin
1354+ MovRR(inObj[i]^.reg, inReg[i]);
1355+ if inSize[i] < 8 then Extend(inObj[i]^.reg, inSize[i], inObj[i]^.typ^.signed);
1356+ end else Store(Mem(RBP, inSlot[i]), inReg[i], inSize[i]);
1357+ p := procParams;
1358+ while p <> nil do begin
1359+ if (p^.reg <> 0) and (p^.val > 0) then
1360+ if p^.typ^.form in [fInt, fBool, fEnum, fSet] then
1361+ Load(p^.reg, Mem(RBP, p^.val), p^.typ^.size, p^.typ^.signed)
1362+ else Load(p^.reg, Mem(RBP, p^.val), 8, false);
1363+ p := p^.next;
1364+ end;
12631365 end;
12641366
12651367 { Pops one of several results, a value of size bytes, into its place
@@ -1300,7 +1402,7 @@
13001402 { The end of the procedure in chunk c: the code that returns, and the
13011403 frame's size, known only now, patched into its prologue. }
13021404 procedure EndProc(c: longint);
1303-var n: int64;
1405+var n: int64; i: longint;
13041406 begin
13051407 codeChunk := -1;
13061408 if (depth <> 0) or (pushed <> 0) then Fatal('internal error: stack depth');
@@ -1317,6 +1419,12 @@
13171419 MovqXR(0, RAX);
13181420 end;
13191421 FixLink(exitL);
1422+ n := 0;
1423+ for i := 0 to 4 do
1424+ if regMask and (1 shl i) <> 0 then begin
1425+ Load(VarRegs[i], Mem(RBP, saveAt + 8 * n), 8, false);
1426+ inc(n);
1427+ end;
13201428 Leave;
13211429 Ret;
13221430 n := AlignUp(frameMax, 16);

src/item.pas modified +13 -1

@@ -47,6 +47,7 @@
4747 end;
4848
4949 var
50+ demoted: boolean; { Address wanted a register variable's address }
5051 checks: boolean; { the module's index and slice checks are made: it
5152 doesn't say check off }
5253
@@ -258,6 +259,8 @@
258259 x.base := bGlobal; x.chunk := o^.chunk
259260 end else if o^.ind then begin
260261 x.base := bSlot; x.chunk := o^.val; x.off := o^.off;
262+ end else if o^.reg <> 0 then begin
263+ x.base := bReg; x.chunk := o^.reg
261264 end else begin
262265 x.base := bFrame; x.off := o^.val
263266 end;
@@ -357,6 +360,14 @@
357360 procedure Address(var x: TItem);
358361 begin
359362 NilTest(x);
363+ if (x.mode = mVar) and (x.base = bReg) then begin
364+ { its address is wanted after all: the procedure is compiled again
365+ with the variable in memory; till then, this code is thrown away }
366+ x.obj^.reg := 0;
367+ demoted := true;
368+ x.base := bFrame;
369+ x.off := x.obj^.val;
370+ end;
360371 if x.mode = mStr then PushAdr(GlobalAdr(x.chunk))
361372 else if x.mode = mVar then begin
362373 PushAdr(AdrOf(x));
@@ -1370,7 +1381,8 @@
13701381 begin
13711382 CoerceExact(k, v.typ, '');
13721383 Value(k);
1373- gen.IncDec(ScalarSize(v.typ), v.typ^.signed, dec);
1384+ if v.base = bReg then IncDecReg(v.chunk, ScalarSize(v.typ), v.typ^.signed, dec)
1385+ else gen.IncDec(ScalarSize(v.typ), v.typ^.signed, dec);
13741386 end;
13751387
13761388 { An error is the address of its length, followed by its message. }

src/link.pas modified +11 -7

@@ -92,10 +92,12 @@
9292 text starts and stops, the procedures' and their variables' (I64s);
9393 for each place in live code its address, line, column and the offset
9494 of its file's path (U32s); for each live procedure where it starts and
95- stops, the offset of its name, its first variable and how many it has
96- (U32s); for each variable the offset of its name, its place in the
97- frame and its kind, as parse.pas's VarKind (U32s); then the paths and
98- names, each ending in a zero byte. They are in no order, since Rt
95+ stops, the offset of its name, its first variable and how many it
96+ has, and the registers of variables it saves, as bits of gen's
97+ VarRegs, and the frame offset they are saved at (U32s); for each
98+ variable the offset of its name, its place in the frame and its
99+ kind, as parse.pas's VarKind (U32s); then the paths and names, each
100+ ending in a zero byte. They are in no order, since Rt
99101 looks at them only as the program stops. }
100102 procedure MakePlaces(start, stop: int64);
101103 var
@@ -141,7 +143,7 @@
141143 for v := first^[c] to first^[c] + count^[c] - 1 do k := k + length(NameOf(varNotes[v].name)) + 1;
142144 nv := nv + count^[c];
143145 end;
144- buf := GetMem(40 + 16 * n + 20 * np + 12 * nv + k);
146+ buf := GetMem(40 + 16 * n + 28 * np + 12 * nv + k);
145147 PInt64(@buf^[0])^ := n;
146148 PInt64(@buf^[8])^ := start;
147149 PInt64(@buf^[16])^ := stop;
@@ -159,7 +161,7 @@
159161 at := at + 16;
160162 end;
161163 { the pool of paths and names starts at k }
162- k := 40 + 16 * n + 20 * np + 12 * nv;
164+ k := 40 + 16 * n + 28 * np + 12 * nv;
163165 names := k;
164166 { the paths first, at the offsets offs gave the places: Name puts
165167 each in the pool, and also writes its offset at at, which a path
@@ -178,7 +180,9 @@
178180 Name(ChunkName(c));
179181 PLongint(@buf^[at])^ := v;
180182 PLongint(@buf^[at + 4])^ := count^[c];
181- at := at + 8;
183+ PLongint(@buf^[at + 8])^ := chunks^[c].saveMask;
184+ PLongint(@buf^[at + 12])^ := chunks^[c].saveAt;
185+ at := at + 16;
182186 v := v + count^[c];
183187 end;
184188 for c := 0 to numChunks - 1 do

src/parse.pas modified +140 -16

@@ -81,7 +81,7 @@
8181 curResult: PType; { the result type of the procedure being compiled }
8282 inExtern: boolean; { reading an extern's signature: ... allowed }
8383 tArgv, tBodySig: PType;
84- nameRt, nameFail, nameMain, nameBody, nameStatic, nameCheck, nameOff: longint;
84+ nameRt, nameFail, nameMain, nameBody, nameStatic, nameCheck, nameOff, nameAdr: longint;
8585 declaring: array[0..63] of longint; { the names the declaration being read declares }
8686 numDeclaring: longint;
8787 skipped: boolean; { the last statement had an error and was skipped }
@@ -830,7 +830,7 @@
830830 NotReadOnly(x);
831831 if (x.mode <> mVar) or not x.isVar or (x.typ^.form <> fInt) then
832832 MarkAt(x.pos, IncOrDec(which) + ' needs an integer variable');
833- Address(x);
833+ if x.base <> bReg then Address(x);
834834 if tok = sComma then begin
835835 Next;
836836 Expression(y, x.typ);
@@ -1741,10 +1741,10 @@
17411741
17421742 { How Rt shows a variable of o's type in the trap report: 1 a signed
17431743 integer, 2 an unsigned one, 3 a BOOL, 4 an address, 5 a real; plus
1744- its size times 16, and 256 if the frame holds its address; 0 if it
1745- isn't shown. }
1744+ its size times 16, and 256 if the frame holds its address, or 512
1745+ times 1 + i if it is in register VarRegs[i]; 0 if it isn't shown. }
17461746 function VarKind(o: PObj): longint;
1747-var k: longint;
1747+var k, i: longint;
17481748 begin
17491749 case o^.typ^.form of
17501750 fInt: k := 2 - ord(o^.typ^.signed);
@@ -1755,10 +1755,121 @@
17551755 else exit(0);
17561756 end;
17571757 VarKind := k + o^.typ^.size * 16 + ord(o^.ind) * 256;
1758+ for i := 0 to 4 do
1759+ if o^.reg = VarRegs[i] then VarKind := k + o^.typ^.size * 16 + (i + 1) * 512;
17581760 end;
17591761
1762+{ Whether variable o could live in a register: a single value, not
1763+ a real, that isn't C's }
1764+function RegFit(o: PObj): boolean;
1765+begin
1766+ RegFit := (o^.cls = oVar) and not o^.ind and not o^.ext
1767+ and ((o^.typ^.form in [fInt, fBool, fEnum, fPtr, fProc, fError])
1768+ or (o^.typ^.form = fSet) and (o^.typ^.size <= 8));
1769+end;
1770+
1771+{ Puts the busiest variables of the procedure, whose parameters are
1772+ params and whose locals follow before, in registers: read ahead from
1773+ its "begin" to its end, a use counts 1, in a loop 4, in two 16, and
1774+ a variable ADR is taken of can't have one. A register costs a save
1775+ and a restore, so a variable used less than three times keeps its
1776+ place in memory. The registers are saved after the variables. }
1777+procedure ChooseRegs(params, before: PObj);
1778+var
1779+ cand: array[0..63] of PObj; weight: array[0..63] of longint;
1780+ isLoop: array[0..255] of boolean;
1781+ n, i, k, d, loops, mask, best: longint; o: PObj; st: TScanState; afterDot, wasSkipping: boolean;
1782+
1783+ function Find(name: longint): longint;
1784+ var j: longint;
1785+ begin
1786+ for j := 0 to n - 1 do if cand[j]^.name = name then exit(j);
1787+ Find := -1;
1788+ end;
1789+
1790+ procedure Add(o: PObj);
1791+ begin
1792+ if RegFit(o) and (n <= High(cand)) then begin cand[n] := o; weight[n] := 0; inc(n) end;
1793+ end;
1794+
1795+begin
1796+ n := 0;
1797+ o := params;
1798+ while o <> nil do begin Add(o); o := o^.next end;
1799+ if before = nil then o := curModule^.locals else o := before^.link;
1800+ while o <> nil do begin Add(o); o := o^.link end;
1801+ mask := 0;
1802+ if n > 0 then begin
1803+ SaveScan(st);
1804+ wasSkipping := skipping;
1805+ skipping := true; { its slips are told when it is compiled }
1806+ d := 0; loops := 0; afterDot := false;
1807+ repeat
1808+ case tok of
1809+ sBegin, sIf, sMatch, sWhile, sFor, sRepeat:
1810+ if d < High(isLoop) then begin
1811+ inc(d);
1812+ isLoop[d] := tok in [sWhile, sFor, sRepeat];
1813+ if isLoop[d] then inc(loops);
1814+ end;
1815+ sEnd, sUntil: begin
1816+ if isLoop[d] then dec(loops);
1817+ dec(d);
1818+ end;
1819+ sIdent:
1820+ if id = nameAdr then begin
1821+ Next;
1822+ if tok = sLparen then Next;
1823+ if (tok = sIdent) and (Find(id) >= 0) then weight[Find(id)] := low(longint) div 2;
1824+ end else if not afterDot and (Find(id) >= 0) then begin
1825+ k := Find(id);
1826+ if loops > 2 then inc(weight[k], 64) else inc(weight[k], 1 shl (2 * loops));
1827+ end;
1828+ end;
1829+ afterDot := tok = sPeriod;
1830+ if (d > 0) and (tok <> sEof) then Next;
1831+ until (d = 0) or (tok = sEof);
1832+ RestoreScan(st);
1833+ skipping := wasSkipping;
1834+ for k := 0 to 4 do begin
1835+ best := -1;
1836+ for i := 0 to n - 1 do
1837+ if (cand[i]^.reg = 0) and (weight[i] >= 3) and ((best < 0) or (weight[i] > weight[best])) then best := i;
1838+ if best < 0 then break;
1839+ cand[best]^.reg := VarRegs[k];
1840+ mask := mask or (1 shl k);
1841+ end;
1842+ end;
1843+ k := 0;
1844+ for i := 0 to 4 do if mask and (1 shl i) <> 0 then inc(k);
1845+ if k = 0 then UseRegs(0, 0)
1846+ else UseRegs(mask, AllocPerm(8 * k, 8));
1847+end;
1848+
1849+{ The registers the variables of the procedure are in, as ChooseRegs's
1850+ mask }
1851+function RegsOf(params, before: PObj): longint;
1852+var o: PObj; m, k: longint;
1853+begin
1854+ m := 0;
1855+ o := params;
1856+ while o <> nil do begin
1857+ for k := 0 to 4 do if o^.reg = VarRegs[k] then m := m or (1 shl k);
1858+ o := o^.next;
1859+ end;
1860+ if before = nil then o := curModule^.locals else o := before^.link;
1861+ while o <> nil do begin
1862+ if o^.cls = oVar then
1863+ for k := 0 to 4 do if o^.reg = VarRegs[k] then m := m or (1 shl k);
1864+ o := o^.link;
1865+ end;
1866+ RegsOf := m;
1867+end;
1868+
17601869 procedure Body(p: PObj; sig: PType; line: longint);
1761-var q, params, last, o, before: PObj; old: PType;
1870+var
1871+ q, params, last, o, before: PObj; old: PType; st: TScanState;
1872+ mark: TCodeMark; drops0, errs: longint;
17621873 begin
17631874 OpenScope(NewScope);
17641875 params := nil; last := nil;
@@ -1784,6 +1895,28 @@
17841895 curProc := p;
17851896 before := curModule^.lastLocal;
17861897 Declarations(false);
1898+ ChooseRegs(params, before);
1899+ { the body, made again if a variable in a register must be in memory }
1900+ SaveScan(st);
1901+ MarkCode(mark); drops0 := numDrops; errs := errors;
1902+ old := curResult;
1903+ repeat
1904+ demoted := false;
1905+ Expect(sBegin);
1906+ curResult := sig^.base;
1907+ EnterBody(p^.chunk, line);
1908+ stray := false; elseIf := false; deferSlot := 0;
1909+ Statements;
1910+ p^.openEnd := (curResult <> nil) and not ends;
1911+ NoteLine(CurLine, CurCol);
1912+ Expect(sEnd);
1913+ if not demoted or (errors <> errs) then break;
1914+ numDrops := drops0;
1915+ Redo(mark);
1916+ UseRegs(RegsOf(params, before), chunks^[p^.chunk].saveAt);
1917+ RestoreScan(st);
1918+ until false;
1919+ EndProc(p^.chunk);
17871920 { its parameters and variables, for the trap report }
17881921 if before = nil then o := curModule^.locals else o := before^.link;
17891922 q := params;
@@ -1795,16 +1928,6 @@
17951928 if (o^.cls = oVar) and (VarKind(o) <> 0) then NoteVar(p^.chunk, o^.name, o^.val, VarKind(o));
17961929 o := o^.link;
17971930 end;
1798- Expect(sBegin);
1799- old := curResult;
1800- curResult := sig^.base;
1801- EnterBody(p^.chunk, line);
1802- stray := false; elseIf := false;
1803- Statements;
1804- p^.openEnd := (curResult <> nil) and not ends;
1805- NoteLine(CurLine, CurCol);
1806- Expect(sEnd);
1807- EndProc(p^.chunk);
18081931 curResult := old;
18091932 curProc := nil;
18101933 CloseScope;
@@ -2758,6 +2881,7 @@
27582881 nameRt := Name('Rt');
27592882 nameFail := Name('fail');
27602883 nameMain := Name('main');
2884+ nameAdr := Name('ADR');
27612885 nameBody := Name('body');
27622886 nameStatic := Name('static');
27632887 nameCheck := Name('check');

src/sym.pas modified +1 -0

@@ -72,6 +72,7 @@
7272 fwd: boolean; { oProc: declared forward, no body yet }
7373 isCode: boolean; { oProc: a code procedure }
7474 openEnd: boolean; { oProc: has results, and may reach its end }
75+ reg: longint; { oVar: the register it lives in, or 0 if in memory }
7576 ext: boolean; { oProc, oVar: C's, reached through its chunk, which
7677 holds its address }
7778 fields: PObj; { oCase: its fields }

src/x64.pas modified +15 -1

@@ -18,7 +18,7 @@
1818
1919 const
2020 RAX = 0; RCX = 1; RDX = 2; RBX = 3; RSP = 4; RBP = 5; RSI = 6; RDI = 7;
21- R8 = 8; R9 = 9; R10 = 10; R11 = 11;
21+ R8 = 8; R9 = 9; R10 = 10; R11 = 11; R12 = 12; R13 = 13; R14 = 14; R15 = 15;
2222 RIP = -1; { a base meaning rip-relative, to a chunk }
2323 NoIndex = -1;
2424
@@ -125,6 +125,8 @@
125125
126126 procedure Assemble(constExpr: TConstFn);
127127 procedure Say(const s: shortstring);
128+function SaidCount: longint;
129+procedure Unsay(n: longint);
128130 procedure Restate(at: longint; const s: shortstring);
129131 procedure List(module: longint);
130132
@@ -244,6 +246,18 @@
244246 var
245247 said: ^TSaid;
246248 numSaid, saidCap: longint;
249+
250+{ How many instructions the listing has, and back to n of them, for
251+ code made again }
252+function SaidCount: longint;
253+begin
254+ SaidCount := numSaid;
255+end;
256+
257+procedure Unsay(n: longint);
258+begin
259+ numSaid := n;
260+end;
247261
248262 procedure SayAt(at: longint; const s: shortstring);
249263 begin

test/list/Listing.expect (history) modified +32 -33

@@ -30,39 +30,38 @@
3030 4 sub rsp, 48
3131 11 xor eax, eax
3232 13 mov [rbp - 8], rax
33+ 17 mov [rbp - 16], rax
34+ 21 mov [rbp - 16], rbx
35+ 25 xor ebx, ebx
3336 20 for i := 1 to 3 do
34- 17 mov qword [rbp - 8], 1
35- 25 mov qword [rbp - 16], 3
36- 33 mov r8, [rbp - 8]
37- 37 mov r9, [rbp - 16]
38- 41 cmp r8, r9
39- 44 jg 160
37+ 27 mov rbx, 1
38+ 32 mov qword [rbp - 24], 3
39+ 40 mov r9, [rbp - 24]
40+ 44 cmp rbx, r9
41+ 47 jg 144
4042 21 if i # 2 then total := add(total, twice(i)); end;
41- 50 mov r8, [rbp - 8]
42- 54 cmp r8, 2
43- 58 je 122
44- 64 mov r8, [Listing.total]
45- 71 mov [rbp - 24], r8
46- 75 mov r8, [rbp - 8]
47- 79 mov [rbp - 32], r8
48- 83 mov rdi, [rbp - 32]
49- 87 call Listing.twice
50- 92 mov r8, rax
51- 95 mov [rbp - 40], r8
52- 99 mov rdi, [rbp - 24]
53- 103 mov rsi, [rbp - 40]
54- 107 call Listing.add
55- 112 mov r8, rax
56- 115 mov [Listing.total], r8
57- 122 mov r8, [rbp - 16]
58- 126 mov r9, [rbp - 8]
59- 130 sub r8, r9
60- 133 cmp r8, 1
61- 137 jb 160
62- 143 mov r8, [rbp - 8]
63- 147 add r8, 1
64- 151 mov [rbp - 8], r8
65- 155 jmp 33
43+ 53 cmp rbx, 2
44+ 57 je 112
45+ 63 mov r8, [Listing.total]
46+ 70 mov [rbp - 32], r8
47+ 74 mov rdi, rbx
48+ 77 call Listing.twice
49+ 82 mov r8, rax
50+ 85 mov [rbp - 40], r8
51+ 89 mov rdi, [rbp - 32]
52+ 93 mov rsi, [rbp - 40]
53+ 97 call Listing.add
54+ 102 mov r8, rax
55+ 105 mov [Listing.total], r8
56+ 112 mov r8, [rbp - 24]
57+ 116 sub r8, rbx
58+ 119 cmp r8, 1
59+ 123 jb 144
60+ 129 mov r8, rbx
61+ 132 add r8, 1
62+ 136 mov rbx, r8
63+ 139 jmp 40
6664 23 end main;
67- 160 leave
68- 161 ret
65+ 144 mov rbx, [rbp - 16]
66+ 148 leave
67+ 149 ret

test/run/ThreadOverflow.stderr (history) modified +2 -2

@@ -1,6 +1,6 @@
11 test/run/ThreadOverflow.raz:6:1: stopped by a stack overflow
22 in ThreadOverflow.down at test/run/ThreadOverflow.raz:6:1
3- in ThreadOverflow.down at test/run/ThreadOverflow.raz:10:5: n = 1926
4- and 1926 more the same
3+ in ThreadOverflow.down at test/run/ThreadOverflow.raz:10:5: n = 1871
4+ and 1871 more the same
55 in ThreadOverflow.work at test/run/ThreadOverflow.raz:15:5: _arg = nil
66 in Thread.run at lib/Thread.linux-x86_64.raz:80:5: arg = 0x?, t = 0x?