raz / commit 6b556e95

commit
6b556e9578ae74e75aeb4b9e824eeb9954a65a91
author
Luis <42945842+ldiaz94@users.noreply.github.com>
date
parent
af361ec5
doc/ir.md: the intermediate form, a draft for review

A stack code, as P-code was: today's stack machine through rax written
down with the machine taken out. Four kinds of value, word, long and
the two reals; loads and stores by type, volatile and misaligned ones
apart; checks that carry their place; labels at which every way in
agrees on the stack, so that a back end keeps the stack in registers
as Wirth's compilers do; calls with their arguments on the stack, the
target's convention left to the back end. What an object file holds,
and three questions left open.

patch · log

2 files changed, +329 -2

PLAN.md (history) modified +3 -2

@@ -66,7 +66,8 @@
6666
6767 ## Proposed, v0.6.0: raz to be rebuilt by anyone
6868
69-Under way: step 2, the report's draft 2026-10.11, is in review. The freeze doesn't hold for this
69+Under way: step 3, `doc/ir.md`, is in review; the report's draft
70+2026-10.11 is agreed. The freeze doesn't hold for this
7071 work, by the owner's word.
7172
7273 **For:** a language a person alone can implement again, from the
@@ -104,7 +105,7 @@
104105 target may leave out; object files, a module's interface and its
105106 IR, and a generic's instances in them, named by their arguments
106107 and the fingerprints they were built from.
107-- [ ] 3. The IR, in its own document, for review: proposed, a stack
108+- [x] 3. The IR, in its own document, `doc/ir.md`, for review: proposed, a stack
108109 code close to what the parser asks of `gen` today, with types
109110 and places, so that a back end turns its stack into registers and
110111 an interpreter of it stays small.

doc/ir.md added +326 -0

