raz / commit a4f60016

commit
a4f60016a5d3018e06cf793ea1c468192f6e1090
author
Luis <42945842+ldiaz94@users.noreply.github.com>
date
parent
c4ee39e3
The compiler's code, faster: 1.8 times the seed's time to 1.4

Found with perf: small blocks cleared and copied by moves, not rep; a
record literal made where it is wanted, clearing only what its fields
leave; p[i] through a pointer as an operand; try with nothing deferred
tests the error in its register; a var parameter's address in a register
(bPtr); and a few routines of the scanner. doc/compiler.md, "Better code,
for the compiler itself", has each and what did not help.

The seed's code is no longer what src/ makes: seed-check compares only
messages and statuses now, and the fixpoint is of stages 2 and 3.
README, compiler.md and src/README.md say the compiler is in raz and
builds itself.

patch · log

10 files changed, +639 -216

PLAN.md (history) modified +20 -0

@@ -47,12 +47,32 @@
4747 Then `seed/` is frozen and `self/` is `src/` (the owner's word,
4848 2026-10-13); the seed is dropped in time, its last tag the bootstrap.
4949
50+6. Faster (done, the owner's word, 2026-10-13: the compiler built by
51+ itself took 1.8 times as long as the Pascal one, and 1.3 was the aim).
52+ `perf` found no hot spot but habits of the code: small blocks cleared
53+ and copied by `rep`, a record literal made in a temporary and copied,
54+ an element through a pointer worked out, `try` through a slot of the
55+ frame, a `var` parameter's address loaded at each use, and a few
56+ routines of the scanner. `doc/compiler.md`, "Better code, for the
57+ compiler itself", has each, with what it measured and what did not
58+ help. The compiler takes 506 ms of 359 for the 348,025-line program,
59+ 1.4 times (1.36 by cycles; before 657 of 359, 1.8 times); `make
60+ bench`, 678,000 lines a second. The seed's code is no longer what
61+ `src/` makes, so `seed-check` no longer compares `Gen`, `Item` or
62+ the executables, only messages and statuses, and the fixpoint is of
63+ stage 2 and 3.
64+
5065 Done when step 5 passes with `make check` and `make bench` on the
5166 compiler it made, and the budget of lines kept.
5267
5368 ## Next, when the owner says
5469
5570 - The book, "Compiling Raz": its brief is `doc/book/PLAN.md`.
71+- The compiler's last 0.1 of the 1.3: an inliner for the small procedures
72+ that are one expression (`Gen.drop`, `X64.mem`, `Chunk.put1`, `Scan.tokPos`)
73+ would take call overhead off some 15% of the instructions; `chooseRegs`
74+ reads each procedure twice, which is 13% of the time; and `Mem`, `Item`
75+ and `Adr` are records copied at each call that passes them on.
5676 - A port to aarch64, to measure one: a new `gen.pas`, an encoder and
5777 assembler for it, and its ELF.
5878

README.md (history) modified +10 -7

@@ -24,10 +24,10 @@
2424 $ examples/Hello
2525 hello, world
2626
27-The compiler is about 10,000 lines of raz, written in itself: one pass, no
27+The compiler is about 10,700 lines of raz, written in itself: one pass, no
2828 intermediate form, no optimizer. It writes x86-64 machine code and the
29-ELF executable itself, with no assembler or linker, and compiles about
30-over 400,000 lines a second.
29+ELF executable itself, with no assembler or linker, and compiles over
30+400,000 lines a second.
3131
3232 ## What's here
3333
@@ -37,7 +37,7 @@
3737 | `doc/compiler.md` | A guide to reading the compiler, file by file |
3838 | `doc/raz.1`, `doc/raz.7`, `doc/raz-tutorial.7` | The manual pages: the command, the language at a glance, a tour; `make man` makes the library's, raz-lib(3), from `lib/` |
3939 | `src/` | The compiler, in raz |
40-| `seed/` | The first compiler, in Free Pascal: frozen, it builds `src/` the first time |
40+| `seed/` | The first compiler, in Free Pascal: frozen, kept only to build `src/` the first time |
4141 | `lib/` | The library, in raz; the compiler finds it beside itself |
4242 | `examples/` | Small programs, each with the output it should give |
4343 | `tools/Doc.raz` | Prints what a module exports, with its comments |
@@ -50,9 +50,12 @@
5050
5151 ## Building
5252
53-The first build needs Free Pascal 3.2.2 (`apt-get install fp-compiler`):
54-it builds the seed, the Pascal compiler in `seed/`, which builds the
55-compiler, `src/`, in the repository's root:
53+The compiler is written in raz, so building it takes a raz. The first
54+time there is none, and Free Pascal 3.2.2 (`apt-get install fp-compiler`)
55+builds the seed, the Pascal compiler in `seed/`, which builds the
56+compiler, `src/`, in the repository's root. Free Pascal is needed for
57+nothing else, and `make fixpoint` has the compiler build itself and
58+checks that the result is the same file.
5659
5760 make # ./raz
5861 make install # ~/.local/bin/raz, its library and tools in

doc/compiler.md (history) modified +146 -18