@@ -0,0 +1,326 @@
1+# The intermediate form of raz
2+
3+A draft, for review before any code (PLAN.md, v0.6.0, step 3).
4+
5+This is the code an object file holds (report, section 10): what the
6+parser makes of a module's procedures, before any machine is chosen.
7+A back end turns it into one target's machine code; an interpreter
8+could run it as it is. It is this compiler's choice, not the
9+language's (report, appendix A): another implementation may keep
10+object files of its own.
11+
12+It is a stack code, as Wirth's P-code was. The parser already
13+compiles to a stack machine through `rax` (`doc/compiler.md`); the
14+intermediate form is that stack machine written down, with the
15+machine taken out. Each call the parser makes into `gen.pas` today
16+becomes one or a few instructions here.
17+
18+## What it is for
19+
20+- **One parser, many machines.** The parser emits this, and knows
21+ nothing of x86-64. A port writes a back end: instruction selection
22+ and encoding, a few thousand lines at most, and leaves the rest of
23+ the compiler alone.
24+- **Object files.** A module is compiled once into its interface and
25+ this code, and linked into any program later (report, section 10).
26+- **Registers without an allocator.** A back end keeps the stack in a
27+ stack of registers, as Wirth's compilers do: the value at depth `d`
28+ lives in register `R[d]`. Nothing has to be allocated, and no
29+ instruction moves a value the program didn't ask to move.
30+- **An interpreter as a fallback.** Every instruction is simple
31+ enough that an interpreter of the whole form is a few hundred lines,
32+ in raz or in anything else: a way to run raz on a machine before it
33+ has a back end.
34+
35+## What it leaves out
36+
37+No SSA, no basic blocks, no optimisation; no types beyond what a
38+machine needs (the parser has checked everything else); no syntax
39+tree. Sizes and layouts are already worked out: an object file is
40+made for one target, its `INT` and its C layout. The same form serves
41+every target, but one object file serves one.
42+
43+## Values
44+
45+The stack holds values of four kinds:
46+
47+| Kind | What |
48+|---|---|
49+| `w` | a word: an integer as big as an address, `INT`, `UINT`, a pointer, a procedure, an `ERROR`, a `BOOL` or an enumeration |
50+| `l` | a 64-bit integer, `I64` and `U64`; the same as `w` where an address is 8 bytes |
51+| `f` | an `F32` |
52+| `d` | an `F64` |
53+
54+A narrower integer (`I8` to `I32`, `U8` to `U32`) is a `w` on the
55+stack, extended by its sign or by zeros as its type says, and cut back
56+when it is stored. Records, arrays, slices and variants are never on
57+the stack: their addresses are.
58+
59+An instruction names the kinds it works on after a dot: `add.w`,
60+`add.l`, `add.d`. Signed and unsigned are told apart only where they
61+differ: `div.s` and `div.u`, `lt.s` and `lt.u`, `shr.s` and `shr.u`.
62+
63+## A procedure
64+
65+```
66+proc Name.f params: w w results: w frame: 32 align 16
67+ ...
68+end
69+```
70+
71+`params` and `results` are the kinds of the procedure's scalar
72+parameters and results, in order; a record, array, slice or variant
73+parameter is a `w`, its address. `frame` is the size of the frame,
74+whose slots the parser has laid out: its parameters, its variables,
75+and the temporaries of each statement. `frame k` pushes the address
76+of the slot at offset `k`.
77+
78+On entry the parameters are already in their slots, put there by the
79+back end's prologue; the frame is zero everywhere else (report,
80+section 4). A procedure returns with `ret`, taking its results from
81+the stack, as many as `results` says. A procedure with several
82+results, or a result that isn't a scalar, has a hidden first
83+parameter, the address to put them at, and the parser writes them
84+there itself; such a procedure's `results` is empty. This is the rule
85+of today's compiler (CLAUDE.md, "several results come back through a
86+hidden pointer"), and C's rule for a struct.
87+
88+## The instructions
89+
90+Each one takes its operands off the stack and pushes its result, the
91+operand pushed last being the right one: `const.w 7; const.w 2; sub.w`
92+leaves 5. `pos` is a place in the source, as a line and a column.
93+
94+**Constants and addresses**
95+
96+| Instruction | Does |
97+|---|---|
98+| `const.w n`, `const.l n`, `const.f x`, `const.d x` | pushes the constant |
99+| `frame k` | the address of the frame slot at offset `k` |
100+| `addr sym+k` | the address of a chunk of the program (a module variable, a string, a procedure, an `ERROR`), plus `k` |
101+| `extern name` | the address of a C symbol (report, section 9) |
102+| `drop` | throws the top value away |
103+| `dup` | pushes the top value again |
104+
105+**Memory**
106+
107+| Instruction | Does |
108+|---|---|
109+| `load.t` | takes an address, pushes the value there, of type `t`: `i8`, `u8`, `i16`, `u16`, `i32`, `u32`, `i64`, `w`, `f`, `d` |
110+| `store.t` | takes an address and a value, stores the value there |
111+| `vload.t`, `vstore.t` | the same, volatile: exactly one access of exactly that size, in this order among the volatile ones (report, section 7.6) |
112+| `uload.t`, `ustore.t` | the same, at an address that may be misaligned: a field of a packed record (report, section 5.5) |
113+| `copy n a` | takes a destination and a source, copies `n` bytes, both aligned to `a` |
114+| `zero n a` | takes an address, zeroes `n` bytes aligned to `a` |
115+
116+**Arithmetic.** On `w` and `l`: `add`, `sub`, `mul`, `div.s`, `div.u`,
117+`mod.s`, `mod.u`, `and`, `or`, `xor`, `shl`, `shr.s`, `shr.u`, `neg`,
118+`not`. On `f` and `d`: `add`, `sub`, `mul`, `div`, `neg`. All of them
119+wrap, and a shift takes its count modulo the width (report, section
120+6.1). `div` and `mod` on integers carry a `pos`: dividing by zero, or
121+the smallest integer by -1, stops the program there (report, section
122+10), by the machine's trap or by a test the back end puts in on a
123+machine that doesn't trap, as RISC-V doesn't.
124+
125+**Comparisons** push a `w`, 0 or 1: `eq`, `ne`, and `lt`, `le`, `gt`,
126+`ge` with `.s` or `.u` on integers, plain on reals, where they are
127+IEEE's (report, section 6.3).
128+
129+**Conversions**
130+
131+| Instruction | Does |
132+|---|---|
133+| `cut.t` | a `w` or `l` cut to the integer type `t` and extended back by its sign or zeros: what `I8(x)` does, and what keeps `U8` arithmetic wrapping at 8 bits |
134+| `wide.s`, `wide.u` | a `w` to an `l`, by sign or by zeros; nothing where they are the same |
135+| `narrow` | an `l` to a `w`, cut |
136+| `itof.s.k`, `itof.u.k` | an integer of kind `w` or `l` to the real kind `k` |
137+| `ftoi.k` | a real to an `l`, toward zero; a NaN or a value out of range gives the smallest `I64` (report, section 6.7) |
138+| `ftod`, `dtof` | `F32` to `F64` and back |
139+
140+**Checks** carry a `pos`; a failed one calls `Rt.fail` with what
141+failed (report, section 6.5).
142+
143+| Instruction | Does |
144+|---|---|
145+| `check.index pos` | takes an index and a length; stops the program unless `0 <= index < length` by value; leaves the index, as a `w` |
146+| `check.slice pos` | takes `lo`, `hi` and a length; stops the program unless `0 <= lo <= hi <= length`; leaves `lo` and `hi` |
147+| `check.order pos` | takes `lo` and `hi`; stops the program unless `lo <= hi` (a slice of a pointer) |
148+| `check.enum n name pos` | takes a `w`; stops the program unless it is below `n`, the number of names of the enumeration `name` |
149+| `check.nil pos` | looks at the top value, a pointer or a procedure, without taking it; stops the program if it is `nil` |
150+
151+A module that says `check off;` has no `check.index`, `check.slice`
152+or `check.order` in its code. `check.nil` comes before every
153+dereference and every call through a procedure value; a back end for
154+a machine that traps on a low address may make it nothing.
155+
156+**Control.** Labels are numbers, one set to each procedure.
157+
158+| Instruction | Does |
159+|---|---|
160+| `label n` | marks a place |
161+| `jump n` | goes there |
162+| `jz n`, `jnz n` | takes a `w`, and goes there if it is zero, or not |
163+| `line pos` | the statement that starts here begins at `pos`; it goes into the table of lines, for the debugger and the trap report |
164+| `gosub n` | runs the code at label `n`, in this same frame, until its `back`, then goes on after the `gosub` |
165+| `back` | returns from a `gosub` |
166+
167+At a `label`, every way in brings the same values on the stack, of the
168+same kinds. Most labels are reached with the stack empty; the one at
169+the end of `a and b` used as a value is reached with one `w`. A back
170+end keeping the stack in registers therefore finds each value in the
171+same register whichever way it came.
172+
173+**Calls**
174+
175+| Instruction | Does |
176+|---|---|
177+| `call sym` | calls a procedure of the program; its arguments are on the stack, the first pushed first, and its results replace them |
178+| `calli sig` | the same, through a procedure value pushed after the arguments; `sig` gives the kinds of its parameters and results |
179+| `callc name sig` | calls a C procedure (report, section 9), by C's convention, `...` and all |
180+| `ret` | returns, with the procedure's results on the stack |
181+
182+A record, array, slice or variant passed by value goes as the address
183+of a copy the caller makes (`copy`, then the temporary's address), as
184+today. Arguments are worked out left to right, onto the stack, so
185+working out one can't disturb another: the back end, not the parser,
186+moves them into the target's registers.
187+
188+**The rest**
189+
190+| Instruction | Does |
191+|---|---|
192+| `cas.t`, `xchg.t`, `xadd.t` | the atomic built-ins (report, section 6.8), on an address and one or two values |
193+| `fence` | a full barrier |
194+| `syscall n` | a Linux system call with `n` arguments; only for Linux targets |
195+| `argc`, `argv` | the command line (report, section 6.8) |
196+
197+## Code procedures and assembly
198+
199+A procedure written in machine code, or in assembly (PLAN.md, step
200+9b), isn't in this form: its bytes are the target's. The object file
201+keeps them as they are, with the name of the target they are for, and
202+a back end for another target rejects them. This is why a module that
203+holds machine code comes in one file per target (report, section 3).
204+
205+## Statements, as they come out
206+
207+What the parser emits for a few statements, the frame offsets made
208+up:
209+
210+```
211+x := a[i] + 1; (* a: [10]I64, i: I64, x: I64; all locals *)
212+
213+ line 12:5
214+ frame 0 (* x's slot: the destination first, section 7.5 *)
215+ frame 16 (* a *)
216+ frame 8 (* i *)
217+ load.i64
218+ const.w 10
219+ check.index 12:14
220+ const.w 8
221+ mul.w
222+ add.w (* the element's address *)
223+ load.i64
224+ const.l 1
225+ add.l
226+ store.i64
227+```
228+
229+```
230+if p # nil then p^.n := 0; end; (* p: ^Node, n at offset 8 *)
231+
232+ line 13:5
233+ frame 24
234+ load.w
235+ const.w 0
236+ ne.w
237+ jz 1
238+ line 13:21
239+ frame 24
240+ load.w
241+ check.nil 13:21
242+ const.w 8
243+ add.w
244+ const.l 0
245+ store.i64
246+ label 1
247+```
248+
249+A back end keeping the stack in four registers turns the second into,
250+on x86-64:
251+
252+```
253+mov rax, [rbp-24]
254+test rax, rax
255+je L1
256+mov rax, [rbp-24] ; check.nil: nothing, the machine traps on nil
257+mov qword [rax+8], 0
258+L1:
259+```
260+
261+where today's compiler pushes and pops. A back end may match small
262+patterns such as `frame k; load.w` (one instruction on most machines)
263+or a comparison followed by `jz` (a compare and a branch), and that is
264+all the optimising it does.
265+
266+## Object files
267+
268+An object file is a module's, for one target. It holds, in this order:
269+
270+1. **A header**: the module's name, the target, the version of this
271+ form, and the fingerprint of the module's interface.
272+2. **Its imports**: each module it read the interface of, with that
273+ interface's fingerprint when it was compiled. The object file is
274+ current while each of those is still the one there, and its source
275+ hasn't changed (report, section 10).
276+3. **Its interface**: what it exports, as an importer needs it: its
277+ constants with their values, its types with their layouts, its
278+ variables, and its procedures' signatures. An importer reads this,
279+ never the source.
280+4. **Its chunks**: each procedure in this form; each module variable
281+ as a size and an alignment; each string and `ERROR` as its bytes.
282+ A chunk is named, so that the linker finds it from other object
283+ files.
284+5. **Its instances**: each instance of a generic module it made, its
285+ chunks named by the generic module, its arguments and the
286+ fingerprints they were built from (report, section 10). The linker
287+ keeps one of each name.
288+6. **Its places**: the lines of its statements and the places of its
289+ checks, for messages, the trap report and the debugger.
290+
291+Numbers are written as LEB128, the variable-length encoding of
292+WebAssembly and DWARF; names as a length and their bytes. A program
293+is linked from object files alone: the linker reads them, marks what
294+the entry point reaches (tree shaking, as today), hands each live
295+procedure to the back end, and writes the executable.
296+
297+## The interpreter
298+
299+An interpreter keeps a stack of values, a frame per call, and memory
300+laid out as the object file's target says. Each instruction is a few
301+lines of it; `callc` and `syscall` are the only ones that need the
302+machine under it. It is not part of v0.6.0. It is here so that the
303+form stays small enough to have one: every instruction added must be
304+easy to interpret, or it doesn't belong.
305+
306+## Open questions
307+
308+1. **Locals in registers.** The form reaches every variable through
309+ `frame k`, so a back end can keep the stack in registers, but not a
310+ variable. Keeping variables in registers too (the next step in
311+ speed) needs to know which variables never have their address
312+ taken. The parser could mark them in the procedure's header at its
313+ end, since it has seen every `ADR` by then. Proposed: leave it out
314+ of v0.6.0, and keep room in the header for it.
315+2. **Text or binary.** The object file is binary, for speed. A text
316+ form, as written above, is what `raz -S` would print, and what the
317+ tests of the back end compare. Proposed: both, the text one only
318+ for reading.
319+3. **Statements deferred.** The parser compiles a deferred statement
320+ once, as a piece of its procedure that ends in `back`, and calls it
321+ with `gosub` at each way out of its list, newest first, as today's
322+ compiler does with a call inside the procedure. The other way,
323+ compiling it again at each way out, needs no `gosub` but makes the
324+ code bigger and the parser read the statement more than once.
325+ Proposed: keep `gosub`, which costs an interpreter a stack of places
326+ to go back to.