@@ -1,9 +1,10 @@
11 # Reading the raz compiler
22
3-The compiler is eleven files of raz, about 10,500 lines of code (the
3+The compiler is eleven files of raz, about 10,700 lines of code (the
44 budget is a soft 10,000, never past 11,000). It is its own compiler: the
55 frozen Pascal compiler in `seed/` builds `src/` the first time, and
6-after that `src/` builds itself. This guide walks through the files in the order they are best read: from the
6+after that a raz builds `src/` (`make fixpoint` checks that it makes
7+itself again, byte for byte). This guide walks through the files in the order they are best read: from the
78 characters of a source file to the bytes of an executable. It assumes
89 you know the language from `doc/raz.md`, and enough x86-64 to read a
910 disassembly. The manual pages say the rest: `raz(1)` the command,
@@ -13,13 +14,13 @@
1314 | File | Lines | Code | What |
1415 |---|---|---|---|
1516 | `src/Diag.raz` | 410 | 315 | Messages: positions, source excerpts, colour, counts |
16-| `src/Scan.raz` | 1,002 | 842 | Symbols, literals, comments, positions |
17+| `src/Scan.raz` | 1,062 | 886 | Symbols, literals, comments, positions |
1718 | `src/Sym.raz` | 684 | 555 | Types, objects, scopes, layout |
1819 | `src/Chunk.raz` | 354 | 272 | The compiled program: chunks, fixups, line notes |
19-| `src/X64.raz` | 1,472 | 1,222 | The instruction encoder, jumps within a procedure, the assembler |
20-| `src/Gen.raz` | 2,350 | 1,693 | The stack machine, for x86-64: values, operations, checks, calls, frames |
21-| `src/Item.raz` | 1,729 | 1,438 | Items: types, constants, variables, operators, conversions, calls |
22-| `src/Parse.raz` | 3,775 | 3,298 | Declarations, statements, expressions, built-ins, recovery, warnings |
20+| `src/X64.raz` | 1,493 | 1,238 | The instruction encoder, jumps within a procedure, the assembler |
21+| `src/Gen.raz` | 2,471 | 1,778 | The stack machine, for x86-64: values, operations, checks, calls, frames |
22+| `src/Item.raz` | 1,763 | 1,458 | Items: types, constants, variables, operators, conversions, calls |
23+| `src/Parse.raz` | 3,842 | 3,353 | Declarations, statements, expressions, built-ins, recovery, warnings |
2324 | `src/Link.raz` | 380 | 298 | Tree shaking, layout, patching, the places |
2425 | `src/Elf.raz` | 431 | 344 | Static and dynamic ELF, symbol table, line numbers |
2526 | `src/Raz.raz` | 273 | 214 | The command line |
@@ -619,6 +620,128 @@
619620 which there is no register. A comparison of reals still makes a
620621 `BOOL` before it jumps, as `not (a < b)` isn't `a >= b` for a NaN;
621622 neither kernel has one.
623+## Better code, for the compiler itself
624+
625+The compiler, built by itself, took 684 ms for a program of 348,000
626+lines where the same compiler written in Pascal took 374: 1.8 times as
627+long. `perf` (`perf record`, `perf annotate`; raz keeps `rbp` frames and
628+a symbol table, so it reads the compiler as it reads any program) found
629+no hot spot, but a few habits of the code, each cheap to mend. The
630+compiler now takes about 500 ms, 1.4 times the Pascal one's, and its
631+own programs are no slower for it (`make kernels`). Each step below was
632+measured by cycles (`perf stat`), as timing alone is too noisy to see
633+1%.
634+
635+1. **Small blocks cleared and copied by moves.** A record made by a
636+ literal was cleared with `rep stosb` and copied with `rep movsb`,
637+ which take some twenty cycles to start whatever the size: `x := {}`
638+ on a 112-byte `Item` was most of `makeItem`'s time. `copyBytes` did
639+ go by moves up to 64 bytes, but `zeroVar` never did. Now both take
640+ `MaxMoves`, 256 bytes, by moves: 16 bytes at a time through `xmm0`
641+ (`movdqu`), then 8, 4, 2 and 1 (`copyBytes`, `zeroBytes`). A copy of
642+ up to 64 bytes stays in words (`MaxWordMoves`): a record just made
643+ field by field is read back by loads as wide as its stores, and a
644+ 16-byte load across two 8-byte stores waits for both to reach the
645+ cache (measured: `Scan.tokPos` doubled). The prologue's loop over
646+ the locals, a quadword an iteration, is now `pxor xmm8` and a row of
647+ `movdqu` stores, or a loop of 16 bytes for a frame of more than 256.
648+ `Parse.matchStatement` has a frame of 25 kilobytes, its table of
649+ labels, cleared at each `match`: that was 5% of the compiler's
650+ misses in the first-level cache, and is the largest left.
651+
652+2. **A record literal made where it is wanted.** `return {f: a, b: c}`
653+ built the record in a temporary, cleared, and copied it behind the
654+ hidden pointer:
655+
656+ ```
657+ lea rdi, [rbp - 32] ; the temporary
658+ (clear it)
659+ mov [rbp - 32], r8 ; its fields
660+ ...
661+ lea rsi, [rbp - 32] ; and copy it out
662+ mov rdi, [rbp - 8]
663+ mov rcx, [rsi] ...
664+ ```
665+
666+ Now `oneStatement`, at `return`, says the literal is the whole of the result
667+ (`Item.literalInResult`), `tempOf` makes the item at `bSlot`, at the
668+ slot that holds the hidden pointer (`Gen.resultSlot`), and the
669+ fields go there: `mov rcx, [rbp - 8]; mov [rcx], r8`. A caller always
670+ passes a temporary of its own, so the fields can't alias what they
671+ are made from. And a literal clears only what its fields leave:
672+ `clearPadding` the words that hold padding, before the fields, and
673+ `clearMissing` the fields it gave no value, after them. `Scan.tokPos`,
674+ which the parser calls over and over, went from 33 instructions to 14.
675+
676+3. **`p[i]` through a pointer as an operand.** An element of a slice in
677+ registers was only noted, `[rdi + r12 * 8]` (`lIdx`); an element
678+ through a pointer worked out its address, `i * 8`, then `+ p`:
679+
680+ ```
681+ mov r9, r12 mov r8, [Sym.hashTab]
682+ shl r9, 3 now: mov r8, [r8 + r12 * 8]
683+ mov r8, [Sym.hashTab]
684+ add r8, r9
685+ mov r8, [r8]
686+ ```
687+
688+ `indexPtr` notes it as `lIdx` when at most one of the pointer and the
689+ index is in a register of the stack (the one the value then owns),
690+ and makes it with one `lea` otherwise.
691+
692+4. **`try` with nothing to defer tests the error in its register.** The
693+ error was stored in a frame slot, loaded, tested, and loaded again
694+ to be returned:
695+
696+ ```
697+ call f; mov r8, rax; mov [rbp - 160], r8; mov r8, [rbp - 160]
698+ test r8, r8; je ok; mov rax, [rbp - 160]; jmp exit
699+ ```
700+
701+ Where no deferred statement is in force, `tryTest` tests the register
702+ the call's result is in and `tryReturnFrom` returns it from there:
703+ `call f; mov r8, rax; test r8, r8; je ok; mov rax, r8; jmp exit`.
704+ With a deferred statement the slot stays, as `runDefers` calls code
705+ that would take the register.
706+
707+5. **A `var` parameter's address in a register.** `term(var x: Item)`
708+ loaded the pointer from its slot, `mov r8, [rbp - 8]`, at each use of
709+ `x`, `x.pos := ...` included. A parameter passed by its address (a
710+ `var` parameter, a record or an array) is now a candidate for a
711+ register as any variable is (`regFit`), and an item at `bPtr`
712+ names it: `place` is `[r12 + off]`, with no load, and `pushVar` notes
713+ it as `lMem`, so that it is read as an operand. The trap report
714+ doesn't show it (`varKind`). One in `rdi` or `rsi` of a procedure
715+ that calls nothing is kept there (`keepArrived`), as any parameter.
716+
717+6. **Two small things in the code.** `lea r8, [r8]`, which `pushAdr`
718+ made of an address already in the register, is not made.
719+ `Scan.next` reads and steps through its text in two variables that
720+ live in registers while its loops run, and stores them back after:
721+ `cur.pos`, in memory, made each step wait for the store of the one
722+ before. And `Parse.chooseRegs`, which reads a procedure through once
723+ to count its variables' uses, stops looking names up for calls after
724+ the first that does.
725+
726+The source changed too, where one routine had the habit. `Scan.lineCol`,
727+for the places the checks of a procedure are told in, counts from the
728+line last found, back or forward, where it counted back from the
729+current symbol's line each time; `curCol`, for the line table of each
730+statement, from the start of the symbol's line only; and the expression
731+levels note where they start as a number (`tokStart`, `spanFromAt`) in
732+place of a whole `Pos` that most never use.
733+
734+What did not help, as it is as well to know: `check off;` for the whole
735+compiler (1%), a better hash for `Sym` (the old one keeps the names of
736+a scope near one another and is faster), putting `scope` next to `name`
737+in `Obj`, a cache of the names found by `chooseRegs`' look-ahead, and
738+passing `Item` to `adrOf` as a `var` parameter, so as not to copy it.
739+What is left is spread thinly: the procedure call overhead of many small
740+routines (`Gen.drop`, `X64.mem`, `Chunk.put1`, which an inliner, listed
741+in `PLAN.md`, would remove), the reading of every procedure twice, and
742+a record parameter copied at each call that passes it on (`Mem`, in the
743+encoder).
744+
622745 ## Diag.raz: messages
623746
624747 Every message the compiler prints is made here. A position, `Pos`, is a
@@ -796,7 +919,8 @@
796919 `notBool`, `narrow` (to a narrow integer's width), the conversions
797920 between integers and reals, `compareSeq` (of two slices), and copying:
798921 `copyBlock`, `copyTo`, `zeroVar`, and `copySlice` for `COPY`, a `rep
799- movsb` that goes down when the destination is above the source;
922+ movsb` that goes down when the destination is above the source; the
923+ small ones by moves (`copyBytes`, `zeroBytes`);
800924 - jumps: `jump`, `jumpIf` (on a `BOOL`), `jumpCmp` (on two integers),
801925 `jumpOut` (`jumpCmp` from within an expression) and `condValue` for
802926 `and` and `or`, `fix` where the label is, and `joinJumps`;
@@ -812,7 +936,8 @@
812936
813937 A variable's place is an `Adr`: relative to the frame (`bFrame`), to a
814938 chunk (`bGlobal`), to an address on the stack (`bStack`), or to one
815-held in a frame slot (`bSlot`, as a `var` parameter's is); plus `off`.
939+held in a frame slot (`bSlot`, as a `var` parameter's is) or in a register
940+(`bPtr`, as one that has a register's is); plus `off`.
816941 `place` turns it into an x64 memory operand, popping or loading the
817942 address first, so that a variable is read or written with one
818943 instruction.
@@ -908,8 +1033,8 @@
9081033 registers.
9091034
9101035 Frames: `beginProc` gives the parameters their slots; `enterBody` writes
911-the prologue, which zeroes the locals in memory (with a few stores, or a
912-loop for more; there are none to zero in `scale`) but not the
1036+the prologue, which zeroes the locals in memory (16 bytes a store: a row of
1037+them, or a loop for more; there are none to zero in `scale`) but not the
9131038 temporaries, since each is written before it is read; `endProc` writes
9141039 the epilogue and patches the frame's size in. Within a statement,
9151040 scratch space comes from `allocTemp` and is given back by
@@ -1070,10 +1195,11 @@
10701195 `withoutLast`. Then, in the code before and after, this:
10711196
10721197 ```
1073- load [slot]; jz ok ; Gen.jumpIf(ok, false)
1198+ load [slot]; jz ok ; Gen.jumpIf(ok, false); with no deferred
1199+ ; statement, the register, tryTest
10741200 and rsp, -16 ; Gen.tryAlign, if a deferred statement is in force
10751201 call deferred... ; runDefers(0), as for a return
1076- mov rax/rdx or the results ; Gen.tryReturn(slot): zeros, and the error last
1202+ mov rax/rdx or the results ; Gen.tryReturn(slot), tryReturnFrom: zeros, and the error last
10771203 jmp exit
10781204 ok: ...
10791205 ```
@@ -1374,7 +1500,7 @@
13741500 instruction, or of calls to gen right there.
13751501 - **An instruction:** a routine in `X64.raz` built on `opM` or `opR`,
13761502 and a line in `test/enctest.pas` to check its encoding (the seed's
1377- test; `test/X64Dump` is the port's).
1503+ test; `src/test/X64Dump.raz` is the port's).
13781504 - **A machine:** a new `Gen.raz`, answering the same calls, and an
13791505 encoder and assembler for it in place of `X64.raz`.
13801506 - **A statement:** a reserved word in `Scan.raz` (in `Sym` and `words`,
@@ -1383,8 +1509,10 @@
13831509 - **A check that fails:** `check` in `Gen.raz`, and the message in
13841510 `lib/Rt.raz`'s `fail`; a reason a signal gives, `onSignal` there.
13851511
1386-The compiler is in raz, and `make raz` builds it with the seed, the
1387-frozen Pascal compiler in `seed/`, which is never edited to suit it;
1388-`make fixpoint` has it build itself twice more and checks that the last
1389-two are the same file. After any change: `make check`, `make bench`,
1512+The compiler is in raz. `make raz` builds it with the seed, the frozen
1513+Pascal compiler in `seed/` (which needs Free Pascal, and is never edited
1514+to suit `src/`); a raz that already exists could do it as well.
1515+`make fixpoint` has the seed's build compile `src/`, that compile it
1516+again, and that again, and checks that the last two are the same file.
1517+`make seed-check` tests each unit of `src/` against the seed's. After any change: `make check`, `make bench`,
13901518 `make loc`.

src/Gen.raz modified +157 -35

@@ -75,10 +75,11 @@
7575
7676 (* Where a variable is: its address is relative to the frame, to a
7777 chunk, to an address on the stack, or to one held in a frame slot *)
78- Base* = (bFrame, bGlobal, bStack, bSlot, bReg);
78+ Base* = (bFrame, bGlobal, bStack, bSlot, bReg, bPtr);
7979 Adr* = record
8080 base*: Base;
81- chunk*: INT; (* bGlobal: the chunk; bSlot: the frame slot; bReg: the register *)
81+ chunk*: INT; (* bGlobal: the chunk; bSlot: the frame slot; bReg: the register;
82+ bPtr: the register that holds the address *)
8283 off*: I64; (* added to the address; for bReg, which word, 0 or 8 *)
8384 hi*: INT; (* bReg, a slice: the register of its length, the
8485 second word; chunk is that of its pointer *)
@@ -568,6 +569,7 @@
568569 ra := peek(depth - 1);
569570 drop();
570571 return X.mem(ra, a.off + o);
572+ | bPtr: return X.mem(a.chunk, a.off);
571573 | else: (* bSlot: the address is in the frame slot a.chunk *)
572574 X.load(r, X.mem(RBP, a.chunk), 8, false);
573575 return X.mem(r, a.off);
@@ -592,7 +594,8 @@
592594 else
593595 r := target(); m := place(a, r);
594596 end;
595- X.lea(r, m);
597+ (* an address that is already in r, [r], needs no instruction *)
598+ if (m.base # r) or (m.index # X.NoIndex) or (m.disp # 0) then X.lea(r, m); end;
596599 computed(kWord);
597600 end;
598601
@@ -612,7 +615,7 @@
612615 end;
613616 (* a variable in the frame or a chunk, or at an address only noted, is
614617 only noted too: read where it is used, as an operand if it can be *)
615- if (a.base in {bFrame, bGlobal}) or (a.base = bStack) and (stack[depth - 1].loc in {lAdr, lIdx}) then
618+ if (a.base in {bFrame, bGlobal, bPtr}) or (a.base = bStack) and (stack[depth - 1].loc in {lAdr, lIdx}) then
616619 m := place(a, -1);
617620 newMem(lMem, m, k, size, signed);
618621 return;
@@ -710,19 +713,34 @@
710713
711714 (* Copying *)
712715
713-(* size bytes from [rsi] to [rdi], through rcx; rsi and rdi are left
714- as they fall. Up to 64 bytes, as a record or a small array mostly
715- is, they go as moves of 8, 4, 2 and 1 bytes: rep movsb takes some
716- twenty cycles to start, longer than the few moves take. *)
716+(* The most that copyBytes and zeroBytes do with moves, in place of rep
717+ movsb and rep stosb, which take some twenty cycles to start, longer
718+ than the few moves take. *)
719+const MaxMoves = 256;
720+
721+(* Up to this size a copy goes as words: a record just made field by
722+ field is read back by loads as wide as its stores, and a 16-byte
723+ load across two 8-byte stores waits for them to reach the cache. *)
724+const MaxWordMoves = 64;
725+
726+(* size bytes from [rsi] to [rdi], through xmm0 and rcx; rsi and rdi are
727+ left as they fall. Up to MaxMoves bytes, as a record or a small array
728+ mostly is, they go as moves: of 16 bytes from MaxWordMoves up, then
729+ of 8, 4, 2 and 1. *)
717730 proc copyBytes(size: I64);
718731 var o, n: I64;
719732 begin
720- if size > 64 then
733+ if size > MaxMoves then
721734 X.movRI(RCX, size);
722735 X.repMovsb();
723736 return;
724737 end;
725738 o := 0;
739+ while (size > MaxWordMoves) and (o + 16 <= size) do
740+ X.movdquXM(0, X.mem(RSI, o));
741+ X.movdquMX(X.mem(RDI, o), 0);
742+ INC(o, 16);
743+ end;
726744 while o < size do
727745 n := 8;
728746 while n > size - o do n := n div 2; end;
@@ -758,13 +776,38 @@
758776 copyBytes(size);
759777 end;
760778
779+(* size zero bytes at [rdi], through xmm0 and rax; rdi is left as it
780+ falls. Up to MaxMoves bytes they go as stores of 16, then of 8, 4, 2
781+ and 1 bytes, as copyBytes does. *)
782+proc zeroBytes(size: I64);
783+var o, n: I64;
784+begin
785+ if size > MaxMoves then
786+ X.movRI(RAX, 0);
787+ X.movRI(RCX, size);
788+ X.repStosb();
789+ return;
790+ end;
791+ o := 0;
792+ if size >= 16 then X.pxorXX(0); end;
793+ while o + 16 <= size do
794+ X.movdquMX(X.mem(RDI, o), 0);
795+ INC(o, 16);
796+ end;
797+ if o < size then X.movRI(RAX, 0); end;
798+ while o < size do
799+ n := 8;
800+ while n > size - o do n := n div 2; end;
801+ X.store(X.mem(RDI, o), RAX, INT(n));
802+ INC(o, n);
803+ end;
804+end;
805+
761806 proc zeroVar*(a: Adr; size: I64);
762807 begin
763808 clobberArgs();
764809 X.lea(RDI, place(a, RDI));
765- X.movRI(RCX, size);
766- X.movRI(RAX, 0);
767- X.repStosb();
810+ zeroBytes(size);
768811 end;
769812
770813 (* Operations *)
@@ -1554,6 +1597,44 @@
15541597 computed(kWord);
15551598 end;
15561599
1600+(* Whether r is one of the stack's registers, not a variable's *)
1601+proc isStackReg(r: INT): BOOL;
1602+var i: INT;
1603+begin
1604+ for i := 0 to NumRegs - 1 do
1605+ if Regs[i] = r then return true; end;
1606+ end;
1607+ return false;
1608+end;
1609+
1610+(* Pops an index and the pointer under it, and pushes the address of
1611+ the element of size bytes: p + i * size. For an element of 1, 2, 4
1612+ or 8 bytes it is only noted, as the operand [p + i * size] (lIdx), to
1613+ be read or written where it is used, when at most one of the two is
1614+ in a stack register, the register the new value owns. Otherwise lea
1615+ adds them up, in one instruction in place of a multiplication and an
1616+ addition. *)
1617+proc indexPtr*(size: I64);
1618+var b, x, own: INT; o: I64;
1619+begin
1620+ o := 0;
1621+ if fits32(stack[depth - 2].off + stack[depth - 1].off * size) then
1622+ o := takeOff(depth - 2) + takeOff(depth - 1) * size;
1623+ end;
1624+ b := peek(depth - 2);
1625+ x := peek(depth - 1);
1626+ own := Regs[(depth - 2) mod NumRegs];
1627+ drop();
1628+ drop();
1629+ if (not isStackReg(b) or (b = own)) and (not isStackReg(x) or (x = own)) then
1630+ newMem(lIdx, X.memIdx(b, x, INT(size), o), kWord, 8, false);
1631+ if b = own then owner[(depth - 1) mod NumRegs] := depth - 1; end;
1632+ else
1633+ X.lea(target(), X.memIdx(b, x, INT(size), o));
1634+ computed(kWord);
1635+ end;
1636+end;
1637+
15571638 (* Pops an index, checked, and makes the address of the element it
15581639 picks of the array at a. An element of 1, 2,
15591640 4 or 8 bytes is only noted, as the operand [base + index * size]
@@ -2019,17 +2100,31 @@
20192100 Chunk.put1(48H); Chunk.put1(81H); Chunk.put1(0ECH);
20202101 frameFix := Chunk.pc; Chunk.put4(0);
20212102 n := (Sym.alignUp(zeroTop, 8) - paramTop) div 8;
2022- if n > 0 then X.movRI(RAX, 0); end;
2023- if n <= 4 then
2024- for i := 1 to INT(n) do X.store(X.mem(RBP, -paramTop - I64(8 * i)), RAX, 8); end;
2025- else
2026- (* a quadword at a time: r10 runs from -n up to 0, and the store's
2027- address is scaled by it *)
2028- X.movRI(R10, -n);
2029- loop := Chunk.pc;
2030- X.store(X.memIdx(RBP, R10, 8, -paramTop), RAX, 8);
2031- X.aluI(X.aluAdd, R10, 1);
2032- X.jccBack(X.ccNE, loop);
2103+ if n = 1 then
2104+ X.movRI(RAX, 0);
2105+ X.store(X.mem(RBP, -paramTop - 8), RAX, 8);
2106+ elsif n > 1 then
2107+ (* the locals, 16 bytes at a time, from xmm8, which holds nothing
2108+ yet (xmm0 to xmm7 may hold a parameter): up to 16 stores in a
2109+ row, else a loop with r10 running from minus the bytes up to 0,
2110+ the store's address scaled by 1. An odd quadword is the
2111+ lowest. *)
2112+ X.pxorXX(8);
2113+ if n <= 32 then
2114+ for i := 0 to INT(n div 2) - 1 do
2115+ X.movdquMX(X.mem(RBP, -paramTop - 16 * I64(i + 1)), 8);
2116+ end;
2117+ else
2118+ X.movRI(R10, -16 * (n div 2));
2119+ loop := Chunk.pc;
2120+ X.movdquMX(X.memIdx(RBP, R10, 1, -paramTop), 8);
2121+ X.aluI(X.aluAdd, R10, 16);
2122+ X.jccBack(X.ccNE, loop);
2123+ end;
2124+ if n mod 2 = 1 then
2125+ X.movRI(RAX, 0);
2126+ X.store(X.mem(RBP, -paramTop - 8 * n), RAX, 8);
2127+ end;
20332128 end;
20342129 (* each register that holds a variable is saved, for the caller, and
20352130 zeroed, as a variable starts at zero *)
@@ -2086,6 +2181,12 @@
20862181
20872182 (* Pops one of several results, a value of size bytes, into its place
20882183 off bytes into the caller's, behind the hidden pointer. *)
2184+(* The frame slot that holds the hidden result pointer *)
2185+proc resultSlot*: I64;
2186+begin
2187+ return retSlot;
2188+end;
2189+
20892190 proc resultTo*(off: I64; size: INT);
20902191 var r: INT; fl: BOOL;
20912192 begin
@@ -2139,31 +2240,52 @@
21392240 X.aluI(X.aluAnd, RSP, -16);
21402241 end;
21412242
2142-(* The rest of it: the procedure returns the error in the frame slot, and
2143- a zero for each of its other results. Only code is made: no entry of
2144- the stack of values is touched, since the code that follows is the
2145- code for an error that is nil, with the stack as it was. *)
2146-proc tryReturn*(slot: I64);
2243+(* The procedure returns the error in register r, and a zero for each of
2244+ its other results; it isn't rax, rcx, rdx or rdi, which this uses. *)
2245+proc returnError(r: INT);
21472246 var f: ^Sym.Obj;
21482247 begin
21492248 if Sym.behindPointer(resType) then
21502249 X.load(RDI, X.mem(RBP, retSlot), 8, false);
2151- X.movRI(RCX, resType^.size);
2152- X.movRI(RAX, 0);
2153- X.repStosb();
2250+ zeroBytes(resType^.size);
21542251 f := resType^.fields;
21552252 while f^.next # nil do f := f^.next; end;
2156- X.load(RCX, X.mem(RBP, slot), 8, false);
21572253 X.load(RDX, X.mem(RBP, retSlot), 8, false);
2158- X.store(X.mem(RDX, f^.val), RCX, 8);
2254+ X.store(X.mem(RDX, f^.val), r, 8);
21592255 X.load(RAX, X.mem(RBP, retSlot), 8, false);
21602256 elsif Sym.inTwoRegs(resType) then
2161- X.load(RDX, X.mem(RBP, slot), 8, false);
2257+ X.movRR(RDX, r);
21622258 X.movRI(RAX, 0);
21632259 else
2164- X.load(RAX, X.mem(RBP, slot), 8, false);
2260+ X.movRR(RAX, r);
21652261 end;
21662262 X.jmp(exitL);
2263+end;
2264+
2265+(* The rest of it: the procedure returns the error in the frame slot, and
2266+ a zero for each of its other results. Only code is made: no entry of
2267+ the stack of values is touched, since the code that follows is the
2268+ code for an error that is nil, with the stack as it was. *)
2269+proc tryReturn*(slot: I64);
2270+begin
2271+ X.load(RSI, X.mem(RBP, slot), 8, false);
2272+ returnError(RSI);
2273+end;
2274+
2275+(* try, with no deferred statement to run: the error on top is tested in
2276+ its register r, which is returned, and, if it isn't nil, returned from
2277+ the procedure by tryReturnFrom, so it needs no slot in the frame. *)
2278+proc tryTest*(var ok: INT): INT;
2279+var r: INT;
2280+begin
2281+ r := loaded(depth - 1);
2282+ jumpIf(ok, false);
2283+ return r;
2284+end;
2285+
2286+proc tryReturnFrom*(r: INT);
2287+begin
2288+ returnError(r);
21672289 end;
21682290
21692291 (* The end of the procedure in chunk c: the code that returns, and the

src/Item.raz (history) modified +65 -31

@@ -43,7 +43,7 @@
4343 not make them); see Gen's jumpOut *)
4444 val*: I64; (* mConst: the value, an F64's bits; mStr: its length *)
4545 base*: Gen.Base; (* mVar: what the address is relative to *)
46- chunk*: INT; (* mVar with bGlobal, mStr: the chunk; bSlot: the slot *)
46+ chunk*: INT; (* mVar with bGlobal, mStr: the chunk; bSlot: the slot; bPtr: the register *)
4747 off*: I64; (* mVar: added to the base *)
4848 vol*: BOOL; (* mVar: reached through ^VOLATILE *)
4949 isVar*: BOOL; (* mVar: a variable of the program, not a temporary *)
@@ -178,35 +178,23 @@
178178 end;
179179
180180 proc frameAdr*(off: I64): Gen.Adr;
181-var a: Gen.Adr;
182181 begin
183- a.base := Gen.bFrame;
184- a.chunk := -1;
185- a.off := off;
186- a.hi := 0;
187- return a;
182+ return {base: Gen.bFrame, chunk: -1, off: off, hi: 0};
188183 end;
189184
190185 proc globalAdr*(c: INT): Gen.Adr;
191-var a: Gen.Adr;
192186 begin
193- a.base := Gen.bGlobal;
194- a.chunk := c;
195- a.off := 0;
196- a.hi := 0;
197- return a;
187+ return {base: Gen.bGlobal, chunk: c, off: 0, hi: 0};
198188 end;
199189
200-(* Where the variable x is, for Gen; a slice in registers has two *)
190+(* Where the variable x is, for Gen; a slice in registers has two. x is
191+ a var parameter only so as not to be copied, as it is a whole Item. *)
201192 proc adrOf*(x: Item): Gen.Adr;
202-var a: Gen.Adr;
193+var hi: INT;
203194 begin
204- a.base := x.base;
205- a.chunk := x.chunk;
206- a.off := x.off;
207- a.hi := 0;
208- if x.base = Gen.bReg then a.hi := x.obj^.reg2; end;
209- return a;
195+ hi := 0;
196+ if x.base = Gen.bReg then hi := x.obj^.reg2; end;
197+ return {base: x.base, chunk: x.chunk, off: x.off, hi: hi};
210198 end;
211199
212200 (* An item for "found ...": a constant without a type of its own as it
@@ -271,6 +259,8 @@
271259 x.base := Gen.bStack;
272260 elsif o^.lev = 0 then
273261 x.base := Gen.bGlobal; x.chunk := o^.chunk;
262+ elsif o^.ind and (o^.reg # 0) then
263+ x.base := Gen.bPtr; x.chunk := o^.reg; x.off := o^.off;
274264 elsif o^.ind then
275265 x.base := Gen.bSlot; x.chunk := INT(o^.val); x.off := o^.off;
276266 elsif o^.reg # 0 then
@@ -658,7 +648,7 @@
658648 end;
659649
660650 proc index*(var x, y: Item): ERROR;
661-var t: ^Sym.Type; s: I64;
651+var t: ^Sym.Type; s: I64; isConst: BOOL;
662652 begin
663653 t := x.typ;
664654 s := t^.base^.size;
@@ -666,9 +656,12 @@
666656 return Scan.markAt(y.pos, say1("an index is an integer, found {}", what(y)));
667657 end;
668658 if t^.form = Sym.fPtr then
659+ isConst := y.mode = mConst;
669660 try value(y);
670- scaleBy(s);
671- Gen.op(Scan.sPlus, Gen.kWord, 8, false);
661+ if isConst or not ((s = 1) or (s = 2) or (s = 4) or (s = 8)) then
662+ scaleBy(s);
663+ Gen.op(Scan.sPlus, Gen.kWord, 8, false);
664+ else Gen.indexPtr(s); end;
672665 x.mode := mVar; x.base := Gen.bStack; x.off := 0;
673666 x.vol := t^.vol; x.isVar := true; x.odd := false; x.ro := false;
674667 elsif (t^.form = Sym.fArray) and (y.mode = mConst) then
@@ -1306,7 +1299,7 @@
13061299 if x.mode = mWords then return nil; end; (* there already *)
13071300 (* copied to a temporary unless its two words are in memory at a place
13081301 that a later argument can't change *)
1309- if (x.mode # mVar) or x.vol or not (x.base in {Gen.bFrame, Gen.bGlobal, Gen.bSlot, Gen.bReg}) then
1302+ if (x.mode # mVar) or x.vol or not (x.base in {Gen.bFrame, Gen.bGlobal, Gen.bSlot, Gen.bReg, Gen.bPtr}) then
13101303 try copyToTemp(x);
13111304 end;
13121305 adr := adrOf(x);
@@ -1401,15 +1394,51 @@
14011394
14021395 (* Variants *)
14031396
1404-(* A temporary of type t, all zero: for variants and record literals. *)
1405-proc zeroTemp*(var x: Item; t: ^Sym.Type);
1406-var tmp: I64;
1397+(* Whether the record literal about to be parsed is the whole of a return
1398+ (see zeroTemp): Parse says so, and clears it after the expression. *)
1399+var inResult: BOOL;
1400+
1401+proc literalInResult*(yes: BOOL);
14071402 begin
1403+ inResult := yes;
1404+end;
1405+
1406+(* A temporary of type t, not cleared: where a record literal is made,
1407+ which clears only what its fields leave (zeroRange). With
1408+ literalInResult it is behind the hidden pointer, so that return {...}
1409+ makes the record where the caller wants it, not in a temporary copied
1410+ there after. *)
1411+proc tempOf*(var x: Item; t: ^Sym.Type);
1412+var tmp: I64; p: Diag.Pos;
1413+begin
1414+ if inResult and (t = result) then
1415+ inResult := false;
1416+ p := x.pos;
1417+ x := {};
1418+ x.pos := p;
1419+ x.mode := mVar; x.typ := t; x.base := Gen.bSlot; x.chunk := INT(Gen.resultSlot());
1420+ return;
1421+ end;
14081422 tmp := Gen.allocTemp(t^.size, t^.align);
1409- Gen.zeroVar(frameAdr(tmp), t^.size);
14101423 tempItem(x, t, tmp);
14111424 end;
14121425
1426+(* A temporary of type t, all zero: for variants. *)
1427+proc zeroTemp*(var x: Item; t: ^Sym.Type);
1428+begin
1429+ tempOf(x, t);
1430+ Gen.zeroVar(adrOf(x), t^.size);
1431+end;
1432+
1433+(* size bytes, off bytes into the variable x, cleared *)
1434+proc zeroRange*(x: Item; off, size: I64);
1435+var a: Gen.Adr;
1436+begin
1437+ a := adrOf(x);
1438+ a.off := a.off + off;
1439+ Gen.zeroVar(a, size);
1440+end;
1441+
14131442 proc construct*(var x: Item; c: ^Sym.Obj);
14141443 begin
14151444 zeroTemp(x, c^.typ);
@@ -1418,15 +1447,18 @@
14181447 end;
14191448
14201449 proc setField*(x: Item; f: ^Sym.Obj; var a: Item): ERROR;
1450+var at: Gen.Adr;
14211451 begin
1452+ at := adrOf(x);
1453+ at.off := at.off + f^.val;
14221454 try coerce(a, f^.typ);
14231455 if Sym.isScalar(f^.typ) then
14241456 try value(a);
1425- Gen.popVar(frameAdr(x.off + f^.val), scalarSize(f^.typ));
1457+ Gen.popVar(at, scalarSize(f^.typ));
14261458 else
14271459 if a.vol then return Scan.markAt(a.pos, "can't copy through a volatile pointer"); end;
14281460 try address(a);
1429- Gen.copyTo(frameAdr(x.off + f^.val), f^.typ^.size);
1461+ Gen.copyTo(at, f^.typ^.size);
14301462 end;
14311463 return nil;
14321464 end;
@@ -1607,6 +1639,8 @@
16071639 try coerce(x, result);
16081640 if Sym.inTwoRegs(result) then try pushWords(x);
16091641 elsif Sym.isAggregate(result) then
1642+ (* a record literal made behind the hidden pointer is there already *)
1643+ if (x.base = Gen.bSlot) and (x.chunk = INT(Gen.resultSlot())) and (x.off = 0) then return nil; end;
16101644 if x.vol then return Scan.markAt(x.pos, "can't copy through a volatile pointer"); end;
16111645 try address(x);
16121646 Gen.copyResult(0, result^.size);

src/Parse.raz (history) modified +112 -45

@@ -1005,23 +1005,23 @@
10051005 (* A designator, with any selectors and calls after it. called tells
10061006 whether the last thing done was a call. *)
10071007 proc designator(var x: TItem; var called: BOOL): ERROR;
1008-var o, f: PObj; y, z: TItem; t: PType; start: Diag.Pos;
1008+var o, f: PObj; y, z: TItem; t: PType; start: INT;
10091009 begin
1010- start := Scan.tokPos();
1010+ start := Scan.tokStart();
10111011 o := try qualIdent();
10121012 called := false;
10131013 if o^.cls = Sym.oModule then
1014- return Scan.markAt(Scan.spanFrom(start), say1("{} is a module, not a value", nameOf(o^.name)));
1014+ return Scan.markAt(Scan.spanFromAt(start), say1("{} is a module, not a value", nameOf(o^.name)));
10151015 end;
10161016 try Item.makeItem(x, o);
10171017 if x.mode = Item.mBuiltin then
10181018 try builtin(x);
10191019 called := true;
10201020 elsif x.mode = Item.mCase then
1021- try constructCase(x, o, Scan.spanFrom(start));
1021+ try constructCase(x, o, Scan.spanFromAt(start));
10221022 end;
10231023 repeat
1024- x.pos := Scan.spanFrom(start);
1024+ x.pos := Scan.spanFromAt(start);
10251025 match Scan.tok of
10261026 | sPeriod:
10271027 Scan.next;
@@ -1064,7 +1064,7 @@
10641064 | else: break;
10651065 end;
10661066 until false;
1067- x.pos := Scan.spanFrom(start);
1067+ x.pos := Scan.spanFromAt(start);
10681068 Item.nilTest(x);
10691069 return nil;
10701070 end;
@@ -1129,13 +1129,57 @@
11291129 return nil;
11301130 end;
11311131
1132-(* A record literal: a zeroed temporary, with the fields named filled in. *)
1132+(* The padding of the record type t, the bytes between its fields and
1133+ after the last, cleared in x: a word at a time, so a few stores *)
1134+proc clearPadding(x: TItem; t: PType);
1135+var f: PObj; at, lo, hi: I64;
1136+begin
1137+ at := 0;
1138+ f := t^.fields;
1139+ while true do
1140+ if f # nil then hi := f^.val; else hi := t^.size; end;
1141+ if hi > at then
1142+ lo := at - at mod 8;
1143+ hi := Sym.alignUp(hi, 8);
1144+ if hi > t^.size then hi := t^.size; end;
1145+ Item.zeroRange(x, lo, hi - lo);
1146+ end;
1147+ if f = nil then break; end;
1148+ at := f^.val + f^.typ^.size;
1149+ f := f^.next;
1150+ end;
1151+end;
1152+
1153+(* The fields of the record type t that a literal left out, of which seen
1154+ are the n names it gave, cleared in x *)
1155+proc clearMissing(x: TItem; t: PType; seen: [MaxNames]INT; n: INT);
1156+var f: PObj; i: INT; given: BOOL;
1157+begin
1158+ f := t^.fields;
1159+ while f # nil do
1160+ given := false;
1161+ for i := 0 to n - 1 do
1162+ if seen[i] = f^.name then given := true; end;
1163+ end;
1164+ if not given then Item.zeroRange(x, f^.val, f^.typ^.size); end;
1165+ f := f^.next;
1166+ end;
1167+end;
1168+
1169+(* A record literal: a temporary, or the result's place, with the fields
1170+ named filled in and the rest zero. The temporary is cleared where the
1171+ fields won't write: the padding first, then what the literal left out. *)
11331172 proc recordLiteral(var x: TItem; t: PType): ERROR;
1134-var f: PObj; a: TItem; seen: [MaxNames]INT; n, i: INT;
1173+var f: PObj; a: TItem; seen: [MaxNames]INT; n, i, fields: INT;
11351174 begin
11361175 Scan.next;
1137- Item.zeroTemp(x, t);
1176+ Item.tempOf(x, t);
11381177 n := 0;
1178+ fields := 0;
1179+ f := t^.fields;
1180+ while f # nil do INC(fields); f := f^.next; end;
1181+ if fields > MaxNames then Item.zeroRange(x, 0, t^.size); (* more than seen has room for *)
1182+ else clearPadding(x, t); end;
11391183 if Scan.tok # Scan.sRbrace then
11401184 repeat
11411185 if Scan.tok # Scan.sIdent then return expected("a field"); end;
@@ -1154,6 +1198,7 @@
11541198 Scan.next;
11551199 until false;
11561200 end;
1201+ if fields <= MaxNames then clearMissing(x, t, seen, n); end;
11571202 return expect(Scan.sRbrace);
11581203 end;
11591204
@@ -1248,7 +1293,7 @@
12481293 since what follows is the code for an error that is nil. *)
12491294 proc tryCall(var x: TItem): ERROR;
12501295 var
1251- called: BOOL; c: Gen.CallInfo; start, at: Diag.Pos; res: PType; last: PObj; slot: I64; ok: INT;
1296+ called: BOOL; c: Gen.CallInfo; start, at: Diag.Pos; res: PType; last: PObj; slot: I64; ok: INT; direct: BOOL;
12521297 begin
12531298 start := Scan.tokPos();
12541299 Scan.next;
@@ -1277,15 +1322,22 @@
12771322 return Scan.markAt(x.pos, say1("try needs a call that returns an ERROR last, and this returns {}", Sym.typeName(x.typ)));
12781323 end;
12791324 res := x.typ;
1325+ direct := false;
12801326 if x.mode = Item.mStack then
12811327 (* an ERROR alone *)
1282- slot := Gen.allocTemp(8, 8);
1283- Gen.popVar(Item.frameAdr(slot), 8);
1328+ direct := numDefers = 0;
1329+ if not direct then
1330+ slot := Gen.allocTemp(8, 8);
1331+ Gen.popVar(Item.frameAdr(slot), 8);
1332+ end;
12841333 x.mode := Item.mNone; x.typ := Sym.tNone;
12851334 elsif x.mode = Item.mWords then
12861335 (* two words, the error on top *)
1287- slot := Gen.allocTemp(8, 8);
1288- Gen.popVar(Item.frameAdr(slot), 8);
1336+ direct := numDefers = 0;
1337+ if not direct then
1338+ slot := Gen.allocTemp(8, 8);
1339+ Gen.popVar(Item.frameAdr(slot), 8);
1340+ end;
12891341 x.mode := Item.mStack; x.typ := res^.fields^.typ;
12901342 else
12911343 (* several, in a temporary: the error is where it is *)
@@ -1295,22 +1347,28 @@
12951347 if res^.len = 2 then try Item.field(x, res^.fields); else x.typ := withoutLast(res); end;
12961348 end;
12971349 ok := Gen.NoLabel;
1298- Gen.pushVar(Item.frameAdr(slot), 8, false, Gen.kWord);
1299- Gen.jumpIf(ok, false);
1300- if numDefers > 0 then Gen.tryAlign(); end;
1301- runDefers(0);
1302- Gen.tryReturn(slot);
1350+ if direct then
1351+ (* nothing to defer: the error is tested and returned from the
1352+ register it is in, with no slot *)
1353+ Gen.tryReturnFrom(Gen.tryTest(ok));
1354+ else
1355+ Gen.pushVar(Item.frameAdr(slot), 8, false, Gen.kWord);
1356+ Gen.jumpIf(ok, false);
1357+ if numDefers > 0 then Gen.tryAlign(); end;
1358+ runDefers(0);
1359+ Gen.tryReturn(slot);
1360+ end;
13031361 Gen.fix(ok);
13041362 x.pos := Scan.spanFrom(start);
13051363 return nil;
13061364 end;
13071365
13081366 proc factor(var x: TItem; want: PType): ERROR;
1309-var called, vol, several: BOOL; t: PType; start: Diag.Pos; s: []U8;
1367+var called, vol, several: BOOL; t: PType; start: INT; s: []U8;
13101368 begin
13111369 several := passOn;
13121370 passOn := false;
1313- start := Scan.tokPos();
1371+ start := Scan.tokStart();
13141372 match Scan.tok of
13151373 | sInt, sChar:
13161374 (* only a hex number can be above high(I64), and it is a U64 *)
@@ -1374,7 +1432,7 @@
13741432 end;
13751433 | else: return expected("an expression");
13761434 end;
1377- x.pos := Scan.spanFrom(start);
1435+ x.pos := Scan.spanFromAt(start);
13781436 return nil;
13791437 end;
13801438
@@ -1403,9 +1461,9 @@
14031461 end;
14041462
14051463 proc term(var x: TItem; want: PType): ERROR;
1406-var op: Scan.Sym; y: TItem; L: INT; start: Diag.Pos;
1464+var op: Scan.Sym; y: TItem; L: INT; start: INT;
14071465 begin
1408- start := Scan.tokPos();
1466+ start := Scan.tokStart();
14091467 try factor(x, want);
14101468 while isMulOp() do
14111469 op := Scan.tok;
@@ -1413,19 +1471,19 @@
14131471 try Item.op1(op, x, L);
14141472 try factor(y, nil);
14151473 try Item.op2(op, x, y, L);
1416- x.pos := Scan.spanFrom(start);
1474+ x.pos := Scan.spanFromAt(start);
14171475 end;
14181476 return nil;
14191477 end;
14201478
14211479 proc simpleExpr(var x: TItem; want: PType): ERROR;
1422-var op: Scan.Sym; y: TItem; L: INT; start: Diag.Pos;
1480+var op: Scan.Sym; y: TItem; L: INT; start: INT;
14231481 begin
1424- start := Scan.tokPos();
1482+ start := Scan.tokStart();
14251483 if Scan.tok = Scan.sMinus then
14261484 Scan.next;
14271485 try term(x, nil);
1428- x.pos := Scan.spanFrom(start);
1486+ x.pos := Scan.spanFromAt(start);
14291487 try Item.neg(x);
14301488 else
14311489 try term(x, want);
@@ -1436,7 +1494,7 @@
14361494 try Item.op1(op, x, L);
14371495 try term(y, nil);
14381496 try Item.op2(op, x, y, L);
1439- x.pos := Scan.spanFrom(start);
1497+ x.pos := Scan.spanFromAt(start);
14401498 end;
14411499 return nil;
14421500 end;
@@ -1458,31 +1516,31 @@
14581516
14591517 (* and binds tighter than or, and both below the relations *)
14601518 proc conjunct(var x: TItem; want: PType): ERROR;
1461-var y: TItem; L: INT; start: Diag.Pos;
1519+var y: TItem; L: INT; start: INT;
14621520 begin
1463- start := Scan.tokPos();
1521+ start := Scan.tokStart();
14641522 try relation(x, want);
14651523 while Scan.tok = Scan.sAnd do
14661524 Scan.next;
14671525 try Item.op1(Scan.sAnd, x, L);
14681526 try relation(y, nil);
14691527 try Item.op2(Scan.sAnd, x, y, L);
1470- x.pos := Scan.spanFrom(start);
1528+ x.pos := Scan.spanFromAt(start);
14711529 end;
14721530 return nil;
14731531 end;
14741532
14751533 proc expression(var x: TItem; want: PType): ERROR;
1476-var y: TItem; L: INT; start: Diag.Pos;
1534+var y: TItem; L: INT; start: INT;
14771535 begin
1478- start := Scan.tokPos();
1536+ start := Scan.tokStart();
14791537 try conjunct(x, want);
14801538 while Scan.tok = Scan.sOr do
14811539 Scan.next;
14821540 try Item.op1(Scan.sOr, x, L);
14831541 try conjunct(y, nil);
14841542 try Item.op2(Scan.sOr, x, y, L);
1485- x.pos := Scan.spanFrom(start);
1543+ x.pos := Scan.spanFromAt(start);
14861544 end;
14871545 return nil;
14881546 end;
@@ -2194,7 +2252,10 @@
21942252 if (curResult # nil) and curResult^.tuple then
21952253 try returnResults();
21962254 else
2255+ Item.literalInResult((Scan.tok = Scan.sLbrace) and (curResult # nil)
2256+ and (curResult^.form = Sym.fRecord) and Sym.behindPointer(curResult));
21972257 try expression(x, curResult);
2258+ Item.literalInResult(false);
21982259 try Item.returnValue(x);
21992260 end;
22002261 (* the result, one value or two words on top, waits in the frame
@@ -2317,6 +2378,7 @@
23172378 proc varKind(o: PObj): INT;
23182379 var k, i, v: INT;
23192380 begin
2381+ if o^.ind and (o^.reg # 0) then return 0; end; (* the address is in a register, not shown *)
23202382 match o^.typ^.form of
23212383 | fInt: if o^.typ^.signed then k := 1; else k := 2; end;
23222384 | fEnum, fSet: k := 2;
@@ -2338,7 +2400,9 @@
23382400 proc regFit(o: PObj): BOOL;
23392401 var f: Sym.Form;
23402402 begin
2341- if (o^.cls # Sym.oVar) or o^.ind or o^.ext then return false; end;
2403+ if (o^.cls # Sym.oVar) or o^.ext then return false; end;
2404+ (* a parameter passed by its address keeps the address in the register *)
2405+ if o^.ind then return o^.param; end;
23422406 f := o^.typ^.form;
23432407 return (f = Sym.fInt) or (f = Sym.fBool) or (f = Sym.fEnum) or (f = Sym.fPtr) or (f = Sym.fProc)
23442408 or (f = Sym.fError) or (f = Sym.fSlice) or (f = Sym.fReal)
@@ -2415,15 +2479,18 @@
24152479 Scan.setSkipping(true); (* its slips are told when it is compiled *)
24162480 d := 0; loops := 0; afterDot := false; leaf := true; qual := nil;
24172481 repeat
2418- (* a name, or a module's name and one of its exports, that calls *)
2419- if (Scan.tok = Scan.sIdent) and not afterDot then
2420- q := Sym.lookup(Scan.id);
2421- if calls(q) then leaf := false; end;
2422- qual := nil;
2423- if (q # nil) and (q^.cls = Sym.oModule) then qual := q; end;
2424- elsif (Scan.tok = Scan.sIdent) and (qual # nil) then
2425- if (qual^.home = nil) or calls(Sym.find(qual^.home^.scope, Scan.id)) then leaf := false; end;
2426- qual := nil;
2482+ (* a name, or a module's name and one of its exports, that calls;
2483+ once one has, the rest needn't be looked up *)
2484+ if leaf then
2485+ if (Scan.tok = Scan.sIdent) and not afterDot then
2486+ q := Sym.lookup(Scan.id);
2487+ if calls(q) then leaf := false; end;
2488+ qual := nil;
2489+ if (q # nil) and (q^.cls = Sym.oModule) then qual := q; end;
2490+ elsif (Scan.tok = Scan.sIdent) and (qual # nil) then
2491+ if (qual^.home = nil) or calls(Sym.find(qual^.home^.scope, Scan.id)) then leaf := false; end;
2492+ qual := nil;
2493+ end;
24272494 end;
24282495 match Scan.tok of
24292496 | sBegin, sIf, sMatch, sWhile, sFor, sRepeat:

src/README.md (history) modified +14 -20

@@ -23,22 +23,16 @@
2323 script, bytes, fixups and listing, and by `test/AsmDump` on the files
2424 `test/genasm.py` makes: a long run of every instruction the assembler
2525 knows, and a file for each of its errors.
26-`Gen` is tested by `test/GenDump`, a script of calls, valid by
27-construction (an expression pushes its operands and then operates; a
28-statement leaves the stack as it found it), that compiles 80 procedures
29-with every kind of expression, statement, call, check, frame and defer,
30-and the entry point, static and dynamic: the bytes, fixups, line notes
31-and listing must be the same.
32-`Item` is tested by `test/ItemDump`, a script of operands and operations
33-with mistakes among them (a constant, a variable in the frame, a
34-register, a slot, another module's or C's, a string, a procedure, a
35-selector through a pointer, a field, an element or a slice, a call, a
36-`match`, a `for`, `return`, `COPY`, a variant): each step shows what
37-it gave, or its message, and goes on, as the parser does after an
38-error. What each step gave, the messages, and the bytes, fixups, line
39-notes and listing of the code must be the same, over 60 scripts (a
40-run ends at its 20th error, as a compile does). The text its messages
41-point into is `test/ItemDump.txt`.
26+`Gen` and `Item` were tested by `test/GenDump`, a script of calls, valid
27+by construction, that compiles 80 procedures with every kind of
28+expression, statement, call, check, frame and defer, and the entry
29+point, and by `test/ItemDump`, a script of operands and operations with
30+mistakes among them, over 60 scripts (the text its messages point into
31+is `test/ItemDump.txt`): the bytes, fixups, line notes and listing, and
32+the messages, had to be the same as the seed's. They were, until the
33+compiler's code was improved (v0.10.0): `src/` makes better code than
34+the seed, so the dumpers are kept, as a way to read what `Gen` makes,
35+and no longer compared. `src/check.sh` says what is.
4236
4337 `Parse` and `Raz`, the last two units, are tested whole: the seed builds
4438 `src/Raz.raz` into `build/src/raz.src`, and each compiler, run as
@@ -46,15 +40,15 @@
4640 library is found beside the compiler), compiles the library, the
4741 examples, the tools, `src/` itself, every test of `test/` and
4842 `conform/`, and the 348,025-line program of `test/genbench.py`, with the
49-options each test has. The executable, the messages, and the status
50-must be the same for every file: 409 of them, 289 of which are errors.
43+options each test has. The messages and the status must be the same
44+for every file (the executables no longer are, since v0.10.0): 409 of them, 289 of which are errors.
5145 `make seed-bench` gives the speed of both.
5246
5347 `make fixpoint` (`fixpoint.sh`) is the proof that the port is whole:
5448 the seed builds `Raz.raz` (stage 1), stage 1 builds it (stage 2), and
5549 stage 2 builds it again (stage 3). Stages 2 and 3 must be the same
56-file; they are, and so is stage 1, since the seed and the port make the
57-same code. Stage 3 then stands in for `./raz`, and `make check` and
50+file; they are (stage 1 is not, since v0.10.0: the port makes better code
51+than the seed's). Stage 3 then stands in for `./raz`, and `make check` and
5852 `make bench` run on it. Each stage is built by the same command in the
5953 same place, since a program holds the paths it was made from.
6054

src/Scan.raz (history) modified +86 -26

@@ -268,35 +268,86 @@
268268 return p;
269269 end;
270270
271+(* The same from a start that tokStart noted, which costs less than a
272+ whole place: the parser notes one at every level of an expression *)
273+proc tokStart*: INT;
274+begin
275+ return cur.tokPos;
276+end;
277+
278+proc spanFromAt*(a: INT): Diag.Pos;
279+begin
280+ return {f: cur.f, a: a, b: cur.prevEnd};
281+end;
282+
271283 proc curLine*: INT;
272284 begin
273285 return cur.tokLine;
274286 end;
275287
276-(* The line and column of byte a of the file, at or before the current
277- symbol: counted back from the symbol's line, so that it costs only
288+var
289+ (* what lineCol found last, in file lcFile: byte lcAt is in line lcLine,
290+ which starts at lcStart, at column lcCol. The next ask is likely
291+ near it, as the places of the checks of a procedure are told in order,
292+ and a line's statements come one after another. *)
293+ lcFile, lcAt, lcLine, lcStart, lcCol: INT;
294+
295+(* The line and column of byte a of the file: counted from the place last
296+ found, or the current symbol's, back or forward, so that it costs only
278297 the distance. A column counts characters, as Diag's do. *)
279298 proc lineCol*(a: INT): (INT, INT);
280299 var i, line, start, col: INT;
281300 begin
282- line := cur.tokLine;
283- start := cur.tokLineStart;
284- while a < start do
285- DEC(line);
286- DEC(start);
287- while (start > 0) and (cur.buf[start - 1] # '\n') do DEC(start); end;
301+ if lcFile = cur.f then
302+ line := lcLine;
303+ start := lcStart;
304+ i := lcAt;
305+ col := lcCol;
306+ else
307+ line := cur.tokLine;
308+ start := cur.tokLineStart;
309+ i := start;
310+ col := 1;
288311 end;
289- col := 1;
290- for i := start to a - 1 do
291- if (cur.buf[i] & 0C0H) # 80H then INC(col); end;
312+ if a < i then
313+ (* before the place, back to the start of its line, or of the
314+ line before until a is in it *)
315+ i := start;
316+ col := 1;
317+ while a < start do
318+ DEC(line);
319+ DEC(start);
320+ while (start > 0) and (cur.buf[start - 1] # '\n') do DEC(start); end;
321+ end;
322+ i := start;
292323 end;
324+ while i < a do
325+ if cur.buf[i] = '\n' then
326+ INC(line);
327+ start := i + 1;
328+ col := 1;
329+ elsif (cur.buf[i] & 0C0H) # 80H then
330+ INC(col);
331+ end;
332+ INC(i);
333+ end;
334+ lcFile := cur.f;
335+ lcAt := a;
336+ lcLine := line;
337+ lcStart := start;
338+ lcCol := col;
293339 return line, col;
294340 end;
295341
342+(* The column of the current symbol: only its line's start to count
343+ from, which the scanner noted *)
296344 proc curCol*: INT;
297-var col: INT;
345+var i, col: INT;
298346 begin
299- _, col := lineCol(cur.tokPos);
347+ col := 1;
348+ for i := cur.tokLineStart to cur.tokPos - 1 do
349+ if (cur.buf[i] & 0C0H) # 80H then INC(col); end;
350+ end;
300351 return col;
301352 end;
302353
@@ -858,25 +909,33 @@
858909
859910 (* Reads the next symbol *)
860911 proc next*;
861-var c: U8; start, h, v, i: INT;
912+var c: U8; start, h, v, i, p: INT; buf: ^U8;
862913 begin
863- cur.prevEnd := cur.pos;
914+ (* the position and the text are kept in variables, in registers,
915+ while the loops run: cur is in memory, and each step through it
916+ waits for the one before *)
917+ buf := cur.buf;
918+ p := cur.pos;
919+ cur.prevEnd := p;
864920 repeat
865- c := cur.buf[cur.pos];
921+ c := buf[p];
866922 while (c = ' ') or (c = '\t') or (c = '\r') or (c = '\n') do
867923 if c = '\n' then
868924 INC(cur.line);
869- cur.lineStart := cur.pos + 1;
925+ cur.lineStart := p + 1;
870926 end;
871- INC(cur.pos);
872- c := cur.buf[cur.pos];
927+ INC(p);
928+ c := buf[p];
873929 end;
874- if (c = '(') and (cur.buf[cur.pos + 1] = '*') then
930+ if (c = '(') and (buf[p + 1] = '*') then
931+ cur.pos := p;
875932 comment;
933+ p := cur.pos;
876934 c := ' ';
877935 end;
878936 until c # ' ';
879- cur.tokPos := cur.pos;
937+ cur.pos := p;
938+ cur.tokPos := p;
880939 cur.tokLine := cur.line;
881940 cur.tokLineStart := cur.lineStart;
882941 if single[c] # sNull then
@@ -886,13 +945,14 @@
886945 end;
887946 match c of
888947 | 'A'..'Z', 'a'..'z', '_':
889- start := cur.pos;
890- repeat INC(cur.pos); until not nameChar[cur.buf[cur.pos]];
891- if cur.pos - start > MaxIdent then
948+ start := p;
949+ repeat INC(p); until not nameChar[buf[p]];
950+ cur.pos := p;
951+ if p - start > MaxIdent then
892952 lexError(Diag.say("a name has at most {} characters", [Fmt.int(MaxIdent)]));
893953 end;
894- h := intern(cur.buf + start, cur.pos - start);
895- if (cur.pos - start = 1) and (c = '_') then
954+ h := intern(buf + start, p - start);
955+ if (p - start = 1) and (c = '_') then
896956 tok := sBlank;
897957 elsif h < NumWords then
898958 tok := Sym(INT(sAnd) + h);

src/X64.raz (history) modified +20 -0

@@ -699,6 +699,26 @@
699699 opR(0, false, 280FH, x, y, false);
700700 end;
701701
702+(* movdqu: 16 bytes between xmm x and memory, and pxor, which zeroes
703+ xmm x: how Gen copies and clears a record in a few instructions *)
704+proc movdquXM*(x: INT; m: Mem);
705+begin
706+ if listing then say(text2("movdqu", xn(x), mn(m))); end;
707+ opM(0F3H, false, 6F0FH, x, m, false);
708+end;
709+
710+proc movdquMX*(m: Mem; x: INT);
711+begin
712+ if listing then say(text2("movdqu", mn(m), xn(x))); end;
713+ opM(0F3H, false, 7F0FH, x, m, false);
714+end;
715+
716+proc pxorXX*(x: INT);
717+begin
718+ if listing then say(text2("pxor", xn(x), xn(x))); end;
719+ opR(66H, false, 0EF0FH, x, x, false);
720+end;
721+
702722 (* The prefix of a real instruction, and the end of its name: sd, or ss for single *)
703723 proc realPfx(single: BOOL): INT;
704724 begin

src/check.sh modified +9 -34

@@ -92,41 +92,16 @@
9292 echo "x64: $n assembler files, $bad differ"
9393 test $bad = 0
9494
95-# Gen: procedures made by a script of calls (expressions, statements,
96-# calls, frames, checks, defers, the entry point), whose bytes, fixups,
97-# line notes and listing must be the same; once with the static entry
98-# point and once with the dynamic one
99-fpc -O2 -Mobjfpc -Sh- -vew -FUbuild -Fuseed -o$b/gendump.seed src/test/GenDump.pas >/dev/null
100-./raz -Werror -I src -o $b/gendump.src src/test/GenDump.raz
101-for a in "" dyn; do
102- $b/gendump.seed $a >$b/gen.seed
103- $b/gendump.src $a >$b/gen.src
104- cmp $b/gen.seed $b/gen.src
105-done
106-echo "gen ok"
95+# Gen and Item were tested here against the seed's while they were ported,
96+# by the code they made: the same bytes, listings and line notes. Since the
97+# compiler's own code was improved (v0.10.0) that code is no longer the
98+# seed's, so they are tested by what the seed can still check, the
99+# messages and statuses of Parse and Raz below, and by the fixpoint and
100+# the tests of `make check`, on the compiler they make.
107101
108-# Item: operands and operations driven by a script with mistakes in it,
109-# which show their messages and go on; what each step gave, the code
110-# made and the messages must be the same. A run ends at the 20th error,
111-# as a compile does, so the script changes with each argument.
112-fpc -O2 -Mobjfpc -Sh- -vew -FUbuild -Fuseed -o$b/itemdump.seed src/test/ItemDump.pas >/dev/null
113-./raz -Werror -I src -o $b/itemdump.src src/test/ItemDump.raz
114-n=0; bad=0
115-for a in $(seq 0 59); do
116- s1=0; s2=0
117- $b/itemdump.seed $a >$b/seed.out 2>$b/seed.err || s1=$?
118- $b/itemdump.src $a >$b/src.out 2>$b/src.err || s2=$?
119- n=$((n + 1))
120- if [ $s1 != $s2 ] || ! cmp -s $b/seed.out $b/src.out || ! cmp -s $b/seed.err $b/src.err; then
121- echo "differs: item script $a (status $s1 and $s2)"; bad=$((bad + 1))
122- fi
123-done
124-echo "item: $n scripts, $bad differ"
125-test $bad = 0
126-
127102 # Parse and Raz: the compiler this makes, built by the seed, compiles
128-# what the seed compiles, to the same file, with the same messages and
129-# status: every example, test and tool, and the library, with each
103+# what the seed compiles, with the same messages and status (the files
104+# are no longer the same, as it makes better code): every example, test and tool, and the library, with each
130105 # one's own options. Both sides run as build/cmp/raz, since a program
131106 # holds the paths it was made from and the library is found beside the
132107 # compiler.
@@ -169,7 +144,7 @@
169144 for f in $files; do
170145 x=$(dirname $f | tr / _).$(basename $f .raz)
171146 n=$((n + 1))
172- for e in "" .out .err .status; do
147+ for e in .out .err .status; do
173148 [ -f $c/seed/$x$e ] || [ -f $c/src/$x$e ] || continue
174149 if ! cmp -s $c/seed/$x$e $c/src/$x$e; then
175150 echo "differs: $f ($x$e)"; bad=$((bad + 1)); break