raz / commit 596c810a

commit
596c810a869276216bd222ece75c8df55949f991
author
Luis <42945842+ldiaz94@users.noreply.github.com>
date
parent
042ee2e2
src/ is the compiler in raz; the Pascal seed moves to seed/

git mv src seed, self src, and every path in the Makefile, scripts, tests and
docs follows. The seed is frozen: it builds src/ the first time and is the
reference src/'s units are tested against, until it is dropped. make check,
make self and make fixpoint pass as before.

patch · log

104 files changed, +29369 -29366

CLAUDE.md modified +7 -5

@@ -131,12 +131,14 @@
131131 a link in its `mods`. A test or example without `.expect` is only
132132 compiled (`examples/Window.raz` needs a display).
133133
134-## The seed and self
134+## The compiler and the seed
135135
136-`src/`, the Free Pascal compiler, is the **seed**. `self/` is its port
137-to raz (`PLAN.md`, "Self"): one module to a seed unit, the same names.
138-Never edit the seed to suit the port; a difference found goes on the
139-plan, for the owner.
136+`src/` is the compiler, in raz (`PLAN.md`, "Self"): one module to a
137+seed unit, the same names. `seed/`, the Free Pascal compiler it was
138+ported from, is the **seed**: frozen at its last version, kept to build
139+`src/` the first time and as the reference its units are tested
140+against, and to be dropped in time. Never edit the seed; a difference
141+found goes on the plan, for the owner.
140142
141143 ## Readings of the report already taken
142144

Makefile (history) modified +16 -16

@@ -1,11 +1,11 @@
1-# Builds the compiler, raz, from src/ into the repository's root; the
1+# Builds the compiler, raz, from seed/ into the repository's root; the
22 # library it needs is lib/, beside it.
33
44 FPC = fpc
55 FPCFLAGS = -O2 -Mobjfpc -Sh- -vew -FUbuild
66
7-raz: src/*.pas build/version.inc | build
8- $(FPC) $(FPCFLAGS) -Fibuild -FE. -oraz src/raz.pas
7+raz: seed/*.pas build/version.inc | build
8+ $(FPC) $(FPCFLAGS) -Fibuild -FE. -oraz seed/raz.pas
99
1010 # The version is git's name for the commit; the file changes only when
1111 # that does, so raz isn't rebuilt for nothing.
@@ -15,14 +15,14 @@
1515
1616 FORCE:
1717
18-units: src/*.pas | build
19- for u in diag scan sym chunk x64 link elf; do $(FPC) $(FPCFLAGS) src/$$u.pas || exit 1; done
18+units: seed/*.pas | build
19+ for u in diag scan sym chunk x64 link elf; do $(FPC) $(FPCFLAGS) seed/$$u.pas || exit 1; done
2020
2121 # tests of the parts below the parser, built from test/
2222 tests: units
23- $(FPC) $(FPCFLAGS) -Fusrc -obuild/scantest test/scantest.pas
24- $(FPC) $(FPCFLAGS) -Fusrc -obuild/enctest test/enctest.pas
25- $(FPC) $(FPCFLAGS) -Fusrc -obuild/handtest test/handtest.pas
23+ $(FPC) $(FPCFLAGS) -Fuseed -obuild/scantest test/scantest.pas
24+ $(FPC) $(FPCFLAGS) -Fuseed -obuild/enctest test/enctest.pas
25+ $(FPC) $(FPCFLAGS) -Fuseed -obuild/handtest test/handtest.pas
2626 build/handtest build/hand && build/hand; test $$? = 42
2727
2828 build:
@@ -35,17 +35,17 @@
3535 check: raz build/raz-lib.3
3636 test/check.sh
3737
38-# the raz compiler in raz, self/, tested against the seed's units
38+# the raz compiler in raz, src/, tested against the seed's units
3939 self: raz | build
40- self/check.sh
40+ src/check.sh
4141
4242 self-bench: raz | build
43- self/bench.sh
43+ src/bench.sh
4444
45-# the seed builds self/, that builds self/, that builds it again: the
45+# the seed builds src/, that builds src/, that builds it again: the
4646 # last two must be the same file; check and bench then run on it
4747 fixpoint: raz | build
48- self/fixpoint.sh
48+ src/fixpoint.sh
4949
5050 # line numbers: gdb stops at a line and names it
5151 gdb: raz
@@ -81,15 +81,15 @@
8181 # formatted already
8282 fmt: raz | build
8383 ./raz -o build/Pretty tools/Pretty.raz
84- @fail=0; for f in lib/*.raz examples/*.raz tools/*.raz self/*.raz self/test/*.raz; do \
84+ @fail=0; for f in lib/*.raz examples/*.raz tools/*.raz src/*.raz src/test/*.raz; do \
8585 build/Pretty $$f | cmp -s - $$f || { echo "not formatted: $$f"; fail=1; }; \
8686 done; test $$fail = 0
8787
8888 # lines of the compiler, by rloc: each file's blank, comment and code,
8989 # then the lines of code in all
9090 loc:
91- @rloc -f src/*.pas
92- @rloc -c src/*.pas
91+ @rloc -f seed/*.pas
92+ @rloc -c seed/*.pas
9393
9494 # raz-lib(3), the library's manual page, made by tools/Doc.raz from
9595 # its sources, in the order of the report's section 11

PLAN.md (history) modified +8 -8

@@ -12,10 +12,10 @@
1212 ## Self: the compiler in raz (under way)
1313
1414 For: a compiler written in raz that compiles itself, so that raz needs
15-no Free Pascal. The Pascal compiler in `src/` is the **seed**: it is
15+no Free Pascal. The Pascal compiler in `seed/` is the **seed**: it is
1616 never edited for this, and stays the one `make check` builds. The new
17-compiler lives in `self/`, one raz module to a seed unit, the same
18-names, and has its own targets; nothing in `src/` or `lib/` changes.
17+compiler lives in `src/`, one raz module to a seed unit, the same
18+names, and has its own targets; nothing in `seed/` or `lib/` changes.
1919
2020 The language gained `try` (report 2026-10.20) for this: the parser's
2121 errors return an `ERROR` (`Scan.Failed`) that `try` passes up to where
@@ -39,13 +39,13 @@
3939 builds, tested by compiling 409 programs, the library and the compiler
4040 itself with both and comparing the executables, messages and status;
4141 452,000 lines a second, the seed's 815,000.
42-5. Fixpoint (done: `self/fixpoint.sh`, `make fixpoint`): the seed builds `self`, that builds `self`, that builds
43- `self` again, and the last two are byte for byte the same (all
42+5. Fixpoint (done: `src/fixpoint.sh`, `make fixpoint`): the seed builds `src`, that builds `src`, that builds
43+ `src` again, and the last two are byte for byte the same (all
4444 three are, 547,000 bytes: the seed and this compiler make the same
45- code from `self/`). `make check` passes on the compiler it made,
45+ code from `src/`). `make check` passes on the compiler it made,
4646 661 tests, and `make bench` gives 493,000 to 870,000 lines a second.
47- Then the seed's last tag is the bootstrap, and the split of `src/` from
48- the rest is the owner's to decide.
47+ Then `seed/` is frozen and `self/` is `src/` (the owner's word,
48+ 2026-10-13); the seed is dropped in time, its last tag the bootstrap.
4949
5050 Done when step 5 passes with `make check` and `make bench` on the
5151 compiler it made, and the budget of lines kept.

README.md (history) modified +2 -1

@@ -36,7 +36,8 @@
3636 | `doc/raz.md` | The language report: the definition of raz |
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/` |
39-| `src/` | The compiler, in Free Pascal |
39+| `src/` | The compiler, in raz |
40+| `seed/` | The first compiler, in Free Pascal: frozen, it builds `src/` the first time |
4041 | `lib/` | The library, in raz; the compiler finds it beside itself |
4142 | `examples/` | Small programs, each with the output it should give |
4243 | `tools/Doc.raz` | Prints what a module exports, with its comments |

doc/book/PLAN.md modified +3 -3

@@ -8,7 +8,7 @@
88
99 ## Read first
1010 - CLAUDE.md, doc/raz.md (the report), doc/compiler.md, README.md.
11-- src/*.pas, the whole compiler (about 5,000 lines), and enough of lib/
11+- seed/*.pas, the whole compiler (about 5,000 lines), and enough of lib/
1212 (Rt, Heap, Mem, Thread, Sys) to explain the runtime.
1313 - The tiza skill, for drawings.
1414
@@ -75,13 +75,13 @@
7575 run by `make check`. It must:
7676 - compile and run every raz example marked as runnable and compare the
7777 expected output written in the book;
78- - confirm every quoted Pascal excerpt still matches src/, quoted by
78+ - confirm every quoted Pascal excerpt still matches seed/, quoted by
7979 unit and routine name, never by line number;
8080 - regenerate or verify the cleaned disassembly.
8181 The goal: when the compiler changes, `make check` fails rather than
8282 the book going quietly wrong.
8383 - CI (.github/workflows/): on a push to main that touches doc/book/**,
84- src/** or lib/**, build the epub and replace the file on a standing
84+ seed/** or lib/**, build the epub and replace the file on a standing
8585 prerelease tagged `book` (gh release upload --clobber), so the owner
8686 has a fixed URL to open on an iPad. Tagged releases also attach that
8787 version's epub.

doc/compiler.md (history) modified +11 -11

@@ -10,17 +10,17 @@
1010
1111 | File | Lines | Code | What |
1212 |---|---|---|---|
13-| `src/diag.pas` | 316 | 233 | Messages: positions, source excerpts, colour, counts |
14-| `src/scan.pas` | 886 | 747 | Symbols, literals, comments, positions |
15-| `src/sym.pas` | 646 | 528 | Types, objects, scopes, layout |
16-| `src/chunk.pas` | 318 | 246 | The compiled program: chunks, fixups, line notes |
17-| `src/x64.pas` | 1,208 | 998 | The instruction encoder, jumps within a procedure, the assembler |
18-| `src/gen.pas` | 2,322 | 1,670 | The stack machine, for x86-64: values, operations, checks, calls, frames |
19-| `src/item.pas` | 1,575 | 1,299 | Items: types, constants, variables, operators, conversions, calls |
20-| `src/parse.pas` | 3,280 | 2,851 | Declarations, statements, expressions, built-ins, recovery, warnings |
21-| `src/link.pas` | 334 | 258 | Tree shaking, layout, patching, the places |
22-| `src/elf.pas` | 373 | 294 | Static and dynamic ELF, symbol table, line numbers |
23-| `src/raz.pas` | 245 | 188 | The command line |
13+| `seed/diag.pas` | 316 | 233 | Messages: positions, source excerpts, colour, counts |
14+| `seed/scan.pas` | 886 | 747 | Symbols, literals, comments, positions |
15+| `seed/sym.pas` | 646 | 528 | Types, objects, scopes, layout |
16+| `seed/chunk.pas` | 318 | 246 | The compiled program: chunks, fixups, line notes |
17+| `seed/x64.pas` | 1,208 | 998 | The instruction encoder, jumps within a procedure, the assembler |
18+| `seed/gen.pas` | 2,322 | 1,670 | The stack machine, for x86-64: values, operations, checks, calls, frames |
19+| `seed/item.pas` | 1,575 | 1,299 | Items: types, constants, variables, operators, conversions, calls |
20+| `seed/parse.pas` | 3,280 | 2,851 | Declarations, statements, expressions, built-ins, recovery, warnings |
21+| `seed/link.pas` | 334 | 258 | Tree shaking, layout, patching, the places |
22+| `seed/elf.pas` | 373 | 294 | Static and dynamic ELF, symbol table, line numbers |
23+| `seed/raz.pas` | 245 | 188 | The command line |
2424
2525 Every file opens with a comment that says what it is, what it depends
2626 on and what it leaves out. Read those first; they are the map.

seed/chunk.pas added +318 -0

@@ -0,0 +1,318 @@
1+{ chunk.pas: the compiled program, before it is linked.
2+
3+ The code of a program is a set of chunks: one per procedure, module
4+ variable and string. A chunk's bytes go in one of three sections:
5+ text (code), rodata (strings and other constants), bss (variables,
6+ which are all zero). A reference from code to another chunk (a call,
7+ or an address) is a fixup, patched once the linker has placed every
8+ chunk. Line notes say which place in the source the code from each
9+ point on is for.
10+
11+ Nothing here depends on the machine: text is bytes, written by the
12+ encoder for the target (x64.pas).
13+
14+ Depends on: scan, for errors.
15+ Leaves out: the instructions; that is x64.pas. }
16+
17+unit chunk;
18+
19+{$mode objfpc}{$H-}
20+
21+interface
22+
23+uses scan, diag;
24+
25+type
26+ TSection = (secText, secRodata, secBss);
27+
28+ TChunk = record
29+ sec: TSection;
30+ start, size, align: longint; { in its section's buffer }
31+ firstFix, numFix: longint; { its fixups: text's in fixups, rodata's in dataFixups }
32+ module, name: longint; { for the symbol table; -1 if none }
33+ adr: int64; { its address, set by the linker }
34+ live: boolean; { reached from the entry point }
35+ ext: boolean; { bss: the address of a C symbol, its name }
36+ reals: boolean; { code: computes with reals, first at realsAt }
37+ 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 }
40+ end;
41+
42+ { A place in the source whose code starts at a place in text: for
43+ gdb, and for Rt to say where a failed check or a signal was }
44+ TLine = record
45+ at, chunk: longint; { the place in text, and its chunk }
46+ path, line, col: longint; { the file's path, interned, the line and column }
47+ end;
48+
49+ { A variable of a procedure, for the trap report: Rt shows it, by
50+ kind, from its place in the frame }
51+ TVarNote = record
52+ chunk, name: longint;
53+ off: longint; { from the frame pointer }
54+ kind: longint; { how Rt shows it: see link.pas }
55+ end;
56+
57+ TFixup = record
58+ at: longint; { the 32-bit field, as an offset in text; in
59+ dataFixups, the 64-bit one, from its chunk's start }
60+ chunk: longint; { the chunk it refers to }
61+ addend: longint; { added to the chunk's address }
62+ end;
63+
64+ PChunks = ^TChunkArray;
65+ TChunkArray = array[0..MaxInt div SizeOf(TChunk) - 1] of TChunk;
66+ PLines = ^TLineArray;
67+ TLineArray = array[0..MaxInt div SizeOf(TLine) - 1] of TLine;
68+ PFixups = ^TFixupArray;
69+ TFixupArray = array[0..MaxInt div SizeOf(TFixup) - 1] of TFixup;
70+
71+var
72+ code: PBytes; { text }
73+ pc: longint; { its length }
74+ rodata: PBytes;
75+ rolen: longint;
76+ chunks: PChunks;
77+ numChunks: longint;
78+ fixups: PFixups;
79+ numFixups: longint;
80+ { Addresses in read-only data, as in an array constant of strings:
81+ each 8 bytes, the chunk's absolute address, since the executable
82+ is loaded where the linker placed it }
83+ dataFixups: PFixups;
84+ numDataFixups: longint;
85+ lines: PLines;
86+ numLines: longint;
87+ curFile: longint; { the file being compiled, for NoteLine }
88+ curChunk: longint; { the chunk of code being written }
89+ varNotes: ^TVarNote;
90+ numVarNotes: longint;
91+
92+function NewChunk(sec: TSection; module, name: longint): longint;
93+procedure BeginChunk(c: longint);
94+procedure EndChunk(c: longint);
95+procedure SetData(c: longint; p: PBytes; n, align: longint);
96+procedure SetBss(c: longint; size, align: longint);
97+function ExternChunk(name: longint): longint;
98+procedure NoteLine(line, col: longint);
99+procedure AddFixup(at, chunk, addend: longint);
100+procedure AddDataFixup(c, at, chunk, addend: longint);
101+procedure NoteVar(chunk, name, off, kind: longint);
102+function ChunkName(c: longint): shortstring;
103+
104+procedure Put1(b: longint);
105+procedure Put4(v: longint);
106+procedure Put8(v: int64);
107+procedure Put4At(at, v: longint);
108+function Get4At(at: longint): longint;
109+procedure TakeBack(n: longint);
110+
111+implementation
112+
113+var
114+ codeCap, roCap, chunkCap, fixCap, lineCap: longint;
115+
116+procedure Room(n: longint);
117+begin
118+ if pc + n > codeCap then begin
119+ codeCap := codeCap * 2 + n;
120+ code := ReAllocMem(code, codeCap);
121+ end;
122+end;
123+
124+procedure Put1(b: longint);
125+begin
126+ if pc + 16 > codeCap then Room(16);
127+ code^[pc] := byte(b);
128+ inc(pc);
129+end;
130+
131+procedure Put4(v: longint);
132+begin
133+ if pc + 16 > codeCap then Room(16);
134+ PLongint(@code^[pc])^ := v;
135+ inc(pc, 4);
136+end;
137+
138+procedure Put4At(at, v: longint);
139+begin
140+ PLongint(@code^[at])^ := v;
141+end;
142+
143+function Get4At(at: longint): longint;
144+begin
145+ Get4At := PLongint(@code^[at])^;
146+end;
147+
148+{ The last n bytes of code taken back. A line noted past the new end
149+ now starts there, in place of one noted there before, as NoteLine
150+ would have it. }
151+procedure TakeBack(n: longint);
152+begin
153+ dec(pc, n);
154+ if (numLines > 0) and (lines^[numLines - 1].at > pc) then begin
155+ lines^[numLines - 1].at := pc;
156+ if (numLines > 1) and (lines^[numLines - 2].at = pc) then begin
157+ lines^[numLines - 2] := lines^[numLines - 1];
158+ dec(numLines);
159+ end;
160+ end;
161+end;
162+
163+procedure Put8(v: int64);
164+begin
165+ Put4(longint(v and $FFFFFFFF));
166+ Put4(longint(v shr 32));
167+end;
168+
169+function NewChunk(sec: TSection; module, name: longint): longint;
170+begin
171+ if numChunks = chunkCap then begin
172+ chunkCap := chunkCap * 2;
173+ chunks := ReAllocMem(chunks, chunkCap * SizeOf(TChunk));
174+ end;
175+ FillChar(chunks^[numChunks], SizeOf(TChunk), 0);
176+ chunks^[numChunks].sec := sec;
177+ chunks^[numChunks].module := module;
178+ chunks^[numChunks].name := name;
179+ chunks^[numChunks].align := 1;
180+ chunks^[numChunks].size := -1; { not yet defined }
181+ NewChunk := numChunks;
182+ inc(numChunks);
183+end;
184+
185+procedure BeginChunk(c: longint);
186+begin
187+ { code is aligned to 32 bytes, the windows in which x86 fetches and
188+ caches it, so that a procedure's loops sit in them the same way
189+ whatever comes before: rat ran 5% slower at 16, by where its loops
190+ fell. Padded with CC, x86's int3: a trap if it were ever run }
191+ while pc and 31 <> 0 do Put1($CC);
192+ curChunk := c;
193+ chunks^[c].start := pc;
194+ chunks^[c].align := 32;
195+ chunks^[c].firstFix := numFixups;
196+end;
197+
198+procedure EndChunk(c: longint);
199+begin
200+ chunks^[c].size := pc - chunks^[c].start;
201+ chunks^[c].numFix := numFixups - chunks^[c].firstFix;
202+end;
203+
204+procedure SetData(c: longint; p: PBytes; n, align: longint);
205+begin
206+ if rolen + n > roCap then begin
207+ roCap := roCap * 2 + n;
208+ rodata := ReAllocMem(rodata, roCap);
209+ end;
210+ Move(p^, rodata^[rolen], n);
211+ chunks^[c].firstFix := numDataFixups;
212+ chunks^[c].numFix := 0;
213+ chunks^[c].start := rolen;
214+ chunks^[c].size := n;
215+ chunks^[c].align := align;
216+ inc(rolen, n);
217+end;
218+
219+procedure SetBss(c: longint; size, align: longint);
220+begin
221+ chunks^[c].size := size;
222+ chunks^[c].align := align;
223+end;
224+
225+{ The code from here on is for line and column of the current file. A
226+ place with no code of its own gives way to the next. }
227+procedure NoteLine(line, col: longint);
228+begin
229+ if (numLines > 0) and (lines^[numLines - 1].at = pc) then dec(numLines);
230+ if (numLines > 0) and (lines^[numLines - 1].chunk = curChunk) and (lines^[numLines - 1].line = line)
231+ and (lines^[numLines - 1].col = col) and (lines^[numLines - 1].path = curFile) then exit;
232+ if numLines = lineCap then begin
233+ lineCap := lineCap * 2;
234+ lines := ReAllocMem(lines, lineCap * SizeOf(TLine));
235+ end;
236+ lines^[numLines].at := pc;
237+ lines^[numLines].chunk := curChunk;
238+ lines^[numLines].path := curFile;
239+ lines^[numLines].line := line;
240+ lines^[numLines].col := col;
241+ inc(numLines);
242+end;
243+
244+{ The quadword that holds the address of C's symbol name, filled in
245+ when the program starts; one for each name. }
246+function ExternChunk(name: longint): longint;
247+var c: longint;
248+begin
249+ for c := 0 to numChunks - 1 do
250+ if chunks^[c].ext and (chunks^[c].name = name) then exit(c);
251+ c := NewChunk(secBss, -1, name);
252+ SetBss(c, 8, 8);
253+ chunks^[c].ext := true;
254+ ExternChunk := c;
255+end;
256+
257+procedure AddFixup(at, chunk, addend: longint);
258+begin
259+ if numFixups = fixCap then begin
260+ fixCap := fixCap * 2;
261+ fixups := ReAllocMem(fixups, fixCap * SizeOf(TFixup));
262+ end;
263+ fixups^[numFixups].at := at;
264+ fixups^[numFixups].chunk := chunk;
265+ fixups^[numFixups].addend := addend;
266+ inc(numFixups);
267+end;
268+
269+{ The address of chunk, plus addend, at offset at of rodata chunk c,
270+ whose data is set: its fixups follow one another. }
271+procedure AddDataFixup(c, at, chunk, addend: longint);
272+begin
273+ if numDataFixups and 255 = 0 then
274+ dataFixups := ReAllocMem(dataFixups, (numDataFixups + 256) * SizeOf(TFixup));
275+ dataFixups^[numDataFixups].at := at;
276+ dataFixups^[numDataFixups].chunk := chunk;
277+ dataFixups^[numDataFixups].addend := addend;
278+ inc(numDataFixups);
279+ inc(chunks^[c].numFix);
280+end;
281+
282+procedure NoteVar(chunk, name, off, kind: longint);
283+begin
284+ if numVarNotes and 255 = 0 then varNotes := ReAllocMem(varNotes, (numVarNotes + 256) * SizeOf(TVarNote));
285+ varNotes[numVarNotes].chunk := chunk;
286+ varNotes[numVarNotes].name := name;
287+ varNotes[numVarNotes].off := off;
288+ varNotes[numVarNotes].kind := kind;
289+ inc(numVarNotes);
290+end;
291+
292+{ The name of chunk c: its module's and its own, or literal and its
293+ number for a literal }
294+function ChunkName(c: longint): shortstring;
295+begin
296+ with chunks^[c] do
297+ if name < 0 then ChunkName := 'literal' + IntStr(c)
298+ else if module < 0 then ChunkName := NameOf(name)
299+ else ChunkName := NameOf(module) + '.' + NameOf(name);
300+end;
301+
302+initialization
303+ codeCap := 1 shl 20;
304+ code := GetMem(codeCap);
305+ pc := 0;
306+ roCap := 1 shl 16;
307+ rodata := GetMem(roCap);
308+ rolen := 0;
309+ chunkCap := 1 shl 10;
310+ chunks := GetMem(chunkCap * SizeOf(TChunk));
311+ numChunks := 0;
312+ fixCap := 1 shl 12;
313+ fixups := GetMem(fixCap * SizeOf(TFixup));
314+ numFixups := 0;
315+ lineCap := 1 shl 12;
316+ lines := GetMem(lineCap * SizeOf(TLine));
317+ numLines := 0;
318+end.

seed/diag.pas added +316 -0

@@ -0,0 +1,316 @@
1+{ diag.pas: messages.
2+
3+ The one place the compiler's messages are made. A message is an
4+ error or a warning at a position, which it shows as the file, line
5+ and column, then the line of source with the position underlined;
6+ notes, each at a position of its own, and help, a line of advice,
7+ may follow it. Colour is used when standard error is a terminal and
8+ NO_COLOR isn't set. diag keeps every source file it is given, so
9+ that a note can show a line of a module compiled earlier.
10+
11+ Depends on: BaseUnix and termio, to write and to ask about the
12+ terminal.
13+ Leaves out: wording. The callers say what is wrong; a message is at
14+ most 255 characters, which every message so far keeps well within. }
15+
16+unit diag;
17+
18+{$mode objfpc}{$H-}
19+
20+interface
21+
22+type
23+ { A stretch of a source file: bytes a up to but not including b.
24+ a = b marks the place between two characters. }
25+ TPos = record
26+ f, a, b: longint;
27+ end;
28+
29+const
30+ MaxErrors = 20;
31+
32+var
33+ errors, warnings: longint;
34+ werror: boolean; { -Werror: a warning counts as an error }
35+ { The construct being read uses a name already reported as not
36+ declared: its errors follow from that one, and aren't shown. }
37+ quiet: boolean;
38+
39+function AddFile(const path: shortstring; buf: PChar; len: longint): longint;
40+function ShownPath(const path: shortstring): shortstring;
41+function PathOf(f: longint): shortstring;
42+function LineOf(const p: TPos): longint;
43+function Join(const p, q: TPos): TPos;
44+function Source(const p: TPos): shortstring;
45+function LineText(const path: shortstring; line: longint): shortstring;
46+procedure Error(const p: TPos; const msg: shortstring);
47+procedure Warning(const p: TPos; const msg: shortstring);
48+procedure Note(const p: TPos; const msg: shortstring);
49+function IntStr(n: int64): shortstring;
50+procedure Help(const msg: shortstring);
51+procedure Fatal(const msg: shortstring);
52+procedure Finish;
53+
54+implementation
55+
56+uses BaseUnix, termio;
57+
58+type
59+ TFile = record
60+ path: shortstring;
61+ buf: PChar;
62+ len: longint;
63+ end;
64+
65+var
66+ files: ^TFile; { numFiles of them, in room for cap }
67+ numFiles, cap: longint;
68+ colour, colourKnown, cwdKnown: boolean;
69+ cwd: shortstring; { the working directory and a /, or '' if unknown }
70+ lastError: TPos; { where the last error was }
71+ shown: boolean; { whether it was shown: its notes and help are only then }
72+
73+{ Paths are shown from the working directory where they are under it,
74+ so messages read the same wherever the compiler or its library is. }
75+function ShownPath(const path: shortstring): shortstring;
76+var d: array[0..255] of char;
77+begin
78+ if not cwdKnown then begin
79+ if FpGetcwd(@d[0], SizeOf(d)) <> nil then cwd := StrPas(@d[0]) + '/';
80+ cwdKnown := true;
81+ end;
82+ if (cwd <> '') and (copy(path, 1, length(cwd)) = cwd) then ShownPath := copy(path, length(cwd) + 1, 255)
83+ else ShownPath := path;
84+end;
85+
86+function AddFile(const path: shortstring; buf: PChar; len: longint): longint;
87+begin
88+ if numFiles = cap then begin
89+ cap := 2 * cap + 8;
90+ ReallocMem(files, cap * SizeOf(TFile));
91+ end;
92+ files[numFiles].path := ShownPath(path);
93+ files[numFiles].buf := buf;
94+ files[numFiles].len := len;
95+ AddFile := numFiles;
96+ inc(numFiles);
97+end;
98+
99+function PathOf(f: longint): shortstring;
100+begin
101+ PathOf := files[f].path;
102+end;
103+
104+{ Writing }
105+
106+const
107+ Bold = #27'[1m'; Red = #27'[1;31m'; Yellow = #27'[1;33m';
108+ Cyan = #27'[1;36m'; Green = #27'[1;32m'; Blue = #27'[1;34m';
109+ Plain = #27'[0m';
110+
111+{ Whether NO_COLOR is set, to anything }
112+function NoColour: boolean;
113+var e: PPChar;
114+begin
115+ e := envp;
116+ while (e^ <> nil) and (CompareByte(e^^, PChar('NO_COLOR=')^, 9) <> 0) do inc(e);
117+ NoColour := e^ <> nil;
118+end;
119+
120+{ s in colour c, when colour is on }
121+function Paint(const c, s: shortstring): shortstring;
122+begin
123+ if not colourKnown then begin
124+ colour := (IsATTY(2) = 1) and not NoColour;
125+ colourKnown := true;
126+ end;
127+ if colour then Paint := c + s + Plain else Paint := s;
128+end;
129+
130+function IntStr(n: int64): shortstring;
131+var s: shortstring;
132+begin
133+ Str(n, s);
134+ IntStr := s;
135+end;
136+
137+{ Positions }
138+
139+{ The line of p, and the byte where it starts. Lines are counted from
140+ the start of the file, which is slow only next to compiling it. }
141+procedure Locate(const p: TPos; out line, start: longint);
142+var i: longint; buf: PChar;
143+begin
144+ buf := files[p.f].buf;
145+ line := 1; start := 0;
146+ for i := 0 to p.a - 1 do
147+ if buf[i] = #10 then begin inc(line); start := i + 1 end;
148+end;
149+
150+function LineOf(const p: TPos): longint;
151+var line, start: longint;
152+begin
153+ Locate(p, line, start);
154+ LineOf := line;
155+end;
156+
157+{ Characters from byte i to byte j of buf: every byte but a UTF-8
158+ continuation byte. }
159+function Chars(buf: PChar; i, j: longint): longint;
160+var n: longint;
161+begin
162+ n := 0;
163+ for i := i to j - 1 do
164+ if (byte(buf[i]) and $C0) <> $80 then inc(n);
165+ Chars := n;
166+end;
167+
168+{ "file:line:col: kind: msg", then the line with p underlined. A tab
169+ before p is copied into the underline, so that the two line up
170+ whatever the terminal makes of tabs. }
171+{ A long line is shown cut to this many bytes around the place, its
172+ cut ends marked ... }
173+const ShownBytes = 100;
174+
175+procedure Show(const p: TPos; const kind, kindColour, msg: shortstring);
176+var line, start, stop, lo, hi, i, n: longint; buf: PChar; num, gutter: shortstring;
177+begin
178+ if p.f >= numFiles then begin
179+ { about no place in a file, as for Rt, which the compiler imports
180+ before it reads one }
181+ writeln(StdErr, Paint(Bold, 'raz:'), ' ', Paint(kindColour, kind + ':'), ' ', Paint(Bold, msg));
182+ exit;
183+ end;
184+ Locate(p, line, start);
185+ buf := files[p.f].buf;
186+ writeln(StdErr, Paint(Bold, files[p.f].path + ':' + IntStr(line) + ':'
187+ + IntStr(Chars(buf, start, p.a) + 1) + ':'), ' ', Paint(kindColour, kind + ':'),
188+ ' ', Paint(Bold, msg));
189+ stop := start;
190+ while (stop < files[p.f].len) and (buf[stop] <> #10) do inc(stop);
191+ num := IntStr(line);
192+ while length(num) < 5 do num := ' ' + num;
193+ gutter := Paint(Blue, num + ' |');
194+ lo := start; hi := stop;
195+ if hi - lo > ShownBytes then begin
196+ if p.a - lo > ShownBytes div 2 then lo := p.a - ShownBytes div 2;
197+ while (byte(buf[lo]) and $C0) = $80 do inc(lo);
198+ if hi - lo > ShownBytes then hi := lo + ShownBytes;
199+ while (hi < stop) and ((byte(buf[hi]) and $C0) = $80) do inc(hi);
200+ end;
201+ write(StdErr, gutter, ' ');
202+ if lo > start then write(StdErr, '...');
203+ for i := lo to hi - 1 do write(StdErr, buf[i]);
204+ if hi < stop then write(StdErr, '...');
205+ writeln(StdErr);
206+ write(StdErr, Paint(Blue, ' |'), ' ');
207+ if lo > start then write(StdErr, ' ');
208+ for i := lo to p.a - 1 do
209+ if buf[i] = #9 then write(StdErr, #9)
210+ else if (byte(buf[i]) and $C0) <> $80 then write(StdErr, ' ');
211+ if p.b < hi then n := Chars(buf, p.a, p.b) else n := Chars(buf, p.a, hi);
212+ if n < 1 then n := 1;
213+ writeln(StdErr, Paint(kindColour, StringOfChar('^', n)));
214+end;
215+
216+{ From the start of p to the end of q }
217+function Join(const p, q: TPos): TPos;
218+begin
219+ Join := p;
220+ Join.b := q.b;
221+end;
222+
223+{ The text at p, at most the 255 bytes a shortstring holds }
224+function Source(const p: TPos): shortstring;
225+var n: longint;
226+begin
227+ n := p.b - p.a;
228+ if n > 255 then n := 255;
229+ SetLength(Source, n);
230+ Move(files[p.f].buf[p.a], Source[1], n);
231+end;
232+
233+{ Messages }
234+
235+{ Line line of the file at path, as written }
236+function LineText(const path: shortstring; line: longint): shortstring;
237+var i, k, n: longint; s: shortstring;
238+begin
239+ s := '';
240+ for i := 0 to numFiles - 1 do
241+ if files[i].path = ShownPath(path) then begin
242+ k := 0; n := 1;
243+ while (n < line) and (k < files[i].len) do begin
244+ if files[i].buf[k] = #10 then inc(n);
245+ inc(k);
246+ end;
247+ while (k < files[i].len) and (files[i].buf[k] <> #10) and (length(s) < 255) do begin
248+ s := s + files[i].buf[k];
249+ inc(k);
250+ end;
251+ break;
252+ end;
253+ LineText := s;
254+end;
255+
256+procedure Error(const p: TPos; const msg: shortstring);
257+begin
258+ { a second error at one place follows from the first: when a symbol
259+ ends a construct with an error, the one around it may stop there too }
260+ shown := not quiet and not ((errors > 0) and (p.f = lastError.f) and (p.a = lastError.a));
261+ if not shown then exit;
262+ lastError := p;
263+ Show(p, 'error', Red, msg);
264+ inc(errors);
265+ if errors >= MaxErrors then begin
266+ writeln(StdErr, 'raz: stopping after ', MaxErrors, ' errors');
267+ Halt(1);
268+ end;
269+end;
270+
271+procedure Warning(const p: TPos; const msg: shortstring);
272+begin
273+ if werror then Error(p, msg)
274+ else begin
275+ Show(p, 'warning', Yellow, msg);
276+ shown := true;
277+ inc(warnings);
278+ end;
279+end;
280+
281+{ Notes and help follow an error or a warning, and are shown with it }
282+procedure Note(const p: TPos; const msg: shortstring);
283+begin
284+ if shown then Show(p, 'note', Cyan, msg);
285+end;
286+
287+procedure Help(const msg: shortstring);
288+begin
289+ if shown then writeln(StdErr, Paint(Green, 'help:'), ' ', msg);
290+end;
291+
292+{ An error with no place in the source, such as a file that can't be
293+ read: it stops the compiler at once. }
294+procedure Fatal(const msg: shortstring);
295+begin
296+ writeln(StdErr, 'raz: ', msg);
297+ Halt(1);
298+end;
299+
300+function Count(n: longint; const what: shortstring): shortstring;
301+begin
302+ if n = 1 then Count := '1 ' + what else Count := IntStr(n) + ' ' + what + 's';
303+end;
304+
305+{ Says how many errors and warnings there were, and stops the compiler
306+ if there were errors. }
307+procedure Finish;
308+begin
309+ if (errors > 0) and (warnings > 0) then
310+ writeln(StdErr, 'raz: ', Count(errors, 'error'), ', ', Count(warnings, 'warning'))
311+ else if errors > 0 then writeln(StdErr, 'raz: ', Count(errors, 'error'))
312+ else if warnings > 0 then writeln(StdErr, 'raz: ', Count(warnings, 'warning'));
313+ if errors > 0 then Halt(1);
314+end;
315+
316+end.

seed/elf.pas added +373 -0

@@ -0,0 +1,373 @@
1+{ elf.pas: the executable file.
2+
3+ Writes an ELF64 executable for x86-64 Linux: the ELF header, the
4+ program headers, the linked text and rodata, and section headers
5+ with a symbol table, so that objdump and gdb can name each procedure
6+ and variable. For gdb's line numbers there is DWARF 4: a line table
7+ (.debug_line), and the one compile unit that points to it
8+ (.debug_info, .debug_abbrev). There are no types or variables.
9+
10+ A program that uses C is linked dynamically, in the least way the
11+ loader accepts: it names its loader and libraries, and each C symbol
12+ it uses is a quadword the loader fills in with the symbol's address
13+ (a GLOB_DAT relocation), which the code calls or reads through.
14+ There is no PLT and no lazy binding, and the program exports nothing.
15+
16+ Depends on: link for the images and addresses, chunk for the chunks,
17+ scan for names and errors, BaseUnix to write the file.
18+ Leaves out: position independent executables, symbol versions, the
19+ rest of DWARF. }
20+
21+unit elf;
22+
23+{$mode objfpc}{$H-}
24+
25+interface
26+
27+uses scan, diag, chunk, link;
28+
29+var
30+ needed: array[0..31] of longint; { the libraries to load, names interned }
31+ numNeeded: longint; { none: a static program }
32+ mainPath: shortstring; { the main module's file, for gdb }
33+ stripped: boolean; { -s: no symbols and no line numbers; the sections are there, empty }
34+
35+procedure WriteElf(const path: shortstring; entry: longint);
36+
37+implementation
38+
39+uses BaseUnix;
40+
41+var
42+ buf: PBytes;
43+ len, cap: int64;
44+
45+procedure Room(n: int64);
46+begin
47+ if len + n > cap then begin
48+ cap := cap * 2 + n;
49+ buf := ReAllocMem(buf, cap);
50+ end;
51+end;
52+
53+procedure PutN(v: qword; n: longint);
54+var i: longint;
55+begin
56+ Room(n);
57+ for i := 0 to n - 1 do begin
58+ buf^[len] := byte(v);
59+ v := v shr 8;
60+ inc(len);
61+ end;
62+end;
63+
64+procedure PutBytes(p: PBytes; n: int64);
65+begin
66+ Room(n);
67+ if n > 0 then Move(p^, buf^[len], n);
68+ len := len + n;
69+end;
70+
71+procedure PadTo(off: int64);
72+begin
73+ while len < off do PutN(0, 1);
74+end;
75+
76+procedure Patch(at: int64; v: qword; n: longint);
77+var i: longint;
78+begin
79+ for i := 0 to n - 1 do begin
80+ buf^[at + i] := byte(v);
81+ v := v shr 8;
82+ end;
83+end;
84+
85+procedure Phdr(typ, flags: longint; off, adr, filesz, memsz, align: int64);
86+begin
87+ PutN(typ, 4);
88+ PutN(flags, 4);
89+ PutN(off, 8);
90+ PutN(adr, 8);
91+ PutN(adr, 8);
92+ PutN(filesz, 8);
93+ PutN(memsz, 8);
94+ PutN(align, 8);
95+end;
96+
97+const
98+ { the section names, in .shstrtab; a section header names its own }
99+ ShNames = #0'.text'#0'.rodata'#0'.bss'#0'.symtab'#0'.strtab'#0'.shstrtab'#0 +
100+ '.dynamic'#0'.dynstr'#0'.dynsym'#0'.debug_line'#0'.debug_info'#0'.debug_abbrev'#0;
101+
102+{ A section header. Its name is given as a string and stored as its
103+ offset in ShNames: the #0 before it, counted from 1, is that offset
104+ counted from 0; the empty name, found nowhere, is 0. }
105+procedure Shdr(const name: shortstring; typ: longint; flags, adr, off, size: int64; lnk, info: longint; align, entsize: int64);
106+begin
107+ PutN(Pos(#0 + name + #0, ShNames), 4); PutN(typ, 4); PutN(flags, 8); PutN(adr, 8);
108+ PutN(off, 8); PutN(size, 8); PutN(lnk, 4); PutN(info, 4);
109+ PutN(align, 8); PutN(entsize, 8);
110+end;
111+
112+procedure PutStr(const s: shortstring);
113+begin
114+ PutBytes(@s[1], length(s));
115+ PutN(0, 1);
116+end;
117+
118+{ LEB128, unsigned }
119+procedure PutU(v: qword);
120+begin
121+ while v >= $80 do begin
122+ PutN(v and $7F or $80, 1);
123+ v := v shr 7;
124+ end;
125+ PutN(v, 1);
126+end;
127+
128+{ The compile unit, which names the line table, and its abbreviation;
129+ the table itself is in the places, in rodata (link.pas). Section
130+ offsets go in off, sizes in size: line, info, abbrev. }
131+procedure PutDebug(var off, size: array of int64);
132+var cwd: array[0..255] of char;
133+begin
134+ off[0] := chunks^[placesChunk].adr - roAdr + roOff + linesOff;
135+ size[0] := linesSize;
136+ off[1] := len;
137+ PutN(0, 4); PutN(4, 2); PutN(0, 4); PutN(8, 1); { length, version, abbrev, address size }
138+ PutU(1);
139+ PutStr(mainPath);
140+ if FpGetcwd(@cwd, SizeOf(cwd)) = nil then cwd[0] := #0;
141+ PutStr(PChar(@cwd));
142+ PutStr('raz');
143+ PutN(0, 4); { the line table, at 0 }
144+ PutN(Base + textOff, 8); PutN(textSize, 8); { the code, all of it }
145+ Patch(off[1], len - off[1] - 4, 4);
146+ size[1] := len - off[1];
147+
148+ off[2] := len;
149+ PutU(1); PutU($11); PutN(0, 1); { 1: a compile unit, no children }
150+ PutU($03); PutU($08); { name, a string }
151+ PutU($1B); PutU($08); { comp_dir, a string }
152+ PutU($25); PutU($08); { producer, a string }
153+ PutU($10); PutU($17); { stmt_list, a section offset }
154+ PutU($11); PutU($01); { low_pc, an address }
155+ PutU($12); PutU($07); { high_pc, a length in 8 bytes }
156+ PutN(0, 2); PutN(0, 1);
157+ size[2] := len - off[2];
158+end;
159+
160+const
161+ Interp = '/lib64/ld-linux-x86-64.so.2';
162+ { program header types }
163+ PtLoad = 1; PtDynamic = 2; PtInterp = 3; PtGnuStack = $6474E551;
164+
165+var
166+ { in the room at the end of rodata: where each of the loader's
167+ tables starts, from extraAdr }
168+ symAt, relaAt, hashAt, strAt: int64;
169+ nsym, strLen: longint;
170+
171+{ The sizes of the loader's tables: what LinkAll must leave room for. }
172+procedure SizeTables(var roExtra, dynSize: int64);
173+var c, i: longint;
174+begin
175+ nsym := 1;
176+ strLen := 1;
177+ for i := 0 to numNeeded - 1 do strLen := strLen + length(NameOf(needed[i])) + 1;
178+ for c := 0 to numChunks - 1 do
179+ if chunks^[c].live and chunks^[c].ext then begin
180+ inc(nsym);
181+ strLen := strLen + length(NameOf(chunks^[c].name)) + 1;
182+ end;
183+ symAt := (length(Interp) + 1 + 7) div 8 * 8;
184+ relaAt := symAt + nsym * 24;
185+ hashAt := relaAt + (nsym - 1) * 24;
186+ strAt := hashAt + 4 * (3 + nsym);
187+ roExtra := strAt + strLen;
188+ dynSize := (numNeeded + 10) * 16;
189+end;
190+
191+{ The loader's tables in the room at the end of rodata, which the
192+ buffer already holds as zeros: the loader's name; the symbols, one
193+ for each C symbol used; a GLOB_DAT relocation for each, at its
194+ quadword; a hash table of one bucket; and their names. }
195+procedure PutTables;
196+var c, k, i, at, name: longint;
197+begin
198+ len := extraAdr - roAdr + roOff;
199+ PutStr(Interp);
200+ PadTo(extraAdr - roAdr + roOff + symAt);
201+ PutN(0, 24);
202+ name := strLen;
203+ for c := numChunks - 1 downto 0 do { names go last in the string table }
204+ if chunks^[c].live and chunks^[c].ext then name := name - length(NameOf(chunks^[c].name)) - 1;
205+ for c := 0 to numChunks - 1 do
206+ if chunks^[c].live and chunks^[c].ext then begin
207+ PutN(name, 4); PutN($10, 1); PutN(0, 1); PutN(0, 2); { global, undefined }
208+ PutN(0, 8); PutN(0, 8);
209+ name := name + length(NameOf(chunks^[c].name)) + 1;
210+ end;
211+ k := 1;
212+ for c := 0 to numChunks - 1 do
213+ if chunks^[c].live and chunks^[c].ext then begin
214+ PutN(chunks^[c].adr, 8);
215+ PutN(qword(k) shl 32 or 6, 8); { R_X86_64_GLOB_DAT }
216+ PutN(0, 8);
217+ inc(k);
218+ end;
219+ PutN(1, 4); PutN(nsym, 4); PutN(nsym - 1, 4); { the bucket chains every symbol }
220+ PutN(0, 4);
221+ for i := 1 to nsym - 1 do PutN(i - 1, 4);
222+ PutN(0, 1);
223+ for i := 0 to numNeeded - 1 do PutStr(NameOf(needed[i]));
224+ for c := 0 to numChunks - 1 do
225+ if chunks^[c].live and chunks^[c].ext then PutStr(NameOf(chunks^[c].name));
226+ len := roOff + roSize;
227+
228+ { the dynamic table, at the start of the writable segment }
229+ PadTo(bssOff);
230+ at := 1;
231+ for i := 0 to numNeeded - 1 do begin
232+ PutN(1, 8); PutN(at, 8); { DT_NEEDED }
233+ at := at + length(NameOf(needed[i])) + 1;
234+ end;
235+ PutN(4, 8); PutN(extraAdr + hashAt, 8); { DT_HASH }
236+ PutN(5, 8); PutN(extraAdr + strAt, 8); { DT_STRTAB }
237+ PutN(6, 8); PutN(extraAdr + symAt, 8); { DT_SYMTAB }
238+ PutN(10, 8); PutN(strLen, 8); { DT_STRSZ }
239+ PutN(11, 8); PutN(24, 8); { DT_SYMENT }
240+ PutN(7, 8); PutN(extraAdr + relaAt, 8); { DT_RELA }
241+ PutN(8, 8); PutN((nsym - 1) * 24, 8); { DT_RELASZ }
242+ PutN(9, 8); PutN(24, 8); { DT_RELAENT }
243+ PutN(21, 8); PutN(0, 8); { DT_DEBUG, for gdb }
244+ PutN(0, 16); { DT_NULL }
245+end;
246+
247+procedure WriteElf(const path: shortstring; entry: longint);
248+var
249+ nph, nsh, c, nsyms, fd: longint;
250+ roExtra, dynSize, symOff, strOff, shstrOff, shOff, strsLen: int64;
251+ dbgOff, dbgSize: array[0..2] of int64;
252+ strs: PBytes;
253+ s, p: shortstring;
254+ sec: longint;
255+ dynamic: boolean;
256+begin
257+ cap := 1 shl 16;
258+ buf := GetMem(cap);
259+ len := 0;
260+ dynamic := numNeeded > 0;
261+ roExtra := 0; dynSize := 0;
262+ if dynamic then SizeTables(roExtra, dynSize);
263+ { room for the most program headers either kind of program has }
264+ LinkAll(64 + 6 * 56, roExtra, dynSize);
265+ if dynamic then nph := 6
266+ else begin
267+ nph := 2;
268+ if roSize > 0 then inc(nph);
269+ if bssSize > 0 then inc(nph);
270+ end;
271+
272+ { ELF header }
273+ PutN($464C457F, 4); { #127 'ELF' }
274+ PutN(2, 1); PutN(1, 1); PutN(1, 1); PutN(0, 9); { 64-bit, little-endian, version 1 }
275+ PutN(2, 2); { ET_EXEC }
276+ PutN(62, 2); { EM_X86_64 }
277+ PutN(1, 4);
278+ PutN(chunks^[entry].adr, 8);
279+ PutN(64, 8); { program headers follow }
280+ PutN(0, 8); { section headers: patched below }
281+ PutN(0, 4);
282+ nsh := 10;
283+ if dynamic then nsh := 13;
284+ PutN(64, 2); PutN(56, 2); PutN(nph, 2);
285+ PutN(64, 2); PutN(nsh, 2); PutN(6, 2); { .shstrtab is section 6 }
286+
287+ { flags: 4 read, 5 read and run, 6 read and write }
288+ if dynamic then Phdr(PtInterp, 4, extraAdr - roAdr + roOff, extraAdr, length(Interp) + 1, length(Interp) + 1, 1);
289+ { the first segment maps the headers too, so text can follow them }
290+ Phdr(PtLoad, 5, 0, Base, textOff + textSize, textOff + textSize, Page);
291+ if roSize > 0 then Phdr(PtLoad, 4, roOff, roAdr, roSize, roSize, Page);
292+ if dynamic then begin
293+ Phdr(PtLoad, 6, bssOff, bssAdr, dynSize, bssSize, Page);
294+ Phdr(PtDynamic, 6, bssOff, bssAdr, dynSize, dynSize, 8);
295+ end else if bssSize > 0 then Phdr(PtLoad, 6, 0, bssAdr, 0, bssSize, Page);
296+ Phdr(PtGnuStack, 6, 0, 0, 0, 0, 16); { a stack that can't run code }
297+
298+ PadTo(textOff);
299+ PutBytes(textImg, textSize);
300+ PadTo(roOff); { even when empty, so that every section lies in the file }
301+ PutBytes(roImg, roSize);
302+ if dynamic then PutTables;
303+
304+ { the symbol table: one local symbol for each named live chunk }
305+ PadTo((len + 7) div 8 * 8);
306+ symOff := len;
307+ strs := GetMem(1 shl 16);
308+ strsLen := 1;
309+ strs^[0] := 0;
310+ PutN(0, 24);
311+ nsyms := 1;
312+ for c := 0 to numChunks - 1 do
313+ if not stripped and chunks^[c].live and (chunks^[c].name >= 0) and not chunks^[c].ext then begin
314+ s := ChunkName(c);
315+ if strsLen + length(s) + 1 > MemSize(strs) then strs := ReAllocMem(strs, strsLen * 2 + 256);
316+ Move(s[1], strs^[strsLen], length(s));
317+ strs^[strsLen + length(s)] := 0;
318+ case chunks^[c].sec of { the section's index in the headers below }
319+ secText: sec := 1;
320+ secRodata: sec := 2;
321+ else sec := 3;
322+ end;
323+ PutN(strsLen, 4);
324+ if sec = 1 then PutN(2, 1) else PutN(1, 1); { STT_FUNC, STT_OBJECT }
325+ PutN(0, 1);
326+ PutN(sec, 2);
327+ PutN(chunks^[c].adr, 8);
328+ PutN(chunks^[c].size, 8);
329+ strsLen := strsLen + length(s) + 1;
330+ inc(nsyms);
331+ end;
332+ strOff := len;
333+ PutBytes(strs, strsLen);
334+ shstrOff := len;
335+ s := ShNames;
336+ PutBytes(@s[1], length(s));
337+ if stripped or (placesChunk < 0) then begin
338+ for c := 0 to 2 do begin dbgOff[c] := len; dbgSize[c] := 0 end;
339+ end else PutDebug(dbgOff, dbgSize);
340+
341+ PadTo((len + 7) div 8 * 8);
342+ shOff := len;
343+ Patch(40, shOff, 8);
344+ { types: 1 PROGBITS, 2 SYMTAB, 3 STRTAB, 6 DYNAMIC, 8 NOBITS, 11 DYNSYM;
345+ flags: 2 ALLOC, 3 WRITE+ALLOC, 6 ALLOC+EXECINSTR. A symbol table's
346+ link is its string table's index: 5 .strtab, 8 .dynstr. The order
347+ here is the index the code above relies on. }
348+ Shdr('', 0, 0, 0, 0, 0, 0, 0, 0, 0);
349+ Shdr('.text', 1, 6, Base + textOff, textOff, textSize, 0, 0, 16, 0);
350+ Shdr('.rodata', 1, 2, roAdr, roOff, roSize, 0, 0, 16, 0);
351+ Shdr('.bss', 8, 3, bssAdr + dynSize, roOff + roSize, bssSize - dynSize, 0, 0, 16, 0);
352+ Shdr('.symtab', 2, 0, 0, symOff, nsyms * 24, 5, nsyms, 8, 24);
353+ Shdr('.strtab', 3, 0, 0, strOff, strsLen, 0, 0, 1, 0);
354+ Shdr('.shstrtab', 3, 0, 0, shstrOff, length(ShNames), 0, 0, 1, 0);
355+ if dynamic then begin { the loader's tables, for readelf and objdump }
356+ Shdr('.dynamic', 6, 3, bssAdr, bssOff, dynSize, 8, 0, 8, 16);
357+ Shdr('.dynstr', 3, 2, extraAdr + strAt, extraAdr + strAt - roAdr + roOff, strLen, 0, 0, 1, 0);
358+ Shdr('.dynsym', 11, 2, extraAdr + symAt, extraAdr + symAt - roAdr + roOff, nsym * 24, 8, 1, 8, 24);
359+ end;
360+ Shdr('.debug_line', 1, 0, 0, dbgOff[0], dbgSize[0], 0, 0, 1, 0);
361+ Shdr('.debug_info', 1, 0, 0, dbgOff[1], dbgSize[1], 0, 0, 1, 0);
362+ Shdr('.debug_abbrev', 1, 0, 0, dbgOff[2], dbgSize[2], 0, 0, 1, 0);
363+
364+ p := path + #0;
365+ fd := FpOpen(@p[1], O_WRONLY or O_CREAT or O_TRUNC, &755);
366+ if fd < 0 then Fatal('can''t write ' + path);
367+ if FpWrite(fd, buf^, len) <> len then Fatal('can''t write ' + path);
368+ FpClose(fd);
369+ FreeMem(strs);
370+ FreeMem(buf);
371+end;
372+
373+end.

seed/gen.pas added +2322 -0

@@ -0,0 +1,2322 @@
1+{ gen.pas: the code generator, for x86-64.
2+
3+ item.pas and parse.pas drive a stack machine: they push constants,
4+ addresses and the values of variables, operate on the values on top,
5+ store them and jump on them. Every value has a kind: a word, which
6+ is an integer as big as an address, a pointer, a BOOL, a set or a
7+ narrower integer; a long, a 64-bit integer on a machine whose word is
8+ smaller (never here); an F32; an F64. This unit makes the machine's
9+ code for those calls, and nothing above it knows the machine: a port
10+ is a new gen.pas, with an encoder of its own.
11+
12+ The stack is kept in registers, as in Wirth's compilers (Niklaus
13+ Wirth's Pascal and Oberon compilers): the value at depth d, depth 0
14+ being the bottom, is in r8 to r11, register d mod 4, or in xmm8 to
15+ xmm11 if it is a real. A value that needs a register a lower one
16+ holds spills that one: stores it in a frame slot, to free the
17+ register. A constant, or an address in the
18+ frame or of a chunk, is only noted until something needs it in a
19+ register, so that it can be an instruction's operand.
20+
21+ A slice is two words, a pointer and then a length.
22+
23+ Calls use the System V convention, which x86-64 Linux has for C:
24+ arguments in rdi, rsi, rdx, rcx, r8, r9 and xmm0 to xmm7, the rest on
25+ the machine's stack; rbx, rbp and r12 to r15 are callee-saved, which
26+ is to say a called procedure gives them back as it found them. The
27+ arguments are computed left to right onto the stack of values, and
28+ moved into their registers just before the call: a call in a later
29+ argument spills the earlier ones, as any call spills the values under
30+ it, so that it can't disturb them. A slice goes as its two words, as
31+ System V passes a 16-byte struct of two integers; a record, array or
32+ variant passed by value goes as the address of a copy the caller
33+ makes. A slice, or two results that are single values, come back in
34+ rax and rdx (InTwoRegs); any other record, or several results, comes
35+ back in memory the caller provides, through a hidden pointer
36+ (BehindPointer), where C would send a small struct back in registers.
37+
38+ A procedure's frame holds its parameters, its variables, and the
39+ temporaries of the statement running. The variables are zeroed on
40+ entry.
41+
42+ Depends on: scan and diag for errors, sym for types, chunk for code
43+ and data, x64 for instructions.
44+ Leaves out: what the program means, its types and their checks; that
45+ is item.pas. }
46+
47+unit gen;
48+
49+{$mode objfpc}{$H-}
50+
51+interface
52+
53+uses scan, diag, sym, chunk, x64;
54+
55+const
56+ NoLabel = -1;
57+ WordSize = 8; { the size of an address, and of INT }
58+ { What the machine catches by itself, which the code needn't test for
59+ (report section 10): on x86-64 Linux, a division by zero, a stack
60+ overflow (at the guard page under the stack), a call to nil, and
61+ a load or store within NilPage bytes of address 0, which is never
62+ mapped. }
63+ NilPage = 4096;
64+
65+type
66+ TKind = (kWord, kLong, kF32, kF64);
67+
68+ { Where a variable is: its address is relative to the frame, to a
69+ chunk, to an address on the stack, or to one held in a frame slot }
70+ TBase = (bFrame, bGlobal, bStack, bSlot, bReg);
71+ TAdr = record
72+ base: TBase;
73+ chunk: longint; { bGlobal: the chunk; bSlot: the frame slot; bReg: the register }
74+ off: int64; { added to the address; for bReg, which word, 0 or 8 }
75+ hi: longint; { bReg, a slice: the register of its length, the
76+ second word; chunk is that of its pointer }
77+ end;
78+
79+ { The code made so far, to go back to for a second try at a body }
80+ TCodeMark = record pc, fixups, lines, said, fails: longint; end;
81+
82+ { For EntryPoint: the address of chunk, put in the variable whose
83+ chunk is into before the program starts }
84+ TLink = record chunk, into: longint; end;
85+
86+ TCall = record
87+ sig: PType;
88+ param: PObj; { the parameter the next argument is for }
89+ obj: PObj; { the procedure called, if it has a name }
90+ n: longint; { the arguments }
91+ isF: array[0..63] of boolean; { ... goes in an xmm register }
92+ pair: array[0..63] of boolean; { ... is a slice's first word, the next its second }
93+ target: int64; { the frame slot of a procedure value, if chunk < 0 }
94+ chunk: longint; { else the procedure's chunk }
95+ ext: boolean; { C's: called through the chunk holding its address }
96+ ret: int64; { set by Call: the temporary a slice or a record result is in }
97+ end;
98+
99+const
100+ { the registers a procedure keeps its busiest variables in: System V's
101+ callee-saved ones, so they live through calls (a register variable); a procedure saves
102+ those it uses, and Rt finds them there for the trap report }
103+ VarRegs: array[0..4] of longint = (RBX, R12, R13, R14, R15);
104+ { the registers the trap report can show a variable in: VarRegs, then
105+ rdi and rsi, where a procedure that calls nothing keeps the
106+ parameters that arrive in them (KeptIn) }
107+ ShownRegs: array[0..6] of longint = (RBX, R12, R13, R14, R15, RDI, RSI);
108+ { the registers a procedure keeps its busiest reals in, xmm12 to
109+ xmm15, numbered from XmmVar up so that they aren't taken for r12 to
110+ r15 (RegAt). Each has a slot too, written as it is, where the trap
111+ report finds it, and from which it is loaded again after a call, as
112+ System V has no callee-saved xmm register (XHome). }
113+ XmmVar = 16;
114+ XVarRegs: array[0..3] of longint = (XmmVar + 12, XmmVar + 13, XmmVar + 14, XmmVar + 15);
115+ { a procedure's registers of variables, as bits: bit i is VarRegs[i],
116+ bit XBit + i XVarRegs[i] }
117+ XBit = 5;
118+
119+var
120+ rtFail, argcChunk, argvChunk: longint;
121+ { the stubs that Check's code calls, one for each kind of failure,
122+ made by EntryPoint for those used }
123+ failStubs: array[0..5] of longint = (-1, -1, -1, -1, -1, -1);
124+ lost: boolean; { a parameter kept where it arrived was wanted
125+ for other work: the procedure is compiled again,
126+ the parameter in memory }
127+ inPlace: longint = -1; { the register of a variable that the statement
128+ being compiled assigns, x := x + e, where the
129+ value can be worked out in the variable's own
130+ register, from its first push on (lInto) }
131+ depth: longint; { the values on the stack }
132+ pushed: longint; { quadwords pushed on the machine's stack }
133+ codeChunk: longint = -1; { the procedure or body being compiled, or -1 }
134+
135+function KindOf(t: PType): TKind;
136+
137+procedure PushConst(k: TKind; v: int64);
138+procedure PushAdr(const a: TAdr);
139+procedure PushVar(const a: TAdr; size: longint; signed: boolean; k: TKind);
140+procedure PushProc(c: longint; ext: boolean);
141+procedure PopVar(const a: TAdr; size: longint);
142+procedure Drop;
143+procedure Swap;
144+procedure ResetStack(d, p: longint);
145+
146+procedure CopyBlock(size, off: int64);
147+procedure CopyTo(const a: TAdr; size: int64);
148+procedure ZeroVar(const a: TAdr; size: int64);
149+
150+procedure Op(op: TSym; k: TKind; size: longint; signed: boolean);
151+procedure Compare(op: TSym; k: TKind; signed: boolean);
152+procedure Neg(k: TKind; size: longint; signed: boolean);
153+procedure Complement(size: longint; signed: boolean);
154+procedure NotBool;
155+procedure Narrow(size: longint; signed: boolean);
156+procedure IntToReal(k: TKind; big: boolean);
157+procedure RealToInt(k: TKind);
158+procedure RealToReal(k: TKind);
159+procedure CompareSeq(a, b: int64; shift: longint; eq: boolean);
160+procedure ErrorText(tmp: int64);
161+procedure IncDec(size: longint; signed, dec: boolean);
162+procedure IncDecReg(r, size: longint; signed, dec: boolean);
163+procedure ZeroNew(size: int64);
164+procedure Atomic(which: longint);
165+procedure SysCall(n: longint);
166+procedure Fence;
167+
168+procedure Jump(var L: longint);
169+procedure JumpIf(var L: longint; when: boolean);
170+procedure JumpCmp(op: TSym; signed: boolean; var L: longint);
171+procedure JumpOut(op: TSym; signed: boolean; var L: longint);
172+procedure CondValue(notOp: TSym; signed: boolean; fj, tj: longint);
173+procedure JumpBack(top: longint);
174+function JumpTable(slot, lo: int64; n, elseAt: longint; var endL: longint): longint;
175+procedure TableEntry(table, target: longint);
176+procedure AlignLoop;
177+procedure Fix(L: longint);
178+procedure FixTo(L, top: longint);
179+function JoinJumps(L1, L2: longint): longint;
180+
181+procedure CheckIndex(n: int64; const p: TPos);
182+procedure CheckEnum(n: int64; name: longint; const p: TPos);
183+procedure CheckNil(reach: int64; const p: TPos);
184+procedure IndexArray(const a: TAdr; size: int64);
185+procedure IndexSlice(const a: TAdr; size: int64; checked: boolean; const p: TPos);
186+procedure Slice(const a: TAdr; isArray: boolean; n, size, tmp: int64; checked: boolean; const p: TPos);
187+procedure SlicePtr(size, tmp: int64; checked: boolean; const p: TPos);
188+procedure CopySlice(dOff, sOff, size: int64; checked: boolean; const p: TPos);
189+
190+procedure Call(var c: TCall);
191+
192+function AllocTemp(size, align: int64): int64;
193+function AllocPerm(size, align: int64): int64;
194+function TempMark: int64;
195+procedure ReleaseTemps(m: int64);
196+procedure KeepTemps;
197+
198+procedure BeginProc(sig: PType; params: PObj);
199+procedure ResetLocals;
200+procedure KeepArrived(o: PObj);
201+function KeptIn(o: PObj): boolean;
202+procedure UseRegs(mask: longint);
203+procedure XHome(r: longint; slot: int64);
204+procedure MarkCode(var m: TCodeMark);
205+procedure Redo(const m: TCodeMark);
206+procedure Rewind(const m: TCodeMark);
207+procedure EnterBody(c, line: longint);
208+procedure ResultTo(off: int64; size: longint);
209+procedure CopyResult(off, size: int64);
210+procedure ReturnJump;
211+procedure TryAlign;
212+procedure TryReturn(slot: int64);
213+procedure EndProc(c: longint; open: boolean);
214+function DeferBegin(var L, saved: longint): longint;
215+procedure DeferEnd(L, saved: longint);
216+procedure RunDefer(at: longint);
217+
218+function EntryPoint(dynamic: boolean; first: PModule; main: PObj; cExit, exitProc: longint; const links: array of TLink; numLinks: longint): longint;
219+procedure CodeProc(c: longint; constExpr: TConstFn);
220+
221+implementation
222+
223+type
224+ { where a value on the stack is }
225+ TLoc = (lConst, { not loaded: val is the value }
226+ lHeld, { not loaded: in register val, a register
227+ variable's own (see VarRegs), read in place, which
228+ nothing in an expression can change }
229+ lAdr, { not loaded: the address of chunk, or of the frame
230+ if chunk is -1, plus val }
231+ lIdx, { not loaded: the address m, an element of an array
232+ or of a slice in registers: the array's or the
233+ pointer's register, or rbp, as the base, and the
234+ index in a register variable's or the value's
235+ own register (IndexSlice, IndexArray) }
236+ lMem, { not loaded: the value of size bytes at m, in the
237+ frame, a chunk, or at an address lAdr or lIdx
238+ noted, read where it is used (PushVar) }
239+ lInto, { in register val, a register variable's own, which
240+ is what the value goes to (inPlace): so it is
241+ changed in place }
242+ lReg, { in its register }
243+ lFrame); { spilled: in the frame slot val }
244+
245+ TEntry = record
246+ loc: TLoc;
247+ val: int64; { lConst: the value; lHeld: the register; lAdr: the
248+ offset; lFrame: the frame slot }
249+ chunk: longint; { lAdr: the chunk, or -1 for the frame }
250+ m: TMem; { lIdx, lMem }
251+ size: longint; { lMem }
252+ signed: boolean; { lMem }
253+ k: TKind;
254+ off: int64; { lHeld, lReg: a word, its register plus off, the
255+ constant of x + 1 not yet added (Op), so that an
256+ operand that uses it can take it as its
257+ displacement: [r13 + r9 * 8 - 8] }
258+ end;
259+
260+const
261+ StubNames: array[0..5] of string[6] = ('check0', 'check1', 'check2', 'check3', 'check4', 'check5');
262+ { the registers of the stack: the value at depth d is in Regs[d mod
263+ NumRegs]. rax, rdx and rcx, which division and shifts need, and rsi
264+ and rdi, which copying needs, aren't among them. }
265+ NumRegs = 4;
266+ Regs: array[0..NumRegs - 1] of longint = (R8, R9, R10, R11);
267+ XRegs: array[0..NumRegs - 1] of longint = (8, 9, 10, 11); { xmm8 to xmm11 }
268+ IntRegs: array[0..5] of longint = (RDI, RSI, RDX, RCX, R8, R9);
269+
270+var
271+ stack: array[0..255] of TEntry;
272+ owner: array[0..NumRegs - 1] of longint; { the value in each register, or -1 }
273+ frameTop, frameMax, permTop: int64;
274+ frameFix: longint; { where the frame size is patched in }
275+ paramTop: int64; { the parameters' slots end here }
276+ zeroTop: int64; { the locals the prologue zeroes end here }
277+ retSlot: int64; { holds the hidden result pointer }
278+ resType: PType; { the procedure's result, or nil }
279+ exitL: longint;
280+ { parameters arriving in registers: where each is stored on entry }
281+ inReg: array[0..13] of longint;
282+ inSlot: array[0..13] of int64;
283+ inSize: array[0..13] of longint;
284+ inObj: array[0..13] of PObj;
285+ numIn: longint;
286+ procParams: PObj; { the parameters, for EnterBody }
287+ regMask: longint; { the registers of variables, as bits (XBit) }
288+ kept: longint; { bit r: register r holds a parameter, as it arrived }
289+ saveAt: int64; { where they are saved, a quadword each }
290+ homes: array[0..3] of int64; { the slots of the variables in XVarRegs }
291+ frameAt: array[0..2] of int64; { frameTop, frameMax, permTop after the declarations }
292+ { the checks of the procedure, whose failures EndFails makes }
293+ fails: array[0..4095] of record
294+ L, what, ra, name, at: longint;
295+ m: TMem;
296+ n: int64;
297+ end;
298+ numFails: longint;
299+
300+function KindOf(t: PType): TKind;
301+begin
302+ if t^.form = fReal then begin
303+ if t^.size = 4 then KindOf := kF32 else KindOf := kF64
304+ end else if t^.size > WordSize then KindOf := kLong
305+ else KindOf := kWord;
306+end;
307+
308+{ The stack, as in Wirth's compilers: the value at depth d is held in
309+ register d mod NumRegs. A value, when a higher one wants its register,
310+ and every value in a register when a call would clobber them, is
311+ spilled to a frame slot, and loaded again where it is used. A constant
312+ is only noted.
313+
314+ Drop emits no code, and a dropped value's register still holds it
315+ until the next push claims it: Place (for bStack), Operands,
316+ IndexSlice and JumpCmp read a register after dropping its value.
317+
318+ Registers outside the stack, free within one operation: rax, rcx and
319+ rdx for arithmetic; rsi and rdi for copying; and, where the stack holds
320+ nothing in them, r10 for the prologue's zeroing loop and r11 for a call
321+ through a procedure value; xmm0 and xmm1 for reals.
322+
323+ A real, an F32 or an F64, is held in xmm8 to xmm11 (XRegs), where the
324+ machine computes with reals, the value at depth d in XRegs[d mod
325+ NumRegs]: so each depth has two registers, and holds its value in the
326+ one of its kind, which owner doesn't tell apart. The xmm registers
327+ from xmm8 up carry no arguments, so that Call can move a real into
328+ xmm0 to xmm7 without overwriting another still to go. }
329+
330+function Fits32(v: int64): boolean;
331+begin
332+ Fits32 := (v >= low(longint)) and (v <= high(longint));
333+end;
334+
335+{ The register of kind k for the value at depth i }
336+function RegIn(k: TKind; i: longint): longint;
337+begin
338+ if k in [kF32, kF64] then RegIn := XRegs[i mod NumRegs] else RegIn := Regs[i mod NumRegs];
339+end;
340+
341+function RegOf(i: longint): longint;
342+begin
343+ RegOf := RegIn(stack[i].k, i);
344+end;
345+
346+function IsReal(i: longint): boolean;
347+begin
348+ IsReal := stack[i].k in [kF32, kF64];
349+end;
350+
351+{ A real constant, its bits v, as an operand: 8 bytes in read-only
352+ data, as the machine has no instruction that holds one }
353+function RealConst(v: int64): TMem;
354+var c: longint;
355+begin
356+ c := NewChunk(secRodata, -1, -1);
357+ SetData(c, @v, 8, 8);
358+ RealConst := MemRip(c, 0);
359+end;
360+
361+{ The real i into xmm register x, from wherever it is, as ValueTo does
362+ for an integer register }
363+procedure XValueTo(i, x: longint);
364+var single: boolean;
365+begin
366+ single := stack[i].k = kF32;
367+ case stack[i].loc of
368+ lConst: MovsXM(x, RealConst(stack[i].val), single);
369+ lMem: MovsXM(x, stack[i].m, stack[i].size = 4);
370+ lHeld, lInto: if stack[i].val <> x then MovX(x, stack[i].val);
371+ lReg: if RegOf(i) <> x then MovX(x, RegOf(i));
372+ else MovsXM(x, Mem(RBP, stack[i].val), false); { spilled, as 8 bytes }
373+ end;
374+end;
375+
376+function Loaded(i: longint): longint; forward;
377+
378+{ The value i, in a register, goes to a frame slot; one noted that
379+ holds its register, as an index, is worked out in it first }
380+procedure Spill(i: longint);
381+var s: int64;
382+begin
383+ if (stack[i].loc <> lReg) or (stack[i].off <> 0) then Loaded(i);
384+ s := AllocTemp(8, 8);
385+ if IsReal(i) then MovsMX(Mem(RBP, s), RegOf(i), false)
386+ else Store(Mem(RBP, s), RegOf(i), 8);
387+ stack[i].loc := lFrame;
388+ stack[i].val := s;
389+ owner[i mod NumRegs] := -1;
390+end;
391+
392+{ Each value below depth d read from memory now, as what comes next
393+ may change it }
394+procedure ReadMems(d: longint);
395+var i: longint;
396+begin
397+ for i := 0 to d - 1 do
398+ if stack[i].loc = lMem then Loaded(i);
399+end;
400+
401+{ Every value below depth d in a register, spilled; one noted in memory
402+ is read first, as a call may change it }
403+procedure SpillBelow(d: longint);
404+var r: longint;
405+begin
406+ ReadMems(d);
407+ for r := 0 to NumRegs - 1 do
408+ if (owner[r] >= 0) and (owner[r] < d) then Spill(owner[r]);
409+end;
410+
411+{ The register of kind k of value i, for it to hold: a lower value at
412+ its depth's registers is spilled. }
413+function Claim(i: longint; k: TKind): longint;
414+var r: longint;
415+begin
416+ r := i mod NumRegs;
417+ if (owner[r] >= 0) and (owner[r] <> i) then Spill(owner[r]);
418+ owner[r] := i;
419+ Claim := RegIn(k, i);
420+end;
421+
422+{ The memory at the noted address i, plus off }
423+function AdrMem(i: longint; off: int64): TMem;
424+begin
425+ if stack[i].chunk < 0 then AdrMem := Mem(RBP, stack[i].val + off)
426+ else AdrMem := MemRip(stack[i].chunk, stack[i].val + off);
427+end;
428+
429+{ The value i, in its register }
430+function Loaded(i: longint): longint;
431+var r: longint;
432+begin
433+ if stack[i].loc = lInto then exit(stack[i].val);
434+ if (stack[i].loc <> lReg) and IsReal(i) then begin
435+ XValueTo(i, Claim(i, stack[i].k));
436+ stack[i].loc := lReg;
437+ end else if stack[i].loc <> lReg then begin
438+ r := Claim(i, kWord);
439+ case stack[i].loc of
440+ lConst: MovRI(r, stack[i].val);
441+ lHeld: MovRR(r, stack[i].val);
442+ lAdr: Lea(r, AdrMem(i, 0));
443+ lIdx: Lea(r, stack[i].m);
444+ lMem: Load(r, stack[i].m, stack[i].size, stack[i].signed);
445+ else Load(r, Mem(RBP, stack[i].val), 8, false);
446+ end;
447+ stack[i].loc := lReg;
448+ end;
449+ if stack[i].off <> 0 then begin
450+ Lea(RegOf(i), Mem(RegOf(i), stack[i].off));
451+ stack[i].off := 0;
452+ end;
453+ Loaded := RegOf(i);
454+end;
455+
456+{ The register value i is in, only to be read: a variable's own, or
457+ its register }
458+function Peek(i: longint): longint;
459+begin
460+ if (stack[i].loc = lHeld) and (stack[i].off = 0) then Peek := stack[i].val else Peek := Loaded(i);
461+end;
462+
463+{ The offset of value i, taken from it, for the caller to add or to
464+ make a displacement of }
465+function TakeOff(i: longint): int64;
466+begin
467+ TakeOff := stack[i].off;
468+ stack[i].off := 0;
469+end;
470+
471+{ The word on top, in a register, has o added: noted, if o can be a
472+ displacement, else added now }
473+procedure PutOff(o: int64);
474+begin
475+ if Fits32(stack[depth - 1].off + o) then stack[depth - 1].off := stack[depth - 1].off + o
476+ else begin
477+ MovRI(RCX, o);
478+ Alu(aluAdd, Loaded(depth - 1), RCX);
479+ end;
480+end;
481+
482+function Top: longint;
483+begin
484+ if depth = 0 then Fatal('internal error: the stack is empty');
485+ Top := Loaded(depth - 1);
486+end;
487+
488+procedure NewEntry(k: TKind; loc: TLoc; v: int64);
489+begin
490+ if depth > High(stack) then Mark('the expression is too deep');
491+ stack[depth].k := k;
492+ stack[depth].loc := loc;
493+ stack[depth].val := v;
494+ stack[depth].chunk := -1;
495+ stack[depth].off := 0;
496+ inc(depth);
497+end;
498+
499+{ An address, lIdx, or a value at it, lMem, noted as the operand m. Its
500+ index may be in the register of the value just dropped, at this
501+ depth: it is the new value's own, then. }
502+procedure NewMem(loc: TLoc; const m: TMem; k: TKind; size: longint; signed: boolean);
503+begin
504+ NewEntry(k, loc, 0);
505+ stack[depth - 1].m := m;
506+ stack[depth - 1].size := size;
507+ stack[depth - 1].signed := signed;
508+ if m.index = Regs[(depth - 1) mod NumRegs] then owner[(depth - 1) mod NumRegs] := depth - 1;
509+end;
510+
511+{ The register a new value on top is to be computed in }
512+function Target: longint;
513+begin
514+ Target := Claim(depth, kWord);
515+end;
516+
517+{ The xmm register a new real on top is to be computed in }
518+function XTarget: longint;
519+begin
520+ XTarget := Claim(depth, kF64);
521+end;
522+
523+{ The value just computed in Target goes on top }
524+procedure Computed(k: TKind);
525+begin
526+ NewEntry(k, lReg, 0);
527+end;
528+
529+procedure Drop;
530+begin
531+ dec(depth);
532+ if owner[depth mod NumRegs] = depth then owner[depth mod NumRegs] := -1;
533+end;
534+
535+{ rsi and rdi are about to be used for other work, as in copying: a
536+ parameter kept in either must go to memory (lost). }
537+procedure ClobberArgs;
538+begin
539+ if kept <> 0 then lost := true;
540+end;
541+
542+{ The value i into register r, from wherever it is: a constant or an
543+ address is made there, a variable's register or the value's own
544+ register copied, a spilled value loaded. Unlike Loaded, it leaves the
545+ value where it was, so r is its only new copy. }
546+procedure ValueTo(i, r: longint);
547+begin
548+ if IsReal(i) and (stack[i].loc in [lHeld, lInto]) then MovqRX(r, stack[i].val)
549+ else case stack[i].loc of
550+ lConst: MovRI(r, stack[i].val);
551+ lHeld, lInto: MovRR(r, stack[i].val);
552+ lAdr: Lea(r, AdrMem(i, 0));
553+ lIdx: Lea(r, stack[i].m);
554+ lMem: Load(r, stack[i].m, stack[i].size, stack[i].signed);
555+ lReg:
556+ if IsReal(i) then MovqRX(r, RegOf(i))
557+ else if RegOf(i) <> r then MovRR(r, RegOf(i));
558+ else Load(r, Mem(RBP, stack[i].val), 8, false);
559+ end;
560+ if stack[i].off <> 0 then Lea(r, Mem(r, stack[i].off));
561+end;
562+
563+{ The value on top, popped into register r }
564+procedure PopTo(r: longint);
565+begin
566+ ValueTo(depth - 1, r);
567+ Drop;
568+end;
569+
570+{ Whether the value on top is a constant, and if so, which }
571+function TopConst(var v: int64): boolean;
572+begin
573+ TopConst := stack[depth - 1].loc = lConst;
574+ v := stack[depth - 1].val;
575+end;
576+
577+procedure ResetStack(d, p: longint);
578+var r: longint;
579+begin
580+ depth := d;
581+ pushed := p;
582+ for r := 0 to NumRegs - 1 do owner[r] := -1;
583+end;
584+
585+procedure PushConst(k: TKind; v: int64);
586+begin
587+ NewEntry(k, lConst, v);
588+end;
589+
590+{ The register of the word at a, a variable in registers: the variable's
591+ own, or for a slice its pointer's (off 0) or its length's (off 8) }
592+function RegAt(const a: TAdr): longint;
593+begin
594+ if a.off = 0 then RegAt := a.chunk else RegAt := a.hi;
595+ if RegAt >= XmmVar then RegAt := RegAt - XmmVar; { an xmm register, XVarRegs }
596+end;
597+
598+{ The memory a names. An address on the stack is popped, and is in its
599+ register still; one in a slot is loaded into r. }
600+function Place(const a: TAdr; r: longint): TMem;
601+var ra: longint; o: int64;
602+begin
603+ if a.base = bReg then Fatal('internal error: a register has no address');
604+ case a.base of
605+ bFrame: Place := Mem(RBP, a.off);
606+ bGlobal: Place := MemRip(a.chunk, a.off);
607+ bStack:
608+ if stack[depth - 1].loc = lAdr then begin
609+ Place := AdrMem(depth - 1, a.off);
610+ Drop;
611+ end else if stack[depth - 1].loc = lIdx then begin
612+ Place := stack[depth - 1].m;
613+ Place.disp := Place.disp + a.off;
614+ Drop;
615+ end else begin
616+ { an offset noted on the address is the operand's, as
617+ p^.f + 8: [r8 + 8] }
618+ if Fits32(a.off + stack[depth - 1].off) then o := TakeOff(depth - 1) else o := 0;
619+ ra := Peek(depth - 1);
620+ Drop;
621+ Place := Mem(ra, a.off + o)
622+ end;
623+ else { bSlot: the address is in the frame slot a.chunk }
624+ Load(r, Mem(RBP, a.chunk), 8, false);
625+ Place := Mem(r, a.off);
626+ end;
627+end;
628+
629+{ The address a names, on top of the stack }
630+procedure PushAdr(const a: TAdr);
631+var m: TMem; r: longint;
632+begin
633+ if (a.base = bStack) and (a.off = 0) then exit; { it is on top already }
634+ if a.base in [bFrame, bGlobal] then begin
635+ NewEntry(kWord, lAdr, a.off);
636+ if a.base = bGlobal then stack[depth - 1].chunk := a.chunk;
637+ exit;
638+ end;
639+ { The order matters. With the address on the stack, Place pops it and
640+ must come first, so that Target may reuse its register; otherwise
641+ Target comes first, since Place may need r to load a slot's pointer. }
642+ if a.base = bStack then begin m := Place(a, -1); r := Target end
643+ else begin r := Target; m := Place(a, r) end;
644+ Lea(r, m);
645+ Computed(kWord);
646+end;
647+
648+procedure PushVar(const a: TAdr; size: longint; signed: boolean; k: TKind);
649+var m: TMem; r: longint;
650+begin
651+ r := inPlace;
652+ inPlace := -1;
653+ if r >= XmmVar then r := r - XmmVar;
654+ if (a.base = bReg) and (RegAt(a) = r) then begin
655+ NewEntry(k, lInto, r);
656+ exit;
657+ end;
658+ if a.base = bReg then begin
659+ NewEntry(k, lHeld, RegAt(a));
660+ exit;
661+ end;
662+ { a variable in the frame or a chunk, or at an address only noted, is
663+ only noted too: read where it is used, as an operand if it can be }
664+ if (a.base in [bFrame, bGlobal]) or (a.base = bStack) and (stack[depth - 1].loc in [lAdr, lIdx]) then begin
665+ m := Place(a, -1);
666+ NewMem(lMem, m, k, size, signed);
667+ exit;
668+ end;
669+ { in the order PushAdr explains }
670+ if a.base = bStack then begin m := Place(a, -1); r := Target end
671+ else begin r := Target; m := Place(a, r) end;
672+ if k in [kF32, kF64] then MovsXM(XTarget, m, size = 4)
673+ else Load(r, m, size, signed);
674+ Computed(k);
675+end;
676+
677+procedure PushProc(c: longint; ext: boolean);
678+var r: longint;
679+begin
680+ r := Target;
681+ if ext then Load(r, MemRip(c, 0), 8, false)
682+ else Lea(r, MemRip(c, 0));
683+ Computed(kWord);
684+end;
685+
686+{ The slot of the variable in xmm register x }
687+function HomeOf(x: longint): TMem;
688+begin
689+ HomeOf := Mem(RBP, homes[x + XmmVar - XVarRegs[0]]);
690+end;
691+
692+{ Pops a value into the variable at a; an address on the stack is under
693+ the value. }
694+procedure PopVar(const a: TAdr; size: longint);
695+var r: longint; v: int64; real: boolean;
696+begin
697+ if (a.base = bReg) and IsReal(depth - 1) then begin
698+ XValueTo(depth - 1, RegAt(a));
699+ Drop;
700+ MovsMX(HomeOf(RegAt(a)), RegAt(a), false); { written through, as XHome says }
701+ exit;
702+ end;
703+ if a.base = bReg then begin
704+ if TopConst(v) then MovRI(RegAt(a), v)
705+ else if Peek(depth - 1) <> RegAt(a) then MovRR(RegAt(a), Peek(depth - 1)); { else it is there, lInto }
706+ Drop;
707+ exit;
708+ end;
709+ if TopConst(v) and Fits32(v) then begin
710+ Drop;
711+ StoreI(Place(a, RCX), v, size);
712+ exit;
713+ end;
714+ if TopConst(v) then begin r := RAX; MovRI(RAX, v) end
715+ else r := Peek(depth - 1);
716+ real := (stack[depth - 1].loc <> lConst) and IsReal(depth - 1);
717+ Drop;
718+ if real then MovsMX(Place(a, RCX), r, size = 4)
719+ else Store(Place(a, RCX), r, size);
720+end;
721+
722+{ Register src to dst, an xmm register's if real }
723+procedure MovReg(real: boolean; dst, src: longint);
724+begin
725+ if real then MovX(dst, src) else MovRR(dst, src);
726+end;
727+
728+{ The two values on top, of one kind, change places. }
729+procedure Swap;
730+var e: TEntry; x, y, t: longint; rx, ry, real: boolean;
731+begin
732+ x := depth - 2; y := depth - 1;
733+ { a value noted at an address that uses its register is worked out,
734+ so that its register moves with it }
735+ if stack[x].loc in [lIdx, lMem] then Loaded(x);
736+ if stack[y].loc in [lIdx, lMem] then Loaded(y);
737+ rx := stack[x].loc = lReg;
738+ ry := stack[y].loc = lReg;
739+ real := IsReal(y);
740+ if real then t := 0 else t := RAX; { xmm0, or rax }
741+ if rx and ry then begin
742+ MovReg(real, t, RegOf(x));
743+ MovReg(real, RegOf(x), RegOf(y));
744+ MovReg(real, RegOf(y), t);
745+ end else if rx then begin
746+ owner[x mod NumRegs] := -1;
747+ MovReg(real, Claim(y, stack[y].k), RegOf(x));
748+ end else if ry then begin
749+ owner[y mod NumRegs] := -1;
750+ MovReg(real, Claim(x, stack[x].k), RegOf(y));
751+ end;
752+ e := stack[x]; stack[x] := stack[y]; stack[y] := e;
753+end;
754+
755+{ Copying }
756+
757+{ size bytes from [rsi] to [rdi], through rcx; rsi and rdi are left
758+ as they fall. Up to 64 bytes, as a record or a small array mostly
759+ is, they go as moves of 8, 4, 2 and 1 bytes: rep movsb takes some
760+ twenty cycles to start, longer than the few moves take. }
761+procedure CopyBytes(size: int64);
762+var o, n: int64;
763+begin
764+ if size > 64 then begin
765+ MovRI(RCX, size);
766+ RepMovsb;
767+ exit;
768+ end;
769+ o := 0;
770+ while o < size do begin
771+ n := 8;
772+ while n > size - o do n := n div 2;
773+ Load(RCX, Mem(RSI, o), n, false);
774+ Store(Mem(RDI, o), RCX, n);
775+ Inc(o, n);
776+ end;
777+end;
778+
779+{ Pops a source's address, and a destination's under it, and copies
780+ size bytes to off bytes past the destination. }
781+procedure CopyBlock(size, off: int64);
782+begin
783+ ClobberArgs;
784+ PopTo(RSI);
785+ PopTo(RDI);
786+ if off <> 0 then Lea(RDI, Mem(RDI, off));
787+ CopyBytes(size);
788+end;
789+
790+{ Pops a source's address, and copies size bytes to a: for a slice in
791+ registers, its two words into them. }
792+procedure CopyTo(const a: TAdr; size: int64);
793+begin
794+ ClobberArgs;
795+ PopTo(RSI);
796+ if a.base = bReg then begin
797+ Load(a.chunk, Mem(RSI, 0), 8, false);
798+ Load(a.hi, Mem(RSI, 8), 8, false);
799+ exit;
800+ end;
801+ Lea(RDI, Place(a, RDI));
802+ CopyBytes(size);
803+end;
804+
805+procedure ZeroVar(const a: TAdr; size: int64);
806+begin
807+ ClobberArgs;
808+ Lea(RDI, Place(a, RDI));
809+ MovRI(RCX, size);
810+ MovRI(RAX, 0);
811+ RepStosb;
812+end;
813+
814+{ Operations }
815+
816+{ n if v is 2^n, which is 0 for 1; -1 if v isn't a power of two }
817+function ExactLog2(v: int64): longint;
818+var n: longint;
819+begin
820+ n := 0;
821+ while (v > 1) and (v and 1 = 0) do begin v := v shr 1; inc(n) end;
822+ if v <> 1 then n := -1;
823+ ExactLog2 := n;
824+end;
825+
826+{ r times v, a size: by a shift where v is a power of two, as it
827+ mostly is, since a shift takes one cycle and imul three }
828+procedure MulI(r: longint; v: int64);
829+begin
830+ if ExactLog2(v) > 0 then ShiftI(shShl, r, ExactLog2(v))
831+ else if v <> 1 then ImulI(r, v);
832+end;
833+
834+{ r compared with v, through rdx if v needs more than 32 bits; with
835+ zero by test, which sets the flags as cmp would and is shorter }
836+procedure CmpI(r: longint; v: int64);
837+begin
838+ if v = 0 then TestRR(r, r)
839+ else if Fits32(v) then AluI(aluCmp, r, v)
840+ else begin MovRI(RDX, v); Alu(aluCmp, r, RDX) end;
841+end;
842+
843+{ r div or mod 2^k, 1 <= k <= 62, with shifts: div truncates towards
844+ zero, so a negative dividend first gets 2^k - 1 added (the bias). }
845+procedure DivPow2(op: TSym; r, k: longint; unsign: boolean);
846+begin
847+ { unsigned: div shifts right; mod keeps the low k bits, by shifting
848+ them up to the top and back down }
849+ if unsign then begin
850+ if op = sDiv then ShiftI(shShr, r, k)
851+ else begin ShiftI(shShl, r, 64 - k); ShiftI(shShr, r, 64 - k) end;
852+ exit;
853+ end;
854+ { signed: sar 63 makes the sign into all ones or all zeros, and shr
855+ 64 - k keeps k of them, the bias 2^k - 1 or 0; with it added, sar k
856+ rounds towards zero. The remainder is r less the quotient times 2^k. }
857+ MovRR(RCX, r);
858+ ShiftI(shSar, RCX, 63);
859+ ShiftI(shShr, RCX, 64 - k);
860+ Alu(aluAdd, RCX, r);
861+ ShiftI(shSar, RCX, k);
862+ if op = sDiv then MovRR(r, RCX)
863+ else begin ShiftI(shShl, RCX, k); Alu(aluSub, r, RCX) end;
864+end;
865+
866+{ Before rax div y, of a signed type of bits < 64: its smallest value
867+ divided by -1 overflows it, which must stop the program as it does for
868+ an I64 (report section 6.1). idiv on the 64-bit values wouldn't fault,
869+ so then rax is made the smallest I64, and it does. }
870+procedure DivTrap(bits, y: longint);
871+var L: longint;
872+begin
873+ L := NoLabel;
874+ CmpI(y, -1);
875+ Jcc(ccNE, L);
876+ CmpI(RAX, int64(-1) shl (bits - 1));
877+ Jcc(ccNE, L);
878+ ShiftI(shShl, RAX, 64 - bits);
879+ FixLink(L);
880+end;
881+
882+{ Whether the value on top is a word in memory that can be the right
883+ operand of an instruction as it is: add r, [m] }
884+function TopInMem: boolean;
885+begin
886+ TopInMem := (stack[depth - 1].loc = lMem) and (stack[depth - 1].size = 8);
887+end;
888+
889+{ The right operand of the two values on top, popped, in register y:
890+ its own, or rcx for a constant; the left one stays, in its register,
891+ which is returned. }
892+function Operands(var y: longint): longint;
893+var v: int64;
894+begin
895+ if TopConst(v) then begin MovRI(RCX, v); y := RCX end else y := Peek(depth - 1);
896+ Drop;
897+ Operands := Top;
898+end;
899+
900+{ The two reals on top, the left op the right, worked out in the left's
901+ xmm register. The right is taken from memory where it is, as a
902+ constant, a variable or a spilled value is: mulsd xmm8, [rbp - 16]. }
903+procedure RealOp(op: TSym; k: TKind);
904+var f: boolean; c, x, y: longint; m: TMem;
905+begin
906+ f := k = kF32;
907+ case op of
908+ sPlus: c := $58; { addsd, or addss for an F32 }
909+ sMinus: c := $5C; { subsd, subss }
910+ sTimes: c := $59; { mulsd, mulss }
911+ else c := $5E; { divsd, divss }
912+ end;
913+ if stack[depth - 1].loc in [lConst, lMem, lFrame] then begin
914+ case stack[depth - 1].loc of
915+ lConst: m := RealConst(stack[depth - 1].val);
916+ lMem: m := stack[depth - 1].m;
917+ else m := Mem(RBP, stack[depth - 1].val);
918+ end;
919+ Drop;
920+ SseM(c, Top, m, f);
921+ end else begin
922+ y := Peek(depth - 1);
923+ Drop;
924+ x := Top;
925+ Sse(c, x, y, f);
926+ end;
927+end;
928+
929+{ The group 1 operation of +, -, &, | and xor }
930+function AluOf(op: TSym): longint;
931+begin
932+ case op of
933+ sPlus: AluOf := aluAdd;
934+ sMinus: AluOf := aluSub;
935+ sAmp: AluOf := aluAnd;
936+ sBar: AluOf := aluOr;
937+ else AluOf := aluXor;
938+ end;
939+end;
940+
941+{ The two values on top, the left op the right, an integer of size
942+ bytes, signed or not, brought back to its width. }
943+procedure Op(op: TSym; k: TKind; size: longint; signed: boolean);
944+var v, o: int64; r, y, sh, bits: longint; c: boolean; m: TMem;
945+begin
946+ if k in [kF32, kF64] then begin RealOp(op, k); exit end;
947+ bits := size * 8;
948+ { a constant on the left of an operation whose order doesn't matter
949+ goes right, where it can be an immediate or a shift }
950+ if (op in [sPlus, sTimes, sAmp, sBar, sXor]) and (stack[depth - 2].loc = lConst)
951+ and (stack[depth - 1].loc <> lConst) then Swap;
952+ c := TopConst(v);
953+ { A word's offset (see TEntry) is carried through + and -, and
954+ through * by a constant, as (x + a) * k is x * k + a * k: the
955+ operation is done on the registers, the offsets worked out here,
956+ and put on the result. x + 1 is only noted. A value changed in
957+ place, lInto, has no offset. }
958+ o := 0;
959+ if (bits = 64) and (stack[depth - 2].loc <> lInto)
960+ and ((op in [sPlus, sMinus]) or (op = sTimes) and c and Fits32(v)) then begin
961+ o := TakeOff(depth - 2);
962+ if op = sTimes then o := o * v
963+ else if c and Fits32(v) then begin
964+ if op = sPlus then o := o + v else o := o - v;
965+ Drop;
966+ if not (stack[depth - 1].loc in [lReg, lHeld]) then Top;
967+ PutOff(o);
968+ exit;
969+ end
970+ else if op = sPlus then o := o + TakeOff(depth - 1)
971+ else o := o - TakeOff(depth - 1);
972+ end;
973+ sh := -1;
974+ if c and (op in [sTimes, sDiv, sMod]) then sh := ExactLog2(v);
975+ if c and (sh >= 1) then begin
976+ Drop;
977+ r := Top;
978+ if op = sTimes then ShiftI(shShl, r, sh) else DivPow2(op, r, sh, not signed);
979+ end else if c and Fits32(v) and (op in [sPlus, sMinus, sBar, sXor, sAmp, sTimes, sShl, sShr]) then begin
980+ Drop;
981+ r := Top;
982+ case op of
983+ sTimes: ImulI(r, v);
984+ sShl: ShiftI(shShl, r, v and (bits - 1));
985+ sShr: if signed then ShiftI(shSar, r, v and (bits - 1)) else ShiftI(shShr, r, v and (bits - 1));
986+ else AluI(AluOf(op), r, v);
987+ end;
988+ end else if TopInMem and (op in [sPlus, sMinus, sAmp, sBar, sXor]) then begin
989+ m := stack[depth - 1].m;
990+ Drop;
991+ r := Top;
992+ AluM(AluOf(op), r, m);
993+ end else begin
994+ r := Operands(y);
995+ case op of
996+ sPlus, sMinus, sAmp, sBar, sXor: Alu(AluOf(op), r, y);
997+ sTimes: Imul(r, y);
998+ sDiv, sMod: begin
999+ MovRR(RAX, r);
1000+ if not signed then begin MovRI(RDX, 0); Unary(6, y) end { div }
1001+ else begin
1002+ { only -1 can make the division overflow, so a constant
1003+ divisor other than -1 needs no check }
1004+ if (bits < 64) and (not c or (v = -1)) then DivTrap(bits, y);
1005+ Cqo; Unary(7, y) { idiv, of rdx:rax, which cqo made from rax }
1006+ end;
1007+ if op = sDiv then MovRR(r, RAX) else MovRR(r, RDX);
1008+ end;
1009+ sShl, sShr: begin
1010+ { the count modulo the width: the machine takes it modulo 64 }
1011+ if y <> RCX then MovRR(RCX, y);
1012+ if bits < 64 then AluI(aluAnd, RCX, bits - 1);
1013+ if op = sShl then Shift(shShl, r)
1014+ else if signed then Shift(shSar, r) else Shift(shShr, r);
1015+ end;
1016+ end;
1017+ end;
1018+ if bits < 64 then Extend(r, size, signed);
1019+ stack[depth - 1].k := k;
1020+ if o <> 0 then PutOff(o);
1021+end;
1022+
1023+{ The left op the right of the two values on top, as a BOOL }
1024+procedure Compare(op: TSym; k: TKind; signed: boolean);
1025+const
1026+ CcSigned: array[sEql..sGeq] of longint = (ccE, ccNE, ccL, ccLE, ccG, ccGE);
1027+ CcUnsigned: array[sEql..sGeq] of longint = (ccE, ccNE, ccB, ccBE, ccA, ccAE);
1028+var f: boolean; r, x, y: longint; v: int64; m: TMem;
1029+begin
1030+ if k in [kF32, kF64] then begin
1031+ f := k = kF32;
1032+ y := Peek(depth - 1);
1033+ Drop;
1034+ x := Peek(depth - 1);
1035+ Drop;
1036+ r := Target; { the BOOL, in the left's integer register }
1037+ { ucomis sets the flags as an unsigned comparison would, but for an
1038+ unordered pair (a NaN) it sets zero, parity and carry all. So only
1039+ "above" can be tested straight: it is false for NaN, as every
1040+ comparison but <> must be. a < b is made b > a. = also asks for
1041+ no parity, as NaN = NaN sets the zero flag, and <> asks for
1042+ parity as well. }
1043+ case op of
1044+ sEql: begin Ucomis(x, y, f); SetCC(ccE, r); SetCC(ccNP, RCX); Alu(aluAnd, r, RCX) end;
1045+ sNeq: begin Ucomis(x, y, f); SetCC(ccNE, r); SetCC(ccP, RCX); Alu(aluOr, r, RCX) end;
1046+ sLss: begin Ucomis(y, x, f); SetCC(ccA, r) end;
1047+ sLeq: begin Ucomis(y, x, f); SetCC(ccAE, r) end;
1048+ sGtr: begin Ucomis(x, y, f); SetCC(ccA, r) end;
1049+ sGeq: begin Ucomis(x, y, f); SetCC(ccAE, r) end;
1050+ end;
1051+ Computed(kWord);
1052+ end else begin
1053+ if TopConst(v) then begin Drop; r := Top; CmpI(r, v) end
1054+ else if TopInMem then begin m := stack[depth - 1].m; Drop; r := Top; AluM(aluCmp, r, m) end
1055+ else begin r := Operands(y); Alu(aluCmp, r, y) end;
1056+ if signed then SetCC(CcSigned[op], r) else SetCC(CcUnsigned[op], r);
1057+ end;
1058+ stack[depth - 1].k := kWord;
1059+end;
1060+
1061+{ A real is negated by flipping its sign bit, in rax }
1062+procedure Neg(k: TKind; size: longint; signed: boolean);
1063+var r: longint;
1064+begin
1065+ r := Top;
1066+ case k of
1067+ kF32, kF64: begin
1068+ MovqRX(RAX, r);
1069+ if k = kF32 then Btc(RAX, 31) else Btc(RAX, 63);
1070+ MovqXR(r, RAX);
1071+ end;
1072+ else
1073+ Unary(3, r); { neg }
1074+ if size < 8 then Extend(r, size, signed);
1075+ end;
1076+end;
1077+
1078+procedure Complement(size: longint; signed: boolean);
1079+var r: longint;
1080+begin
1081+ r := Top;
1082+ Unary(2, r); { not }
1083+ if size < 8 then Extend(r, size, signed);
1084+end;
1085+
1086+procedure NotBool;
1087+begin
1088+ AluI(aluXor, Top, 1);
1089+end;
1090+
1091+{ The integer on top, brought to size bytes }
1092+procedure Narrow(size: longint; signed: boolean);
1093+var r: longint;
1094+begin
1095+ r := Top;
1096+ if size < 8 then Extend(r, size, signed);
1097+ stack[depth - 1].k := kWord;
1098+end;
1099+
1100+{ The integer on top, as a real of kind k; big if it may be a U64 above
1101+ high(I64), which the machine would take as negative }
1102+procedure IntToReal(k: TKind; big: boolean);
1103+var L1, L2, r, x: longint; f: boolean;
1104+begin
1105+ f := k = kF32;
1106+ r := Top;
1107+ x := RegIn(k, depth - 1); { its xmm register }
1108+ if big then begin
1109+ { above high(I64): halve, keeping the low bit, and double }
1110+ L1 := NoLabel; L2 := NoLabel;
1111+ TestRR(r, r);
1112+ Jcc(ccS, L1);
1113+ Cvtsi2s(x, r, f);
1114+ Jmp(L2);
1115+ FixLink(L1);
1116+ MovRR(RCX, r);
1117+ ShiftI(shShr, RCX, 1);
1118+ AluI(aluAnd, r, 1);
1119+ Alu(aluOr, RCX, r);
1120+ Cvtsi2s(x, RCX, f);
1121+ Sse($58, x, x, f); { adds it to itself: doubles }
1122+ FixLink(L2);
1123+ end else Cvtsi2s(x, r, f);
1124+ stack[depth - 1].k := k;
1125+end;
1126+
1127+{ The real of kind k on top, truncated to an integer }
1128+procedure RealToInt(k: TKind);
1129+var x: longint;
1130+begin
1131+ x := Top;
1132+ Cvtts2si(RegIn(kWord, depth - 1), x, k = kF32);
1133+ stack[depth - 1].k := kWord;
1134+end;
1135+
1136+{ The real of kind k on top, as the other kind }
1137+procedure RealToReal(k: TKind);
1138+var x: longint;
1139+begin
1140+ x := Top;
1141+ Sse($5A, x, x, k = kF32); { cvtss2sd, or cvtsd2ss }
1142+ if k = kF32 then stack[depth - 1].k := kF64 else stack[depth - 1].k := kF32;
1143+end;
1144+
1145+{ Whether the slices in the frame at a and b (the offsets of their
1146+ pointers, the lengths 8 bytes on) are equal (or not, if not eq): the
1147+ lengths, then the bytes, len shl shift of them, compared where the
1148+ comparison stands. }
1149+procedure CompareSeq(a, b: int64; shift: longint; eq: boolean);
1150+var differ, r: longint;
1151+begin
1152+ ClobberArgs;
1153+ r := Target;
1154+ Load(RCX, Mem(RBP, b + 8), 8, false);
1155+ AluM(aluCmp, RCX, Mem(RBP, a + 8));
1156+ differ := NoLabel;
1157+ Jcc(ccNE, differ);
1158+ Load(RSI, Mem(RBP, b), 8, false);
1159+ Load(RDI, Mem(RBP, a), 8, false);
1160+ if shift > 0 then ShiftI(shShl, RCX, shift);
1161+ { repe cmpsb with rcx = 0 leaves the flags alone, so make them say
1162+ equal first, which is right if there are no bytes }
1163+ Alu(aluCmp, RCX, RCX);
1164+ RepeCmpsb;
1165+ FixLink(differ);
1166+ if eq then SetCC(ccE, r) else SetCC(ccNE, r);
1167+ Computed(kWord);
1168+end;
1169+
1170+{ An error points at its message's length, an 8-byte word, with the
1171+ text after it; nil is no error. Pops one, and makes the slice of its
1172+ message at tmp, empty for nil. }
1173+procedure ErrorText(tmp: int64);
1174+var L: longint;
1175+begin
1176+ PopTo(RAX);
1177+ MovRI(RCX, 0);
1178+ L := NoLabel;
1179+ TestRR(RAX, RAX);
1180+ Jcc(ccE, L);
1181+ Load(RCX, Mem(RAX, 0), 8, false);
1182+ Lea(RAX, Mem(RAX, 8));
1183+ FixLink(L);
1184+ Store(Mem(RBP, tmp), RAX, 8);
1185+ Store(Mem(RBP, tmp + 8), RCX, 8);
1186+end;
1187+
1188+{ Pops a step and an integer variable's address, and adds the step to
1189+ it, or takes it away. }
1190+procedure IncDec(size: longint; signed, dec: boolean);
1191+var r, y, op: longint; v: int64; a: TAdr;
1192+begin
1193+ if TopConst(v) and Fits32(v) then begin
1194+ Drop;
1195+ a.base := bStack; a.off := 0;
1196+ if dec then op := aluSub else op := aluAdd;
1197+ AluMI(op, Place(a, RCX), v, size);
1198+ exit;
1199+ end;
1200+ r := Operands(y);
1201+ Drop;
1202+ Load(RAX, Mem(r, 0), size, signed);
1203+ if dec then Alu(aluSub, RAX, y) else Alu(aluAdd, RAX, y);
1204+ Store(Mem(r, 0), RAX, size);
1205+end;
1206+
1207+{ INC or DEC of the variable in register r, by the value on top; a
1208+ narrow one wraps at its width }
1209+procedure IncDecReg(r, size: longint; signed, dec: boolean);
1210+var y, op: longint; v: int64;
1211+begin
1212+ if dec then op := aluSub else op := aluAdd;
1213+ if TopConst(v) and Fits32(v) then AluI(op, r, v)
1214+ else begin y := Top; Alu(op, r, y) end;
1215+ Drop;
1216+ if size < 8 then Extend(r, size, signed);
1217+end;
1218+
1219+{ The pointer on top, which NEW got, to size zero bytes unless nil }
1220+procedure ZeroNew(size: int64);
1221+var L, r: longint;
1222+begin
1223+ ClobberArgs;
1224+ r := Top;
1225+ L := NoLabel;
1226+ TestRR(r, r);
1227+ Jcc(ccE, L);
1228+ MovRR(RDI, r);
1229+ MovRI(RCX, size);
1230+ MovRI(RAX, 0);
1231+ RepStosb;
1232+ FixLink(L);
1233+end;
1234+
1235+{ CAS(p, old, new), XCHG(p, v) or XADD(p, v), from the stack: the
1236+ result where p was }
1237+procedure Atomic(which: longint);
1238+var r, n: longint;
1239+begin
1240+ ReadMems(depth - 2 - ord(which = bCas)); { what it writes may be one }
1241+ if which = bCas then begin n := Top; Drop end;
1242+ PopTo(RAX); { cmpxchg compares with rax, so CAS's old value goes there }
1243+ r := Top;
1244+ case which of
1245+ bCas: begin LockCmpxchg(Mem(r, 0), n); SetCC(ccE, r) end;
1246+ bXchg: begin Xchg(Mem(r, 0), RAX); MovRR(r, RAX) end;
1247+ bXadd: begin LockXadd(Mem(r, 0), RAX); MovRR(r, RAX) end;
1248+ end;
1249+ stack[depth - 1].k := kWord;
1250+end;
1251+
1252+{ The system call and its arguments, n values on the stack. Linux takes
1253+ the number in rax and the arguments in rdi, rsi, rdx, r10, r8 and r9,
1254+ and the syscall instruction clobbers rcx and r11. Every value in a
1255+ register is spilled first, as r8 to r11 are the stack's registers,
1256+ and the arguments are loaded from their slots. }
1257+procedure SysCall(n: longint);
1258+const SysRegs: array[0..6] of longint = (RAX, RDI, RSI, RDX, R10, R8, R9);
1259+var i: longint;
1260+begin
1261+ ClobberArgs;
1262+ SpillBelow(depth);
1263+ for i := 0 to n - 1 do ValueTo(depth - n + i, SysRegs[i]);
1264+ for i := 1 to n do Drop;
1265+ x64.Syscall;
1266+ MovRR(Target, RAX);
1267+ Computed(kWord);
1268+end;
1269+
1270+procedure Fence;
1271+begin
1272+ Mfence;
1273+end;
1274+
1275+{ Jumps. A label is the chain of the jumps to it, until it is placed. }
1276+
1277+procedure Jump(var L: longint);
1278+begin
1279+ Jmp(L);
1280+end;
1281+
1282+{ Pops a BOOL, and jumps if it is when }
1283+procedure JumpIf(var L: longint; when: boolean);
1284+var r: longint;
1285+begin
1286+ r := Peek(depth - 1);
1287+ Drop;
1288+ TestRR(r, r);
1289+ if when then Jcc(ccNE, L) else Jcc(ccE, L);
1290+end;
1291+
1292+{ Pops two integers, and jumps if the left op the right }
1293+procedure JumpCmp(op: TSym; signed: boolean; var L: longint);
1294+const
1295+ CcSigned: array[sEql..sGeq] of longint = (ccE, ccNE, ccL, ccLE, ccG, ccGE);
1296+ CcUnsigned: array[sEql..sGeq] of longint = (ccE, ccNE, ccB, ccBE, ccA, ccAE);
1297+var r, y: longint; v: int64; m: TMem;
1298+begin
1299+ { a comparison changes neither: a variable's register will do }
1300+ if TopConst(v) then begin Drop; r := Peek(depth - 1); CmpI(r, v) end
1301+ else if TopInMem then begin m := stack[depth - 1].m; Drop; r := Peek(depth - 1); AluM(aluCmp, r, m) end
1302+ else begin y := Peek(depth - 1); Drop; r := Peek(depth - 1); Alu(aluCmp, r, y) end;
1303+ Drop;
1304+ if signed then Jcc(CcSigned[op], L) else Jcc(CcUnsigned[op], L);
1305+end;
1306+
1307+{ JumpCmp out of an expression, past code that may spill: the values
1308+ under the two compared are spilled first, so that they are where the
1309+ code after the landing place expects them, whichever way it came. In
1310+ v + (a < b and f(x) = 0), a call to f spills v on the way through, so
1311+ v must be in its slot too where a < b jumps past the call. }
1312+procedure JumpOut(op: TSym; signed: boolean; var L: longint);
1313+begin
1314+ SpillBelow(depth - 2);
1315+ JumpCmp(op, signed, L);
1316+end;
1317+
1318+{ The two values on top, compared, as a BOOL: true unless notOp, the
1319+ opposite comparison, holds. fj and tj are the chains of jumps, made
1320+ earlier by and, or and not, that are taken when the whole condition is
1321+ false and when it is true; they land here, on the 0 and the 1. }
1322+procedure CondValue(notOp: TSym; signed: boolean; fj, tj: longint);
1323+var r, e: longint;
1324+begin
1325+ JumpOut(notOp, signed, fj);
1326+ FixLink(tj);
1327+ r := Target;
1328+ MovRI(r, 1);
1329+ e := NoLabel;
1330+ Jmp(e);
1331+ FixLink(fj);
1332+ MovRI(r, 0);
1333+ FixLink(e);
1334+ Computed(kWord);
1335+end;
1336+
1337+{ JumpBack, Fix, FixTo and JoinJumps are gen's names for the encoder's,
1338+ so that a port can place jumps its own way. Fix(L) places label L here;
1339+ FixTo(L, top) makes every jump on chain L go to the earlier place top;
1340+ JoinJumps makes one chain of two. }
1341+procedure JumpBack(top: longint);
1342+begin
1343+ JmpBack(top);
1344+end;
1345+
1346+procedure Fix(L: longint);
1347+begin
1348+ FixLink(L);
1349+end;
1350+
1351+{ A jump table, for a match on the integer in frame slot slot, whose
1352+ labels run from lo up for n values. The selector less lo, compared
1353+ unsigned (so below lo is above n too), is out of the table if it
1354+ isn't below n, and goes to the else arm at elseAt, or, if there is
1355+ none, to endL, the end of the match. Else it indexes a table of
1356+ 4-byte offsets, each from the start of the lea, that follows the
1357+ jump, and the code jumps to its start plus the entry:
1358+
1359+ mov rax, [slot]
1360+ sub rax, lo
1361+ cmp rax, n - 1
1362+ ja else
1363+ lea rcx, [rip + start] start: this very lea
1364+ movsxd rax, [rcx + rax*4 + 17]
1365+ add rax, rcx
1366+ jmp rax
1367+ table: .long arm0 - start, arm1 - start, ...
1368+
1369+ The four instructions after the compare are 7, 5, 3 and 2 bytes, so
1370+ the table is 17 bytes on, which JumpTable checks. It returns start;
1371+ the caller then makes the n entries with TableEntry. }
1372+function JumpTable(slot, lo: int64; n, elseAt: longint; var endL: longint): longint;
1373+const TableAt = 17;
1374+var start: longint;
1375+begin
1376+ Load(RAX, Mem(RBP, slot), 8, false);
1377+ if lo <> 0 then AluI(aluSub, RAX, lo);
1378+ AluI(aluCmp, RAX, n - 1);
1379+ if elseAt <> NoLabel then JccBack(ccA, elseAt) else Jcc(ccA, endL);
1380+ start := pc;
1381+ Lea(RCX, Here);
1382+ Load(RAX, MemIdx(RCX, RAX, 4, TableAt), 4, true);
1383+ Alu(aluAdd, RAX, RCX);
1384+ JmpR(RAX);
1385+ if pc <> start + TableAt then Fatal('internal error: the jump table is not where it was said');
1386+ JumpTable := start;
1387+end;
1388+
1389+{ The next entry of the table that JumpTable started at table: the
1390+ code at target }
1391+procedure TableEntry(table, target: longint);
1392+begin
1393+ Put4(target - table);
1394+end;
1395+
1396+procedure AlignLoop;
1397+begin
1398+ Align(32);
1399+end;
1400+
1401+function JoinJumps(L1, L2: longint): longint;
1402+begin
1403+ JoinJumps := JoinLinks(L1, L2);
1404+end;
1405+
1406+procedure FixTo(L, top: longint);
1407+begin
1408+ FixLinkTo(L, top);
1409+end;
1410+
1411+{ Checks }
1412+
1413+const
1414+ NoBase = -2; { a TMem that is no memory }
1415+ ARegister = -3; { a TMem that is no memory but a register, its index }
1416+
1417+{ The program goes on if the condition cc holds, and otherwise stops
1418+ in Rt.fail(what, a, b, len, at, name), which says what failed at p,
1419+ found by at, which a stub works out from where it was called; what is
1420+ an index a (0), a slice a..b (1), each for a length len, a position a
1421+ of the enumeration called name (2), a slice of a pointer a..b that
1422+ runs backwards (3), or a nil pointer (4). Rt.fail knows 5 and 6, a
1423+ division fault and a stack overflow, which this machine catches
1424+ itself, so no check here has them. The arguments go in rdi, rsi, rdx,
1425+ rcx, r8 and r9: a is in register ra, b in RDX; len is in memory at m,
1426+ or n if m.base is NoBase, or in register m.index if it is ARegister.
1427+ rdi and rsi are passed on as they were, since a parameter may be kept
1428+ in them, for the trap report to show: so a goes to the stub in rax.
1429+ The failing code is out of the way, at the
1430+ procedure's end (EndFails), so that a check that holds costs a jump
1431+ not taken; it has p for its place (at is p's offset in the source),
1432+ never returns, and may use any register once it has read what it
1433+ needs. }
1434+procedure Check(cc, what: longint; const p: TPos; ra: longint; const m: TMem; n: int64; name: longint);
1435+begin
1436+ if numFails > High(fails) then Mark('more than ' + IntStr(High(fails) + 1) + ' checks in one procedure');
1437+ fails[numFails].L := NoLabel;
1438+ Jcc(cc xor 1, fails[numFails].L); { x86's conditions come in pairs, the other one its last bit flipped }
1439+ fails[numFails].what := what;
1440+ fails[numFails].ra := ra;
1441+ fails[numFails].m := m;
1442+ fails[numFails].n := n;
1443+ fails[numFails].name := name;
1444+ fails[numFails].at := p.a;
1445+ inc(numFails);
1446+end;
1447+
1448+{ The failures of the procedure's checks: each gives Rt.fail its values
1449+ and the place of the offending expression, through a stub for its
1450+ kind, which takes the place from where it was called }
1451+procedure EndFails;
1452+var i, line, col: longint;
1453+begin
1454+ for i := 0 to numFails - 1 do
1455+ with fails[i] do begin
1456+ FixLink(L);
1457+ LineCol(at, line, col);
1458+ NoteLine(line, col);
1459+ if ra <> RAX then MovRR(RAX, ra);
1460+ if m.base = NoBase then MovRI(RCX, n)
1461+ else if m.base = ARegister then MovRR(RCX, m.index)
1462+ else Load(RCX, m, 8, false);
1463+ if name >= 0 then Lea(R9, MemRip(name, 0));
1464+ if failStubs[what] < 0 then failStubs[what] := NewChunk(secText, Intern('Rt', 2), Intern(@StubNames[what][1], 6));
1465+ CallChunk(failStubs[what]);
1466+ end;
1467+ numFails := 0;
1468+end;
1469+
1470+{ For Check: a length known here, not in memory }
1471+function NoMem: TMem;
1472+begin
1473+ NoMem := Mem(NoBase, 0);
1474+end;
1475+
1476+{ For Check: a length in register r, a slice's in registers }
1477+function InRegister(r: longint): TMem;
1478+begin
1479+ InRegister := Mem(ARegister, 0);
1480+ InRegister.index := r;
1481+end;
1482+
1483+{ The index on top is below n, unsigned }
1484+procedure CheckIndex(n: int64; const p: TPos);
1485+var r: longint;
1486+begin
1487+ r := Peek(depth - 1);
1488+ CmpI(r, n);
1489+ Check(ccB, 0, p, r, NoMem, n, -1);
1490+end;
1491+
1492+{ The integer on top is a position of an enumeration of n names }
1493+procedure CheckEnum(n: int64; name: longint; const p: TPos);
1494+var r: longint;
1495+begin
1496+ r := Top;
1497+ CmpI(r, n);
1498+ Check(ccB, 2, p, r, NoMem, n, name);
1499+end;
1500+
1501+{ The address on top, from a pointer, which is to be used reach bytes
1502+ past: the program stops if it is nil, unless the machine would stop
1503+ it, as for a reach within NilPage. }
1504+procedure CheckNil(reach: int64; const p: TPos);
1505+var r: longint;
1506+begin
1507+ if reach <= NilPage then exit;
1508+ r := Top;
1509+ TestRR(r, r);
1510+ Check(ccNE, 4, p, r, NoMem, 0, -1);
1511+end;
1512+
1513+{ The displacement disp of an element of size bytes, with the offset of
1514+ the index on top taken into it if it fits: s[k - 1] is [r13 + r9 * 8
1515+ - 8] }
1516+function IndexOff(size, disp: int64): int64;
1517+begin
1518+ IndexOff := disp;
1519+ if Fits32(disp + stack[depth - 1].off * size) then IndexOff := disp + TakeOff(depth - 1) * size;
1520+end;
1521+
1522+{ Pops an index, and the address of the slice at a if it is on the
1523+ stack, and pushes the address of its element of size bytes: the
1524+ index, checked against the length, times size, plus the pointer.
1525+ It is worked out in the index's own register, which then holds the
1526+ address; but if the slice's address is on the stack, under the
1527+ index, the element's register is the one that holds that, still
1528+ needed, so the work is done in rax. A slice in registers is
1529+ compared with and added to them; for an element of 1, 2, 4 or 8
1530+ bytes, its address is only noted, as the operand [pointer + index *
1531+ size], to be read or written where it is used (lIdx). }
1532+procedure IndexSlice(const a: TAdr; size: int64; checked: boolean; const p: TPos);
1533+var m, ml: TMem; r: longint; inRax: boolean; o: int64;
1534+begin
1535+ if (a.base = bReg) and (size in [1, 2, 4, 8]) then begin
1536+ o := 0;
1537+ if not checked then o := IndexOff(size, 0);
1538+ r := Peek(depth - 1);
1539+ if checked then begin
1540+ Alu(aluCmp, r, a.hi);
1541+ Check(ccB, 0, p, r, InRegister(a.hi), 0, -1);
1542+ end;
1543+ Drop;
1544+ NewMem(lIdx, MemIdx(a.chunk, r, size, o), kWord, 8, false);
1545+ exit;
1546+ end;
1547+ inRax := a.base = bStack;
1548+ if inRax then begin r := RAX; PopTo(RAX) end
1549+ else begin r := Top; Drop end;
1550+ if a.base = bReg then begin
1551+ if checked then begin
1552+ Alu(aluCmp, r, a.hi);
1553+ Check(ccB, 0, p, r, InRegister(a.hi), 0, -1);
1554+ end;
1555+ MulI(r, size);
1556+ Alu(aluAdd, r, a.chunk);
1557+ end else begin
1558+ m := Place(a, RCX);
1559+ ml := m; ml.disp := ml.disp + 8;
1560+ if checked then begin
1561+ AluM(aluCmp, r, ml);
1562+ Check(ccB, 0, p, r, ml, 0, -1);
1563+ end;
1564+ MulI(r, size);
1565+ AluM(aluAdd, r, m);
1566+ end;
1567+ if inRax then MovRR(Target, RAX)
1568+ else Claim(depth, kWord); { the index's register again, now for the address }
1569+ Computed(kWord);
1570+end;
1571+
1572+{ Pops an index, checked, and makes the address of the element it
1573+ picks of the array at a. An element of 1, 2,
1574+ 4 or 8 bytes is only noted, as the operand [base + index * size]
1575+ (lIdx): an array in the frame has rbp as its base, and one in a
1576+ chunk, if the index is a variable's register, its address made in
1577+ the value's own register. Any other is added up. }
1578+procedure IndexArray(const a: TAdr; size: int64);
1579+var r, b: longint; o: int64;
1580+begin
1581+ if (size in [1, 2, 4, 8]) and (a.base = bFrame) then begin
1582+ o := IndexOff(size, a.off);
1583+ r := Peek(depth - 1);
1584+ Drop;
1585+ NewMem(lIdx, MemIdx(RBP, r, size, o), kWord, 8, false);
1586+ end else if (size in [1, 2, 4, 8]) and (a.base = bGlobal) and (stack[depth - 1].loc = lHeld) then begin
1587+ o := IndexOff(size, 0);
1588+ r := Peek(depth - 1);
1589+ Drop;
1590+ b := Target;
1591+ Lea(b, MemRip(a.chunk, a.off));
1592+ NewMem(lIdx, MemIdx(b, r, size, o), kWord, 8, false);
1593+ end else begin
1594+ MulI(Top, size);
1595+ PushAdr(a);
1596+ Op(sPlus, kWord, 8, false);
1597+ end;
1598+end;
1599+
1600+{ Pops lo and hi, and the address of the array or slice at a if it is
1601+ on the stack, and makes the slice lo..hi of it, with elements of size
1602+ bytes, in the frame at tmp; the array has n elements. }
1603+procedure Slice(const a: TAdr; isArray: boolean; n, size, tmp: int64; checked: boolean; const p: TPos);
1604+var m, ml: TMem;
1605+begin
1606+ PopTo(RDX);
1607+ PopTo(RCX);
1608+ if a.base = bSlot then ClobberArgs; { Place loads its slot into rdi }
1609+ if a.base = bReg then ml := InRegister(a.hi) { a slice in registers }
1610+ else begin
1611+ m := Place(a, RDI);
1612+ ml := m; ml.disp := ml.disp + 8;
1613+ end;
1614+ if checked then begin
1615+ { two checks, both unsigned, so that a negative bound fails too:
1616+ hi against the length, then lo against hi }
1617+ if isArray then begin CmpI(RDX, n); ml := NoMem end
1618+ else if a.base = bReg then Alu(aluCmp, RDX, a.hi)
1619+ else AluM(aluCmp, RDX, ml);
1620+ Check(ccBE, 1, p, RCX, ml, n, -1);
1621+ Alu(aluCmp, RCX, RDX);
1622+ Check(ccBE, 1, p, RCX, ml, n, -1);
1623+ end;
1624+ MovRR(RAX, RDX);
1625+ Alu(aluSub, RAX, RCX);
1626+ Store(Mem(RBP, tmp + 8), RAX, 8);
1627+ MulI(RCX, size);
1628+ if isArray then Lea(RAX, m)
1629+ else if a.base = bReg then MovRR(RAX, a.chunk)
1630+ else Load(RAX, m, 8, false);
1631+ Alu(aluAdd, RAX, RCX);
1632+ Store(Mem(RBP, tmp), RAX, 8);
1633+end;
1634+
1635+{ COPY: the elements of the slice in the frame at sOff, of size bytes
1636+ each, to the start of the one at dOff, which must be at least as long
1637+ (the source may be shorter), as one block; backwards when the
1638+ destination is above the source, so that an overlap comes out right. }
1639+procedure CopySlice(dOff, sOff, size: int64; checked: boolean; const p: TPos);
1640+var ml: TMem; L, E: longint;
1641+begin
1642+ ClobberArgs;
1643+ Load(RDX, Mem(RBP, sOff + 8), 8, false);
1644+ if checked then begin
1645+ ml := Mem(RBP, dOff + 8);
1646+ MovRI(RAX, 0);
1647+ AluM(aluCmp, RDX, ml);
1648+ Check(ccBE, 1, p, RAX, ml, 0, -1);
1649+ end;
1650+ MovRR(RCX, RDX);
1651+ MulI(RCX, size);
1652+ Load(RSI, Mem(RBP, sOff), 8, false);
1653+ Load(RDI, Mem(RBP, dOff), 8, false);
1654+ Alu(aluCmp, RDI, RSI);
1655+ L := NoLabel;
1656+ Jcc(ccBE, L); { the destination is not above: forwards, at L }
1657+ { backwards: std makes rep movsb run downward, so it starts at the
1658+ last byte of each }
1659+ Lea(RSI, MemIdx(RSI, RCX, 1, -1));
1660+ Lea(RDI, MemIdx(RDI, RCX, 1, -1));
1661+ Std;
1662+ RepMovsb;
1663+ Cld;
1664+ E := NoLabel;
1665+ Jmp(E);
1666+ FixLink(L);
1667+ RepMovsb;
1668+ FixLink(E);
1669+end;
1670+
1671+{ Pops a pointer, lo and hi, and makes the slice p[lo..hi] at tmp. Its
1672+ bounds can't be known, but it can't run backwards. }
1673+procedure SlicePtr(size, tmp: int64; checked: boolean; const p: TPos);
1674+begin
1675+ ClobberArgs;
1676+ PopTo(RDX);
1677+ PopTo(RCX);
1678+ PopTo(RDI);
1679+ if checked then begin
1680+ Alu(aluCmp, RCX, RDX);
1681+ Check(ccLE, 3, p, RCX, NoMem, 0, -1);
1682+ end;
1683+ MovRR(RAX, RDX);
1684+ Alu(aluSub, RAX, RCX);
1685+ Store(Mem(RBP, tmp + 8), RAX, 8);
1686+ MulI(RCX, size);
1687+ Alu(aluAdd, RCX, RDI);
1688+ Store(Mem(RBP, tmp), RCX, 8);
1689+end;
1690+
1691+{ Calls }
1692+
1693+{ The call c, its c.n arguments the values on top of the stack, in
1694+ registers, noted as constants or spilled. They go to registers or the
1695+ machine's stack, the procedure is called, and its result, if any,
1696+ comes back: one value is pushed, two results are pushed as two values,
1697+ a slice or a record is stored in the temporary c.ret.
1698+
1699+ ni and nf count the integer and the real registers used so far, k the
1700+ arguments on the machine's stack, and pad is 1 when a padding quadword
1701+ is needed. }
1702+
1703+procedure Call(var c: TCall);
1704+var
1705+ res: PType; i, ni, nf, k, pad, r, first: longint;
1706+ onStack: array[0..63] of boolean; late: array[4..5] of longint;
1707+begin
1708+ { the arguments are the c.n values on top, where computing them left
1709+ them; the registers in use under them are saved around the call }
1710+ ClobberArgs;
1711+ first := depth - c.n;
1712+ SpillBelow(first);
1713+ res := c.sig^.base;
1714+ c.ret := 0;
1715+ ni := 0; nf := 0;
1716+ if (res <> nil) and (BehindPointer(res) or (res^.form = fSlice)) then begin
1717+ c.ret := AllocTemp(res^.size, res^.align);
1718+ if BehindPointer(res) then ni := 1;
1719+ end;
1720+ { the System V classes: each argument in the next free register of
1721+ its kind, or else on the stack }
1722+ k := 0;
1723+ for i := 0 to c.n - 1 do begin
1724+ if c.isF[i] then begin onStack[i] := nf >= 8; if nf < 8 then inc(nf) end
1725+ else begin
1726+ { a slice's words both go in registers, or both on the stack }
1727+ if (i > 0) and c.pair[i - 1] then onStack[i] := onStack[i - 1]
1728+ else if c.pair[i] then onStack[i] := ni > 4
1729+ else onStack[i] := ni >= 6;
1730+ if not onStack[i] then inc(ni);
1731+ end;
1732+ if onStack[i] then inc(k);
1733+ end;
1734+ { System V wants rsp a multiple of 16 at the call. A procedure's body
1735+ has it so (push rbp, and a frame size that is a multiple of 16), so
1736+ a quadword of padding makes the count pushed since even. The stack
1737+ arguments go right to left, so that the first is at the lowest
1738+ address. }
1739+ pad := ord(odd(pushed + k));
1740+ if pad <> 0 then AluI(aluSub, RSP, 8);
1741+ for i := c.n - 1 downto 0 do
1742+ if onStack[i] then begin
1743+ ValueTo(first + i, RAX);
1744+ Push(RAX);
1745+ end;
1746+ ni := 0; nf := 0;
1747+ late[4] := -1; late[5] := -1;
1748+ if (c.ret <> 0) and BehindPointer(res) then begin Lea(RDI, Mem(RBP, c.ret)); ni := 1 end;
1749+ { rdi, rsi, rdx, rcx and the xmm registers first; r8 and r9 last, as
1750+ they are stack registers and may hold arguments not yet moved: late
1751+ is the value for each. The fifth goes through rax, so that writing r8
1752+ doesn't destroy a value still wanted for r9. }
1753+ for i := 0 to c.n - 1 do
1754+ if not onStack[i] then
1755+ if c.isF[i] then begin
1756+ XValueTo(first + i, nf);
1757+ inc(nf);
1758+ end else begin
1759+ if ni < 4 then ValueTo(first + i, IntRegs[ni]) else late[ni] := first + i;
1760+ inc(ni);
1761+ end;
1762+ if late[4] >= 0 then ValueTo(late[4], RAX);
1763+ if late[5] >= 0 then ValueTo(late[5], R9);
1764+ if late[4] >= 0 then MovRR(R8, RAX);
1765+ for i := 1 to c.n do Drop;
1766+ { a procedure taking ... is told in al how many xmm registers it got }
1767+ if c.sig^.variadic then MovRI(RAX, nf);
1768+ if c.ext then CallM(MemRip(c.chunk, 0))
1769+ else if c.chunk >= 0 then CallChunk(c.chunk)
1770+ else begin
1771+ { r11 is scratch: caller-saved, carrying no argument, and free,
1772+ as the value stack was spilled above }
1773+ Load(R11, Mem(RBP, c.target), 8, false);
1774+ CallR(R11);
1775+ end;
1776+ if k + pad > 0 then AluI(aluAdd, RSP, 8 * (k + pad));
1777+ { the variables in xmm registers, which the call may have changed,
1778+ from their slots }
1779+ for i := 0 to 3 do
1780+ if regMask and (1 shl (XBit + i)) <> 0 then MovsXM(XVarRegs[i] - XmmVar, Mem(RBP, homes[i]), false);
1781+ { the result: a slice in rax and rdx goes to the caller's temporary,
1782+ two results on the stack, the first under the second, and a single
1783+ value on top }
1784+ if res = nil then
1785+ { nothing comes back }
1786+ else if res^.form = fSlice then begin
1787+ Store(Mem(RBP, c.ret), RAX, 8);
1788+ Store(Mem(RBP, c.ret + 8), RDX, 8);
1789+ end else if InTwoRegs(res) then begin
1790+ MovRR(Target, RAX); Computed(kWord);
1791+ MovRR(Target, RDX); Computed(kWord);
1792+ end else if (c.ret = 0) and (res^.form = fReal) then begin
1793+ MovX(XTarget, 0);
1794+ Computed(KindOf(res));
1795+ end else if c.ret = 0 then begin
1796+ r := Target;
1797+ MovRR(r, RAX);
1798+ if res^.form = fBool then Extend(r, 1, false)
1799+ else if (res^.form = fInt) and (res^.size < 8) then Extend(r, res^.size, res^.signed);
1800+ Computed(KindOf(res));
1801+ end;
1802+end;
1803+
1804+{ Frames }
1805+
1806+{ A slot of size bytes in the frame: its offset from rbp, negative, as
1807+ the frame grows down. A temporary is released at the end of its
1808+ statement (TempMark, ReleaseTemps); AllocPerm's lasts the procedure. }
1809+function AllocTemp(size, align: int64): int64;
1810+begin
1811+ if align < 1 then align := 1;
1812+ frameTop := AlignUp(frameTop + size, align);
1813+ if frameTop > frameMax then frameMax := frameTop;
1814+ AllocTemp := -frameTop;
1815+end;
1816+
1817+function AllocPerm(size, align: int64): int64;
1818+begin
1819+ AllocPerm := AllocTemp(size, align);
1820+ permTop := frameTop;
1821+end;
1822+
1823+function TempMark: int64;
1824+begin
1825+ TempMark := frameTop;
1826+end;
1827+
1828+{ The slots allocated since the mark m are free again, but those
1829+ AllocPerm made stay }
1830+procedure ReleaseTemps(m: int64);
1831+begin
1832+ if m < permTop then m := permTop;
1833+ frameTop := m;
1834+end;
1835+
1836+{ Every slot used so far stays reserved for the rest of the procedure:
1837+ a deferred statement's temporaries live until it runs. }
1838+procedure KeepTemps;
1839+begin
1840+ frameTop := frameMax;
1841+ permTop := frameMax;
1842+end;
1843+
1844+{ The parameters' places: each in a frame slot of its own, stored there
1845+ from its register on entry, or above the frame where the caller
1846+ pushed it. A var parameter, and a record or array passed by value,
1847+ holds an address (ind). }
1848+procedure BeginProc(sig: PType; params: PObj);
1849+var p: PObj; ni, nf, k: longint; stackOff: int64; f: boolean;
1850+begin
1851+ frameTop := 0; frameMax := 0; permTop := 0;
1852+ ResetStack(0, 0);
1853+ exitL := NoLabel;
1854+ numIn := 0;
1855+ lost := false;
1856+ kept := 0;
1857+ resType := sig^.base;
1858+ procParams := params;
1859+ regMask := 0;
1860+ ni := 0; nf := 0; stackOff := 16; { stackOff: above the saved rbp and the return address }
1861+ if (resType <> nil) and BehindPointer(resType) then begin
1862+ retSlot := AllocPerm(8, 8);
1863+ inReg[0] := RDI; inSlot[0] := retSlot; inSize[0] := 8; inObj[0] := nil;
1864+ numIn := 1; ni := 1;
1865+ end;
1866+ p := params;
1867+ while p <> nil do begin
1868+ p^.ind := p^.isVar or (IsAggregate(p^.typ) and (p^.typ^.form <> fSlice));
1869+ f := (p^.typ^.form = fReal) and not p^.isVar;
1870+ if (p^.typ^.form = fSlice) and not p^.isVar then begin
1871+ { its two words, in two registers or both on the stack }
1872+ if ni <= 4 then begin
1873+ p^.val := AllocPerm(16, 8);
1874+ for k := 0 to 1 do begin
1875+ inReg[numIn] := IntRegs[ni]; inSlot[numIn] := p^.val + 8 * k;
1876+ inSize[numIn] := 8; inObj[numIn] := p;
1877+ inc(numIn); inc(ni);
1878+ end;
1879+ end else begin
1880+ p^.val := stackOff;
1881+ inc(stackOff, 16);
1882+ end;
1883+ end else if (f and (nf < 8)) or (not f and (ni < 6)) then begin
1884+ p^.val := AllocPerm(8, 8);
1885+ { a real's register, xmm nf, is told from an integer register by
1886+ a negative number (EnterBody decodes it) }
1887+ if f then begin inReg[numIn] := -1 - nf; inc(nf) end
1888+ else begin inReg[numIn] := IntRegs[ni]; inc(ni) end;
1889+ inSlot[numIn] := p^.val;
1890+ inObj[numIn] := p;
1891+ if p^.ind then inSize[numIn] := 8
1892+ else if p^.typ^.form in [fInt, fBool, fEnum, fSet, fReal] then inSize[numIn] := p^.typ^.size
1893+ else inSize[numIn] := 8;
1894+ inc(numIn);
1895+ end else begin
1896+ p^.val := stackOff;
1897+ inc(stackOff, 8);
1898+ end;
1899+ p := p^.next;
1900+ end;
1901+ paramTop := frameTop;
1902+end;
1903+
1904+{ The frame as BeginProc left it, with the parameters' slots only: the
1905+ locals are given theirs again once their registers are chosen. }
1906+procedure ResetLocals;
1907+begin
1908+ frameTop := paramTop; frameMax := paramTop; permTop := paramTop;
1909+end;
1910+
1911+{ The register the word (0, or 1 for a slice's second) of parameter o
1912+ arrives in, or -1 if it comes on the stack or in an xmm register }
1913+function ArrivesIn(o: PObj; word: longint): longint;
1914+var i: longint;
1915+begin
1916+ ArrivesIn := -1;
1917+ for i := 0 to numIn - 1 do
1918+ if (inObj[i] = o) and (inSlot[i] = o^.val + 8 * word) and (inReg[i] >= 0) then ArrivesIn := inReg[i];
1919+end;
1920+
1921+{ Parameter o, of a procedure that calls nothing, stays in the register
1922+ it arrives in if that is rdi or rsi, which only a call or a copy needs:
1923+ no register is saved for it, and nothing is moved. A slice stays only
1924+ if it has both. If the procedure turns out to copy after all, lost is
1925+ set, and it is compiled again with o in memory. }
1926+procedure KeepArrived(o: PObj);
1927+var r: longint;
1928+begin
1929+ r := ArrivesIn(o, 0);
1930+ if o^.typ^.form = fSlice then begin
1931+ if (r = RDI) and (ArrivesIn(o, 1) = RSI) then begin o^.reg := RDI; o^.reg2 := RSI end;
1932+ end else if (r = RDI) or (r = RSI) then o^.reg := r;
1933+end;
1934+
1935+{ Whether parameter o is kept where it arrived }
1936+function KeptIn(o: PObj): boolean;
1937+begin
1938+ KeptIn := (o^.reg = RDI) or (o^.reg = RSI);
1939+end;
1940+
1941+{ The locals in memory have their slots: the prologue zeroes those and
1942+ nothing below. The procedure keeps variables in the registers of
1943+ mask, which are saved next, a quadword each, in slots that need no
1944+ zeroing; the frame as it then stands is where a second try at the
1945+ body starts. }
1946+procedure UseRegs(mask: longint);
1947+var i, k: longint; p: PObj;
1948+begin
1949+ zeroTop := permTop;
1950+ regMask := mask;
1951+ { the parameters left in rdi and rsi, as they arrived }
1952+ kept := 0;
1953+ p := procParams;
1954+ while p <> nil do begin
1955+ if p^.reg in [RDI, RSI] then kept := kept or (1 shl p^.reg);
1956+ if p^.reg2 in [RDI, RSI] then kept := kept or (1 shl p^.reg2);
1957+ p := p^.next;
1958+ end;
1959+ k := 0;
1960+ for i := 0 to 4 do if mask and (1 shl i) <> 0 then inc(k);
1961+ if k > 0 then saveAt := AllocPerm(8 * k, 8);
1962+ frameAt[0] := frameTop; frameAt[1] := frameMax; frameAt[2] := permTop;
1963+end;
1964+
1965+{ The variable in xmm register r of XVarRegs has a slot of 8 bytes at
1966+ slot, kept as it changes }
1967+procedure XHome(r: longint; slot: int64);
1968+begin
1969+ homes[r - XVarRegs[0]] := slot;
1970+end;
1971+
1972+procedure MarkCode(var m: TCodeMark);
1973+begin
1974+ m.pc := pc; m.fixups := numFixups; m.lines := numLines; m.said := SaidCount;
1975+ m.fails := numFails;
1976+end;
1977+
1978+{ The code made since m taken back, as if it had never been made; the
1979+ frame is left as it is }
1980+procedure Rewind(const m: TCodeMark);
1981+begin
1982+ pc := m.pc; numFixups := m.fixups; numLines := m.lines; Unsay(m.said);
1983+ numFails := m.fails;
1984+end;
1985+
1986+{ For a second try at the body: the code as it was at m, and the frame
1987+ as UseRegs found it }
1988+procedure Redo(const m: TCodeMark);
1989+begin
1990+ pc := m.pc; numFixups := m.fixups; numLines := m.lines; Unsay(m.said);
1991+ numFails := 0;
1992+ lost := false;
1993+ frameTop := frameAt[0]; frameMax := frameAt[1]; permTop := frameAt[2];
1994+ exitL := NoLabel;
1995+end;
1996+
1997+{ The prologue, which is for the procedure's first line. Only the
1998+ locals in memory are zeroed, from the parameters' slots down to
1999+ zeroTop: the parameters are stored over their slots next, the
2000+ registers of variables are zeroed in place, their save slots are
2001+ written before they are read, and so is every temporary. }
2002+procedure EnterBody(c, line: longint);
2003+var i, top, r: longint; n: int64; p: PObj;
2004+begin
2005+ BeginChunk(c);
2006+ codeChunk := c;
2007+ NoteLine(line, 1); { a declaration starts a line }
2008+ Push(RBP);
2009+ MovRR(RBP, RSP);
2010+ Say('sub rsp, frame');
2011+ { sub rsp, imm32: always the form with a 32-bit field, so that EndProc
2012+ can patch the frame's size in }
2013+ Put1($48); Put1($81); Put1($EC);
2014+ frameFix := pc; Put4(0);
2015+ n := (AlignUp(zeroTop, 8) - paramTop) div 8;
2016+ if n > 0 then MovRI(RAX, 0);
2017+ if n <= 4 then
2018+ for i := 1 to n do Store(Mem(RBP, -paramTop - 8 * i), RAX, 8)
2019+ else begin
2020+ { a quadword at a time: r10 runs from -n up to 0, and the store's
2021+ address is scaled by it }
2022+ MovRI(R10, -n);
2023+ top := pc;
2024+ Store(MemIdx(RBP, R10, 8, -paramTop), RAX, 8);
2025+ AluI(aluAdd, R10, 1);
2026+ JccBack(ccNE, top);
2027+ end;
2028+ { each register that holds a variable is saved, for the caller, and
2029+ zeroed, as a variable starts at zero }
2030+ chunks^[c].saveMask := regMask and (1 shl XBit - 1);
2031+ chunks^[c].saveAt := saveAt;
2032+ n := 0;
2033+ for i := 0 to 4 do
2034+ if regMask and (1 shl i) <> 0 then begin
2035+ Store(Mem(RBP, saveAt + 8 * n), VarRegs[i], 8);
2036+ MovRI(VarRegs[i], 0);
2037+ inc(n);
2038+ end;
2039+ { and each xmm register that holds a variable, zeroed, as its slot
2040+ is: the caller keeps its own }
2041+ for i := 0 to 3 do
2042+ if regMask and (1 shl (XBit + i)) <> 0 then begin
2043+ MovRI(RAX, 0);
2044+ MovqXR(XVarRegs[i] - XmmVar, RAX);
2045+ end;
2046+ { the parameters that came in registers, to their slots or, for a
2047+ register variable, to its register: a slice's second word, the one
2048+ for the slot 8 bytes into its own, to its length's }
2049+ for i := 0 to numIn - 1 do
2050+ if inReg[i] < 0 then begin
2051+ MovsMX(Mem(RBP, inSlot[i]), -1 - inReg[i], false);
2052+ if inObj[i]^.reg <> 0 then MovX(inObj[i]^.reg - XmmVar, -1 - inReg[i]);
2053+ end
2054+ else if (inObj[i] <> nil) and (inObj[i]^.reg <> 0) then begin
2055+ r := inObj[i]^.reg;
2056+ if inSlot[i] <> inObj[i]^.val then r := inObj[i]^.reg2;
2057+ if r <> inReg[i] then MovRR(r, inReg[i]); { else it is kept where it is }
2058+ if inSize[i] < 8 then Extend(r, inSize[i], inObj[i]^.typ^.signed);
2059+ end else Store(Mem(RBP, inSlot[i]), inReg[i], inSize[i]);
2060+ { a register variable's parameter that came on the stack, above the
2061+ frame (val > 0), is loaded from there }
2062+ p := procParams;
2063+ while p <> nil do begin
2064+ if (p^.reg <> 0) and (p^.val > 0) then
2065+ if p^.typ^.form = fReal then MovsXM(p^.reg - XmmVar, Mem(RBP, p^.val), p^.typ^.size = 4)
2066+ else if p^.typ^.form in [fInt, fBool, fEnum, fSet] then
2067+ Load(p^.reg, Mem(RBP, p^.val), p^.typ^.size, p^.typ^.signed)
2068+ else begin
2069+ Load(p^.reg, Mem(RBP, p^.val), 8, false);
2070+ if p^.typ^.form = fSlice then Load(p^.reg2, Mem(RBP, p^.val + 8), 8, false);
2071+ end;
2072+ p := p^.next;
2073+ end;
2074+end;
2075+
2076+{ Pops one of several results, a value of size bytes, into its place
2077+ off bytes into the caller's, behind the hidden pointer. }
2078+procedure ResultTo(off: int64; size: longint);
2079+var r: longint; real: boolean;
2080+begin
2081+ r := Top;
2082+ real := IsReal(depth - 1);
2083+ Drop;
2084+ Load(RCX, Mem(RBP, retSlot), 8, false);
2085+ if real then MovsMX(Mem(RCX, off), r, size = 4)
2086+ else Store(Mem(RCX, off), r, size);
2087+end;
2088+
2089+{ Pops an address, and copies size bytes from it to the result, off
2090+ bytes into it. }
2091+procedure CopyResult(off, size: int64);
2092+begin
2093+ ClobberArgs;
2094+ PopTo(RSI);
2095+ Load(RDI, Mem(RBP, retSlot), 8, false);
2096+ if off <> 0 then Lea(RDI, Mem(RDI, off));
2097+ CopyBytes(size);
2098+end;
2099+
2100+{ return: the result, a value on top, goes in rax or xmm0; two words,
2101+ the two values on top, in rax and rdx; one behind the hidden pointer
2102+ goes back with that pointer in rax. }
2103+procedure ReturnJump;
2104+begin
2105+ if resType <> nil then
2106+ if BehindPointer(resType) then Load(RAX, Mem(RBP, retSlot), 8, false)
2107+ else if InTwoRegs(resType) then begin
2108+ PopTo(RDX);
2109+ PopTo(RAX);
2110+ end else begin
2111+ if resType^.form = fReal then begin XValueTo(depth - 1, 0); Drop end
2112+ else PopTo(RAX);
2113+ end;
2114+ Jmp(exitL);
2115+end;
2116+
2117+{ The first of what try does where the error isn't nil (the report, 7.8):
2118+ the machine's stack made even, as the deferred statements about to be
2119+ run expect to find it. try can stand among the arguments of another
2120+ call, where quadwords have been pushed. Nothing is lost: the frame is
2121+ above rsp, and the code returns through the frame pointer. }
2122+procedure TryAlign;
2123+begin
2124+ AluI(aluAnd, RSP, -16);
2125+end;
2126+
2127+{ The rest of it: the procedure returns the error in the frame slot, and
2128+ a zero for each of its other results. Only code is made: no entry of
2129+ the stack of values is touched, since the code that follows is the
2130+ code for an error that is nil, with the stack as it was. }
2131+procedure TryReturn(slot: int64);
2132+var f: PObj;
2133+begin
2134+ if BehindPointer(resType) then begin
2135+ Load(RDI, Mem(RBP, retSlot), 8, false);
2136+ MovRI(RCX, resType^.size);
2137+ MovRI(RAX, 0);
2138+ RepStosb;
2139+ f := resType^.fields;
2140+ while f^.next <> nil do f := f^.next;
2141+ Load(RCX, Mem(RBP, slot), 8, false);
2142+ Load(RDX, Mem(RBP, retSlot), 8, false);
2143+ Store(Mem(RDX, f^.val), RCX, 8);
2144+ Load(RAX, Mem(RBP, retSlot), 8, false);
2145+ end else if InTwoRegs(resType) then begin
2146+ Load(RDX, Mem(RBP, slot), 8, false);
2147+ MovRI(RAX, 0);
2148+ end else Load(RAX, Mem(RBP, slot), 8, false);
2149+ Jmp(exitL);
2150+end;
2151+
2152+{ The end of the procedure in chunk c: the code that returns, and the
2153+ frame's size, known only now, patched into its prologue. If it is
2154+ open, running off its end, it returns zeros. }
2155+procedure EndProc(c: longint; open: boolean);
2156+var n: int64; i: longint;
2157+begin
2158+ codeChunk := -1;
2159+ if (depth <> 0) or (pushed <> 0) then Fatal('internal error: stack depth');
2160+ if open then begin
2161+ if BehindPointer(resType) then begin
2162+ Load(RDI, Mem(RBP, retSlot), 8, false);
2163+ MovRI(RCX, resType^.size);
2164+ MovRI(RAX, 0);
2165+ RepStosb;
2166+ Load(RAX, Mem(RBP, retSlot), 8, false);
2167+ end else begin
2168+ MovRI(RAX, 0);
2169+ if InTwoRegs(resType) then MovRI(RDX, 0);
2170+ MovqXR(0, RAX);
2171+ end;
2172+ end else DropJumpTo(exitL);
2173+ FixLink(exitL);
2174+ n := 0;
2175+ for i := 0 to 4 do
2176+ if regMask and (1 shl i) <> 0 then begin
2177+ Load(VarRegs[i], Mem(RBP, saveAt + 8 * n), 8, false);
2178+ inc(n);
2179+ end;
2180+ Leave;
2181+ Ret;
2182+ EndFails;
2183+ n := AlignUp(frameMax, 16);
2184+ if n < 16 then n := 16;
2185+ if n > high(longint) then Mark('frame too big');
2186+ Put4At(frameFix, n);
2187+ { the listing's text for the sub, which starts 3 bytes (REX.W, opcode,
2188+ ModRM) before its immediate }
2189+ Restate(frameFix - 3, 'sub rsp, ' + IntStr(n));
2190+ EndChunk(c);
2191+end;
2192+
2193+{ A deferred statement is compiled where it stands, as a subroutine of
2194+ its procedure that the code jumps over, in the procedure's own frame
2195+ (the same rbp), so that it sees all its variables; DeferBegin gives its address
2196+ and starts it, with the return address pushed. The stack is empty
2197+ where it is called, and where it begins. }
2198+function DeferBegin(var L, saved: longint): longint;
2199+begin
2200+ Jmp(L);
2201+ saved := pushed;
2202+ pushed := 1;
2203+ DeferBegin := pc;
2204+end;
2205+
2206+procedure DeferEnd(L, saved: longint);
2207+begin
2208+ KeepTemps;
2209+ Ret;
2210+ FixLink(L);
2211+ pushed := saved;
2212+end;
2213+
2214+procedure RunDefer(at: longint);
2215+begin
2216+ CallBack(at);
2217+end;
2218+
2219+{ The entry point, _start, and its chunk: it saves argc and argv, and
2220+ the address of the places for Rt; runs every used module's body, then
2221+ main; and ends with Rt.exit, its status main's or 0. A dynamic program
2222+ starts as C's crt1 does, through __libc_start_main(main, argc, argv,
2223+ nil, nil, rtld_fini, stack_end), with rsp aligned; its main first
2224+ gives Rt C's exit, in cExit.
2225+
2226+ dynamic: the program uses C. first: the first module, whose chain
2227+ gives the order of the bodies. main: the program's main procedure, or
2228+ nil. cExit and exitProc: the chunks of Rt's cExit and exit. The
2229+ first numLinks of links: the addresses Rt is given, of what the program has: the places, and
2230+ the profiler and calls; what it isn't given, nothing reaches, and the
2231+ linker leaves out. }
2232+function EntryPoint(dynamic: boolean; first: PModule; main: PObj; cExit, exitProc: longint; const links: array of TLink; numLinks: longint): longint;
2233+var entry, start, i: longint; m: PModule;
2234+begin
2235+ entry := NewChunk(secText, -1, Intern('_start', 6));
2236+ if dynamic then begin
2237+ start := NewChunk(secText, -1, Intern('main', 4));
2238+ BeginChunk(entry);
2239+ { at the start rdx holds rtld_fini, from the dynamic loader, and the
2240+ stack argc, then argv }
2241+ MovRI(RBP, 0); { no frame above, where a trace stops }
2242+ MovRR(R9, RDX); { rtld_fini, the sixth argument }
2243+ Pop(RSI); { argc, the second }
2244+ MovRR(RDX, RSP); { argv, the third }
2245+ AluI(aluAnd, RSP, -16);
2246+ Push(RAX); { padding, so that the next push, the seventh }
2247+ Push(RSP); { argument, stack_end, leaves rsp aligned }
2248+ MovRI(R8, 0); { fini and init: none }
2249+ MovRI(RCX, 0);
2250+ Lea(RDI, MemRip(start, 0)); { main, the first argument }
2251+ CallM(MemRip(ExternChunk(Intern('__libc_start_main', 17)), 0));
2252+ Ud2; { it never returns }
2253+ EndChunk(entry);
2254+ BeginChunk(start);
2255+ Push(RBP); { aligns the stack again }
2256+ Store(MemRip(argcChunk, 0), RDI, 8);
2257+ Store(MemRip(argvChunk, 0), RSI, 8);
2258+ Load(RAX, MemRip(ExternChunk(Intern('exit', 4)), 0), 8, false);
2259+ Store(MemRip(cExit, 0), RAX, 8);
2260+ end else begin
2261+ start := entry;
2262+ BeginChunk(entry);
2263+ Load(RAX, Mem(RSP, 0), 8, false);
2264+ Store(MemRip(argcChunk, 0), RAX, 8);
2265+ Lea(RAX, Mem(RSP, 8));
2266+ Store(MemRip(argvChunk, 0), RAX, 8);
2267+ end;
2268+ for i := 0 to numLinks - 1 do begin
2269+ Lea(RAX, MemRip(links[i].chunk, 0));
2270+ Store(MemRip(links[i].into, 0), RAX, 8);
2271+ end;
2272+ m := first;
2273+ while m <> nil do begin
2274+ if m^.used and (m^.body >= 0) then CallChunk(m^.body);
2275+ m := m^.next;
2276+ end;
2277+ if main <> nil then CallChunk(main^.chunk);
2278+ if (main <> nil) and (main^.typ^.base <> nil) then MovRR(RDI, RAX) else MovRI(RDI, 0);
2279+ CallChunk(exitProc);
2280+ Ud2; { exit never returns: trap if it does }
2281+ EndChunk(start);
2282+ { Rt.fail, for the failures of each kind: the place is where the
2283+ check's call is. The return address is the next instruction's, which
2284+ may belong to another line; one byte back is inside the call, so the
2285+ lookup finds the call's line. rsp is aligned for the call, as the
2286+ check's code may have pushed an odd number of quadwords. rdi and rsi
2287+ as the failing code had them go on the stack, as Rt.fail's last two
2288+ arguments, and a comes in rax (EndFails). }
2289+ for i := 0 to High(failStubs) do
2290+ if failStubs[i] >= 0 then begin
2291+ BeginChunk(failStubs[i]);
2292+ Load(R8, Mem(RSP, 0), 8, false);
2293+ AluI(aluSub, R8, 1);
2294+ AluI(aluAnd, RSP, -16);
2295+ Push(RSI);
2296+ Push(RDI);
2297+ MovRR(RSI, RAX);
2298+ MovRI(RDI, i);
2299+ CallChunk(rtFail);
2300+ Ud2;
2301+ EndChunk(failStubs[i]);
2302+ end;
2303+ EntryPoint := entry;
2304+end;
2305+
2306+{ A code procedure: its instructions, read by the assembler (x64.pas),
2307+ are the whole of chunk c }
2308+procedure CodeProc(c: longint; constExpr: TConstFn);
2309+begin
2310+ BeginChunk(c);
2311+ Assemble(constExpr);
2312+ EndChunk(c);
2313+end;
2314+
2315+initialization
2316+ ResetStack(0, 0);
2317+ rtFail := NewChunk(secText, Intern('Rt', 2), Intern('fail', 4));
2318+ argcChunk := NewChunk(secBss, -1, Intern('argc', 4));
2319+ SetBss(argcChunk, 8, 8);
2320+ argvChunk := NewChunk(secBss, -1, Intern('argv', 4));
2321+ SetBss(argvChunk, 8, 8);
2322+end.

seed/item.pas added +1575 -0

@@ -0,0 +1,1575 @@
1+{ item.pas: operands, their types, and what they mean.
2+
3+ The parser describes each operand as an item (TItem), as in Wirth's
4+ compilers: a constant, a variable at an address it can name, a value
5+ on gen's stack, a procedure, a string. The routines here check the
6+ items' types, fold constants, and have gen.pas make the code, as calls
7+ of its stack machine; nothing here knows the machine.
8+
9+ Depends on: scan for errors, sym for types, chunk for data, gen for
10+ code.
11+ Leaves out: the language's syntax, which is parse.pas; the machine,
12+ which is gen.pas. }
13+
14+unit item;
15+
16+{$mode objfpc}{$H-}
17+
18+interface
19+
20+uses scan, diag, sym, chunk, gen;
21+
22+type
23+ TMode = (mConst, mVar, mStack, mProc, mType, mStr, mBuiltin, mCase, mNone, mCond,
24+ mWords); { two results of a call, on the stack, the first under the second }
25+
26+ TItem = record
27+ mode: TMode;
28+ typ: PType;
29+ rel: TSym; { mCond: the comparison of the two integers on
30+ the stack, not yet made, as Wirth's compilers
31+ keep a condition }
32+ relSigned: boolean;
33+ fj, tj: longint; { mCond: the chains of jumps already made that are
34+ taken when the whole condition is false, and when
35+ it is true, not yet given a place (and, or and
36+ not make them); see gen's JumpOut }
37+ val: int64; { mConst: the value, an F64's bits; mStr: its length }
38+ base: TBase; { mVar: what the address is relative to }
39+ chunk: longint; { mVar with bGlobal, mStr: the chunk; bSlot: the slot }
40+ off: int64; { mVar: added to the base }
41+ vol: boolean; { mVar: reached through ^VOLATILE }
42+ isVar: boolean; { mVar: a variable of the program, not a temporary }
43+ odd: boolean; { mVar: in a packed record, so maybe misaligned }
44+ ro: boolean; { mVar: another module's exported variable, or part
45+ of one, which only that module changes }
46+ deref: boolean; { mVar: at an address from a pointer, which may be
47+ nil and isn't tested yet (NilTest) }
48+ obj: PObj; { mProc, mBuiltin, mCase; mVar: the variable named }
49+ pos: TPos; { where it is in the source, for messages }
50+ end;
51+
52+var
53+ demoted: boolean; { Address wanted a register variable's address: its
54+ procedure is compiled again, the variable in memory }
55+ checks: boolean; { the module's index and slice checks are made: it
56+ doesn't say check off }
57+
58+procedure MakeConst(var x: TItem; t: PType; v: int64);
59+function What(const x: TItem): shortstring;
60+procedure MakeReal(var x: TItem; r: double);
61+procedure MakeStr(var x: TItem);
62+procedure MakeItem(var x: TItem; o: PObj);
63+function RealOf(const x: TItem): double;
64+function FrameAdr(off: int64): TAdr;
65+function GlobalAdr(c: longint): TAdr;
66+function AdrOf(const x: TItem): TAdr;
67+
68+procedure UsesReals(const p: TPos);
69+procedure Value(var x: TItem);
70+procedure Address(var x: TItem);
71+procedure Discard(const x: TItem);
72+procedure NilTest(var x: TItem);
73+procedure Coerce(var x: TItem; t: PType);
74+procedure CoerceExact(var x: TItem; t: PType; const help: shortstring);
75+procedure NotReadOnly(const x: TItem);
76+procedure Assign(var dst, src: TItem);
77+procedure CopyToTemp(var x: TItem);
78+function ToSlot(var x: TItem): int64;
79+
80+procedure Deref(var x: TItem);
81+procedure Field(var x: TItem; f: PObj);
82+procedure IndexPrep(var x: TItem);
83+procedure Index(var x, y: TItem);
84+procedure SliceLo(var lo: TItem);
85+procedure Slice(var x, lo, hi: TItem);
86+
87+procedure Neg(var x: TItem);
88+procedure NotOp(var x: TItem);
89+procedure Complement(var x: TItem);
90+procedure Op1(op: TSym; var x: TItem; var L: longint);
91+procedure Op2(op: TSym; var x, y: TItem; L: longint);
92+function IsWord(t: PType): boolean;
93+procedure Convert(var x: TItem; t: PType);
94+
95+procedure BeginCall(var c: TCall; var x: TItem);
96+procedure PassArg(var c: TCall; var a: TItem);
97+procedure EndCall(var c: TCall; var x: TItem);
98+
99+procedure ZeroTemp(var x: TItem; t: PType);
100+procedure Construct(var x: TItem; c: PObj);
101+procedure SetField(const x: TItem; f: PObj; var a: TItem);
102+function MatchBegin(var x: TItem): int64;
103+procedure MatchTag(p: int64; tag: int64; var L: longint);
104+procedure MatchRange(p, lo, hi: int64; var body: longint);
105+procedure CondJump(var x: TItem; var L: longint);
106+procedure CondJumpTrue(var x: TItem; var L: longint);
107+
108+procedure SliceOf(var x: TItem; t: PType; len: int64);
109+procedure TempItem(var x: TItem; t: PType; off: int64);
110+function ScalarSize(t: PType): longint;
111+procedure ForStep(o: PObj; step: int64);
112+procedure ForCmp(o: PObj; const lim: TItem; op: TSym; var L: longint);
113+procedure ForNext(o: PObj; const lim: TItem; step: int64; var exitL: longint; top, body: longint);
114+
115+procedure BeginProc(sig: PType; params: PObj);
116+procedure ReturnValue(var x: TItem);
117+procedure ReturnField(f: PObj; var x: TItem);
118+procedure ReturnAll(var x: TItem);
119+procedure ReturnNone;
120+procedure Pin(var x: TItem);
121+procedure IncDec(var v, k: TItem; dec: boolean);
122+procedure CopyDest(var d: TItem);
123+procedure CopyFrom(var d, s: TItem);
124+procedure Msg(var x: TItem);
125+function ErrorChunk(var x: TItem; module, name: longint): longint;
126+
127+implementation
128+
129+const
130+ { the comparison that holds when op doesn't, for integers }
131+ Negated: array[sEql..sGeq] of TSym = (sNeq, sEql, sGeq, sGtr, sLeq, sLss);
132+
133+var
134+ result: PType; { the result of the procedure being compiled, or nil }
135+
136+{ Items }
137+
138+procedure MakeConst(var x: TItem; t: PType; v: int64);
139+var p: TPos;
140+begin
141+ p := x.pos;
142+ FillChar(x, SizeOf(x), 0);
143+ x.pos := p;
144+ x.mode := mConst;
145+ x.typ := t;
146+ x.val := v;
147+end;
148+
149+{ A real constant: untyped, unless typed later. Its value is an F64,
150+ which for an F32 is one an F32 can hold. }
151+procedure MakeReal(var x: TItem; r: double);
152+begin
153+ MakeConst(x, tRConst, 0);
154+ Move(r, x.val, 8);
155+end;
156+
157+function IsF32(t: PType): boolean;
158+begin
159+ IsF32 := (t^.form = fReal) and (t^.size = 4);
160+end;
161+
162+{ Gives a real constant the real type t, rounded to it. }
163+procedure RealTo(var x: TItem; t: PType);
164+var r: double;
165+begin
166+ r := RealOf(x);
167+ if IsF32(t) then MakeReal(x, single(r)) else MakeReal(x, r);
168+ x.typ := t;
169+end;
170+
171+function RealOf(const x: TItem): double;
172+var r: double;
173+begin
174+ Move(x.val, r, 8);
175+ RealOf := r;
176+end;
177+
178+{ The current string literal, as an item of its own chunk. }
179+procedure MakeStr(var x: TItem);
180+begin
181+ FillChar(x, SizeOf(x), 0);
182+ x.mode := mStr;
183+ x.typ := tStr;
184+ x.val := slen;
185+ x.chunk := NewChunk(secRodata, -1, -1);
186+ SetData(x.chunk, @sbuf, slen + 1, 1);
187+end;
188+
189+function FrameAdr(off: int64): TAdr;
190+begin
191+ FrameAdr.base := bFrame;
192+ FrameAdr.chunk := -1;
193+ FrameAdr.off := off;
194+ FrameAdr.hi := 0;
195+end;
196+
197+function GlobalAdr(c: longint): TAdr;
198+begin
199+ GlobalAdr.base := bGlobal;
200+ GlobalAdr.chunk := c;
201+ GlobalAdr.off := 0;
202+ GlobalAdr.hi := 0;
203+end;
204+
205+{ Where the variable x is, for gen; a slice in registers has two }
206+function AdrOf(const x: TItem): TAdr;
207+begin
208+ AdrOf.base := x.base;
209+ AdrOf.chunk := x.chunk;
210+ AdrOf.off := x.off;
211+ AdrOf.hi := 0;
212+ if x.base = bReg then AdrOf.hi := x.obj^.reg2;
213+end;
214+
215+{ An item for "found ...": a constant without a type of its own as it
216+ is written, so that "found 1.5" says what is wrong; else its type. }
217+function What(const x: TItem): shortstring;
218+begin
219+ if (x.mode = mConst) and ((x.typ = tConst) or (x.typ = tRConst)) then What := Source(x.pos)
220+ else What := TypeName(x.typ);
221+end;
222+
223+{ Two operands of different types. Numbers convert, so say how. }
224+procedure Mismatch(const x, y: TItem; xt, yt: PType);
225+var msg: shortstring;
226+begin
227+ msg := TypeName(xt) + ' and ' + TypeName(yt) + ' are different types';
228+ if (IsInt(xt) or (xt^.form = fReal)) and (IsInt(yt) or (yt^.form = fReal))
229+ and (xt <> tConst) and (xt <> tRConst) then
230+ MarkHelp(Join(x.pos, y.pos), msg, 'convert one to the other''s type, as in ' + TypeName(xt) + '(' + Source(y.pos) + ')')
231+ else MarkAt(Join(x.pos, y.pos), msg);
232+end;
233+
234+{ An item that is not a value, by what it is. }
235+procedure NotValue(const x: TItem);
236+begin
237+ case x.mode of
238+ mType: MarkAt(x.pos, TypeName(x.typ) + ' is a type, not a value');
239+ mBuiltin: MarkAt(x.pos, NameOf(x.obj^.name) + ' is a built-in procedure, not a value');
240+ mCase: MarkAt(x.pos, NameOf(x.obj^.name) + ' is a case, not a value');
241+ mNone:
242+ if x.obj <> nil then MarkAt(x.pos, NameOf(x.obj^.name) + ' returns nothing')
243+ else MarkAt(x.pos, 'the procedure returns nothing');
244+ else MarkAt(x.pos, 'a string can''t be an operand');
245+ end;
246+end;
247+
248+procedure MakeItem(var x: TItem; o: PObj);
249+begin
250+ FillChar(x, SizeOf(x), 0);
251+ x.typ := o^.typ;
252+ x.obj := o;
253+ case o^.cls of
254+ oConst:
255+ if o^.typ = tStr then begin
256+ x.mode := mStr; x.val := o^.val; x.chunk := o^.chunk
257+ end else if o^.typ^.form in [fArray, fRecord] then begin
258+ { an array or record constant: a variable in read-only data, not one of
259+ the program's, so nothing can change it }
260+ x.mode := mVar; x.base := bGlobal; x.chunk := o^.chunk
261+ end else begin
262+ x.mode := mConst; x.val := o^.val
263+ end;
264+ oVar: begin
265+ x.mode := mVar;
266+ x.ro := (o^.lev = 0) and (o^.module <> curModule);
267+ x.isVar := not x.ro;
268+ if o^.ext then begin
269+ PushVar(GlobalAdr(o^.chunk), 8, false, kWord);
270+ x.base := bStack;
271+ end else if o^.lev = 0 then begin
272+ x.base := bGlobal; x.chunk := o^.chunk
273+ end else if o^.ind then begin
274+ x.base := bSlot; x.chunk := o^.val; x.off := o^.off;
275+ end else if o^.reg <> 0 then begin
276+ x.base := bReg; x.chunk := o^.reg
277+ end else begin
278+ x.base := bFrame; x.off := o^.val
279+ end;
280+ end;
281+ oProc: x.mode := mProc;
282+ oType: x.mode := mType;
283+ oBuiltin: x.mode := mBuiltin;
284+ oCase: x.mode := mCase;
285+ else Mark(NameOf(o^.name) + ' is not a value');
286+ end;
287+end;
288+
289+function ScalarSize(t: PType): longint;
290+begin
291+ if t^.form in [fInt, fBool, fEnum, fSet, fReal] then ScalarSize := t^.size
292+ else ScalarSize := 8;
293+end;
294+
295+{ The width an operation on t is brought back to, and whether signed }
296+function IntSize(t: PType): longint;
297+begin
298+ if t^.form = fInt then IntSize := t^.size else IntSize := 8;
299+end;
300+
301+function Signed(t: PType): boolean;
302+begin
303+ Signed := ((t^.form = fInt) and t^.signed) or (t^.form = fConst);
304+end;
305+
306+function Cut(v: int64; t: PType): int64;
307+begin
308+ Cut := v;
309+ if t^.form <> fInt then exit;
310+ case t^.size of
311+ 1: if t^.signed then Cut := shortint(v) else Cut := byte(v);
312+ 2: if t^.signed then Cut := smallint(v) else Cut := word(v);
313+ 4: if t^.signed then Cut := longint(v) else Cut := longword(v);
314+ end;
315+end;
316+
317+{ Code computing with a real is noted on its chunk, at the first place,
318+ for a target without reals (report 5.1) to refuse if the chunk turns
319+ out to be used. A real moved whole, as a record's bytes are copied,
320+ needs nothing the target lacks, and isn't noted. }
321+procedure UsesReals(const p: TPos);
322+begin
323+ if (codeChunk >= 0) and not chunks^[codeChunk].reals then begin
324+ chunks^[codeChunk].reals := true;
325+ chunks^[codeChunk].realsAt := p;
326+ end;
327+end;
328+
329+{ x, at an address from a pointer, is about to be used: gen tests the
330+ address for nil where the machine wouldn't stop at it (report section
331+ 10), from its offset to its end. }
332+procedure NilTest(var x: TItem);
333+begin
334+ if (x.mode = mVar) and x.deref then CheckNil(x.off + x.typ^.size, x.pos);
335+ x.deref := false;
336+end;
337+
338+{ x's value, on top of the stack }
339+procedure Value(var x: TItem);
340+var f: single;
341+begin
342+ if x.mode = mCond then begin
343+ if (x.fj = NoLabel) and (x.tj = NoLabel) then Compare(x.rel, kWord, x.relSigned)
344+ else CondValue(Negated[x.rel], x.relSigned, x.fj, x.tj);
345+ x.mode := mStack;
346+ exit;
347+ end;
348+ if x.typ^.form = fReal then UsesReals(x.pos);
349+ NilTest(x);
350+ case x.mode of
351+ mConst:
352+ if (x.typ^.form = fError) and (x.val > 0) then PushAdr(GlobalAdr(x.val - 1))
353+ else if IsF32(x.typ) then begin
354+ f := RealOf(x);
355+ PushConst(kF32, PLongword(@f)^);
356+ end else PushConst(KindOf(x.typ), x.val);
357+ mVar: begin
358+ if not IsScalar(x.typ) then MarkAt(x.pos, 'expected a single value, found ' + What(x));
359+ PushVar(AdrOf(x), ScalarSize(x.typ), (x.typ^.form = fInt) and x.typ^.signed, KindOf(x.typ));
360+ end;
361+ mStack: ;
362+ mProc: begin
363+ if x.obj^.isCode and (x.obj^.typ^.base <> nil) and x.obj^.typ^.base^.tuple then
364+ MarkAt(x.pos, 'a code procedure with two results can only be called');
365+ PushProc(x.obj^.chunk, x.obj^.ext);
366+ end;
367+ else NotValue(x);
368+ end;
369+ x.mode := mStack;
370+end;
371+
372+{ The address of the variable or string x, on top of the stack }
373+procedure Address(var x: TItem);
374+begin
375+ NilTest(x);
376+ if (x.mode = mVar) and (x.base = bReg) then begin
377+ { its address is wanted after all: the procedure is compiled again
378+ with the variable in memory; till then, this code is thrown away }
379+ x.obj^.reg := 0;
380+ x.obj^.reg2 := 0;
381+ demoted := true;
382+ x.base := bFrame;
383+ x.off := x.obj^.val;
384+ end;
385+ if x.mode = mStr then PushAdr(GlobalAdr(x.chunk))
386+ else if x.mode = mVar then begin
387+ PushAdr(AdrOf(x));
388+ x.base := bStack; x.off := 0;
389+ end else MarkAt(x.pos, 'expected a variable');
390+end;
391+
392+{ x isn't wanted: what it has on the stack is dropped }
393+procedure Discard(const x: TItem);
394+var y: TItem;
395+begin
396+ if x.mode = mCond then begin y := x; Value(y); Drop; exit end;
397+ if (x.mode = mStack) or ((x.mode = mVar) and (x.base = bStack)) then Drop;
398+ if x.mode = mWords then begin Drop; Drop end;
399+end;
400+
401+{ Frames }
402+
403+procedure TempItem(var x: TItem; t: PType; off: int64);
404+var p: TPos;
405+begin
406+ p := x.pos;
407+ FillChar(x, SizeOf(x), 0);
408+ x.pos := p;
409+ x.mode := mVar; x.typ := t; x.base := bFrame; x.off := off;
410+end;
411+
412+function ToSlot(var x: TItem): int64;
413+var s: int64;
414+begin
415+ Value(x);
416+ s := AllocTemp(8, 8);
417+ PopVar(FrameAdr(s), 8);
418+ ToSlot := s;
419+end;
420+
421+{ Copying }
422+
423+{ x, copied to a temporary }
424+procedure CopyToTemp(var x: TItem);
425+var t: int64; f, g: PObj; a: TAdr;
426+begin
427+ if x.vol then MarkAt(x.pos, 'can''t copy through a volatile pointer');
428+ t := AllocTemp(x.typ^.size, x.typ^.align);
429+ if (x.mode = mVar) and (x.base = bReg) then begin
430+ { a slice in registers, which has no address: its words stored }
431+ a := AdrOf(x);
432+ PushVar(a, 8, false, kWord);
433+ PopVar(FrameAdr(t), 8);
434+ a.off := 8;
435+ PushVar(a, 8, false, kWord);
436+ PopVar(FrameAdr(t + 8), 8);
437+ TempItem(x, x.typ, t);
438+ exit;
439+ end;
440+ if x.mode = mWords then begin
441+ { the second result is on top, so it is popped first }
442+ f := x.typ^.fields; g := f^.next;
443+ PopVar(FrameAdr(t + g^.val), ScalarSize(g^.typ));
444+ PopVar(FrameAdr(t + f^.val), ScalarSize(f^.typ));
445+ TempItem(x, x.typ, t);
446+ exit;
447+ end;
448+ Address(x);
449+ CopyTo(FrameAdr(t), x.typ^.size);
450+ TempItem(x, x.typ, t);
451+end;
452+
453+{ A slice made from an address on the stack and a length. }
454+procedure SliceOf(var x: TItem; t: PType; len: int64);
455+var s: int64;
456+begin
457+ s := AllocTemp(16, 8);
458+ PopVar(FrameAdr(s), 8);
459+ PushConst(kWord, len);
460+ PopVar(FrameAdr(s + 8), 8);
461+ TempItem(x, t, s);
462+end;
463+
464+{ An INT goes silently into an I64, and a UINT into a U64, losing
465+ nothing on any target (report section 5.10). }
466+function Widens(s, t: PType): boolean;
467+begin
468+ Widens := ((s = tInt) and Same(t, tI64)) or ((s = tUInt) and Same(t, tU64));
469+end;
470+
471+{ Another module's exported variable can be read, not changed, nor
472+ handed to anything that could change it (report section 3). }
473+procedure NotReadOnly(const x: TItem);
474+begin
475+ if x.ro then MarkAt(x.pos, Source(x.pos) + ' is ' + NameOf(x.obj^.module^.name) + '''s, and can''t be changed outside it');
476+end;
477+
478+var
479+ passing: PObj; { the parameter the argument at passingAt goes to }
480+ passingAt: TPos;
481+
482+{ An error in x's type; if x is an argument, a note at the parameter
483+ it goes to. }
484+procedure Mismatch(const x: TItem; const msg: shortstring);
485+begin
486+ Error(x.pos, msg);
487+ if (passing <> nil) and (x.pos.f = passingAt.f) and (x.pos.a = passingAt.a) and (x.pos.b = passingAt.b) then
488+ Note(passing^.pos, 'it goes to ' + NameOf(passing^.name) + ', declared here');
489+ Fail;
490+end;
491+
492+procedure Coerce(var x: TItem; t: PType);
493+var s: PType; tmp: int64;
494+begin
495+ if x.mode = mCond then Value(x);
496+ s := x.typ;
497+ if x.mode = mStr then begin
498+ if (t^.form = fSlice) and (t^.base = tU8) then begin
499+ Address(x); SliceOf(x, t, x.val)
500+ end else if (t^.form = fPtr) and (t^.base = tU8) then begin
501+ Address(x); x.mode := mStack; x.typ := t
502+ end else if (t^.form = fArray) and (t^.base = tU8) and (t^.len >= x.val) then begin
503+ tmp := AllocTemp(t^.size, 1);
504+ Address(x);
505+ CopyTo(FrameAdr(tmp), x.val);
506+ if t^.len > x.val then ZeroVar(FrameAdr(tmp + x.val), t^.len - x.val);
507+ TempItem(x, t, tmp);
508+ end else Mismatch(x, 'can''t use a string as ' + TypeName(t));
509+ exit;
510+ end;
511+ if x.mode in [mType, mBuiltin, mNone, mCase] then NotValue(x);
512+ if Same(s, t) then exit;
513+ if Widens(s, t) then x.typ := t { the same bits, on a 64-bit target }
514+ else if (s = tRConst) and (t^.form = fReal) then RealTo(x, t)
515+ else if (s^.form = fConst) and (t^.form = fInt) then begin
516+ if (x.mode = mConst) and not Fits(x.val, t) then MarkAt(x.pos, IntStr(x.val) + ' doesn''t fit ' + TypeName(t));
517+ x.typ := t;
518+ end else if (s^.form = fNil) and (t^.form in [fPtr, fProc, fError]) then
519+ x.typ := t
520+ else if (s^.form = fPtr) and (t^.form = fPtr) and t^.vol and not s^.vol
521+ and Same(s^.base, t^.base) then
522+ x.typ := t
523+ else if (s^.form = fArray) and (t^.form = fSlice) and Same(s^.base, t^.base) then begin
524+ NotReadOnly(x);
525+ if x.vol then MarkAt(x.pos, 'can''t make a slice through a volatile pointer');
526+ if x.odd then MarkAt(x.pos, 'can''t make a slice of a field of a packed record');
527+ Address(x);
528+ SliceOf(x, t, s^.len);
529+ end else if (x.mode = mProc) and (t^.form <> fProc) and (s^.base = nil) then
530+ MarkAt(x.pos, Source(x.pos) + ' is a procedure, and returns nothing')
531+ else if (x.mode = mProc) and (t^.form <> fProc) then
532+ MarkHelp(x.pos, 'can''t use ' + TypeName(s) + ' as ' + TypeName(t), 'to call it, write ' + Source(x.pos) + '()')
533+ else
534+ Mismatch(x, 'can''t use ' + TypeName(s) + ' as ' + TypeName(t));
535+end;
536+
537+{ Coerce where the types must be the same, as in a for loop, INC and
538+ several results, which don't widen an INT to an I64 (report sections
539+ 5.10, 6.1 and 7.2); help, if not empty, says why. }
540+procedure CoerceExact(var x: TItem; t: PType; const help: shortstring);
541+var h: shortstring;
542+begin
543+ if Widens(x.typ, t) then begin
544+ h := help;
545+ if h = '' then h := 'they don''t mix here: write ' + TypeName(t) + '(' + Source(x.pos) + ')';
546+ MarkHelp(x.pos, 'expected ' + TypeName(t) + ', found ' + What(x), h);
547+ end;
548+ Coerce(x, t);
549+end;
550+
551+{ dst := src. The address of dst, if it has to be computed, is on the
552+ stack already, under src's. }
553+procedure Assign(var dst, src: TItem);
554+begin
555+ Coerce(src, dst.typ);
556+ if IsScalar(dst.typ) then begin
557+ Value(src);
558+ PopVar(AdrOf(dst), ScalarSize(dst.typ));
559+ end else begin
560+ if dst.vol or src.vol then MarkAt(src.pos, 'can''t copy through a volatile pointer');
561+ if (src.mode = mVar) and (src.base = bReg) then CopyToTemp(src); { a slice in registers }
562+ Address(src);
563+ if dst.base = bStack then CopyBlock(dst.typ^.size, dst.off)
564+ else CopyTo(AdrOf(dst), dst.typ^.size);
565+ end;
566+end;
567+
568+{ t's name, ending in a zero byte, for Rt.fail }
569+function NameChunk(t: PType): longint;
570+var s: shortstring; c: longint;
571+begin
572+ s := TypeName(t) + #0;
573+ c := NewChunk(secRodata, -1, -1);
574+ SetData(c, @s[1], length(s), 1);
575+ NameChunk := c;
576+end;
577+
578+{ Selectors }
579+
580+procedure Deref(var x: TItem);
581+var t: PType;
582+begin
583+ t := x.typ;
584+ if t^.form <> fPtr then MarkAt(x.pos, 'expected a pointer, found ' + TypeName(t));
585+ if t^.base = nil then MarkAt(x.pos, TypeName(t) + ' points to a type never declared');
586+ Value(x);
587+ x.mode := mVar; x.base := bStack; x.off := 0; x.deref := true;
588+ x.typ := t^.base; x.vol := t^.vol; x.isVar := true; x.odd := false; x.ro := false;
589+end;
590+
591+{ A field of a packed record, of more than one byte's alignment, may
592+ sit anywhere; it is read and written, but has no address and no
593+ volatile access, which a machine that can't reach a misaligned word
594+ couldn't make one access (report section 5.5). }
595+procedure Field(var x: TItem; f: PObj);
596+begin
597+ if x.typ^.packd and (f^.typ^.align > 1) then begin
598+ if x.vol then MarkAt(x.pos, 'a field of a packed record can''t be volatile');
599+ x.odd := true;
600+ end;
601+ x.off := x.off + f^.val;
602+ x.typ := f^.typ;
603+end;
604+
605+procedure IndexPrep(var x: TItem);
606+begin
607+ NilTest(x);
608+ if x.mode = mStr then Coerce(x, tBytes);
609+ if (x.typ^.form = fPtr) and (x.typ^.base^.form = fArray) then
610+ MarkAt(x.pos, 'a pointer to an array is indexed as p^[i]');
611+ if x.typ^.form = fPtr then Value(x)
612+ else if not ((x.mode = mVar) and (x.typ^.form in [fArray, fSlice])) then
613+ MarkAt(x.pos, 'expected an array, a slice or a pointer, found ' + What(x));
614+end;
615+
616+{ The index on top, times the size of an element }
617+procedure ScaleBy(s: int64);
618+begin
619+ if s <> 1 then begin
620+ PushConst(kWord, s);
621+ gen.Op(sTimes, kWord, 8, true);
622+ end;
623+end;
624+
625+procedure Index(var x, y: TItem);
626+var t: PType; s: int64;
627+begin
628+ t := x.typ;
629+ s := t^.base^.size;
630+ if not IsInt(y.typ) then MarkAt(y.pos, 'an index is an integer, found ' + What(y));
631+ if t^.form = fPtr then begin
632+ Value(y);
633+ ScaleBy(s);
634+ gen.Op(sPlus, kWord, 8, false);
635+ x.mode := mVar; x.base := bStack; x.off := 0;
636+ x.vol := t^.vol; x.isVar := true; x.odd := false; x.ro := false;
637+ end else if (t^.form = fArray) and (y.mode = mConst) then begin
638+ if (y.val < 0) or (y.val >= t^.len) then MarkAt(y.pos, 'index ' + IntStr(y.val) + ' is out of range for a length of ' + IntStr(t^.len));
639+ x.off := x.off + y.val * s;
640+ end else if t^.form = fArray then begin
641+ Value(y);
642+ if checks then CheckIndex(t^.len, y.pos);
643+ if x.base = bStack then begin ScaleBy(s); gen.Op(sPlus, kWord, 8, false) end
644+ else begin IndexArray(AdrOf(x), s); x.off := 0 end;
645+ x.base := bStack;
646+ end else begin
647+ Value(y);
648+ IndexSlice(AdrOf(x), s, checks, y.pos);
649+ x.base := bStack; x.off := 0; x.isVar := true; x.vol := false; x.ro := false;
650+ end;
651+ x.typ := t^.base;
652+end;
653+
654+procedure SliceLo(var lo: TItem);
655+begin
656+ if not IsInt(lo.typ) then MarkAt(lo.pos, 'an index is an integer, found ' + What(lo));
657+ Value(lo);
658+end;
659+
660+procedure Slice(var x, lo, hi: TItem);
661+var t, st: PType; tmp: int64;
662+begin
663+ t := x.typ;
664+ if not IsInt(hi.typ) then MarkAt(hi.pos, 'an index is an integer, found ' + What(hi));
665+ if x.vol then MarkAt(x.pos, 'can''t make a slice through a volatile pointer');
666+ if x.odd then MarkAt(x.pos, 'can''t make a slice of a field of a packed record');
667+ if t^.form = fArray then NotReadOnly(x);
668+ Value(hi);
669+ tmp := AllocTemp(16, 8);
670+ if t^.form = fPtr then SlicePtr(t^.base^.size, tmp, checks, lo.pos)
671+ else gen.Slice(AdrOf(x), t^.form = fArray, t^.len, t^.base^.size, tmp, checks, lo.pos);
672+ st := NewType(fSlice, 16, 8);
673+ st^.base := t^.base;
674+ TempItem(x, st, tmp);
675+end;
676+
677+{ Operators }
678+
679+procedure Neg(var x: TItem);
680+begin
681+ if x.typ^.form = fReal then begin
682+ if x.mode = mConst then x.val := x.val xor low(int64)
683+ else begin Value(x); gen.Neg(KindOf(x.typ), 8, false) end;
684+ end else if IsInt(x.typ) then begin
685+ if (x.mode = mConst) and (x.typ^.form = fConst) and (x.val = low(int64)) then
686+ MarkAt(x.pos, 'the constant is too big for I64')
687+ else if x.mode = mConst then x.val := Cut(-x.val, x.typ)
688+ else begin Value(x); gen.Neg(kWord, IntSize(x.typ), Signed(x.typ)) end;
689+ end else MarkAt(x.pos, 'can''t negate ' + TypeName(x.typ));
690+end;
691+
692+procedure NotOp(var x: TItem);
693+var L: longint;
694+begin
695+ if IsInt(x.typ) then MarkHelp(x.pos, '"not" needs a BOOL, found ' + What(x), 'the bits of an integer flip with ~');
696+ if x.typ^.form <> fBool then MarkAt(x.pos, '"not" needs a BOOL, found ' + What(x));
697+ if x.mode = mConst then x.val := 1 - x.val
698+ else if x.mode = mCond then begin
699+ x.rel := Negated[x.rel];
700+ L := x.fj; x.fj := x.tj; x.tj := L;
701+ end
702+ else begin Value(x); NotBool end;
703+end;
704+
705+procedure Complement(var x: TItem);
706+begin
707+ if x.typ^.form = fBool then MarkHelp(x.pos, '"~" needs an integer, found ' + What(x), 'a BOOL is negated with not');
708+ if not IsInt(x.typ) then MarkAt(x.pos, '"~" needs an integer, found ' + What(x));
709+ if x.mode = mConst then x.val := Cut(not x.val, x.typ)
710+ else begin Value(x); gen.Complement(IntSize(x.typ), Signed(x.typ)) end;
711+end;
712+
713+{ Arrays, slices and strings, which = and # compare element by element }
714+function IsSeq(t: PType): boolean;
715+begin
716+ IsSeq := t^.form in [fStr, fArray, fSlice];
717+end;
718+
719+function ElemOf(t: PType): PType;
720+begin
721+ if t^.form = fStr then ElemOf := tU8 else ElemOf := t^.base;
722+end;
723+
724+{ An array, slice or string as a slice in a temporary, for comparing. }
725+procedure SeqSlice(var x: TItem);
726+var t: PType;
727+begin
728+ t := NewType(fSlice, 16, 8);
729+ t^.base := ElemOf(x.typ);
730+ if x.typ^.form = fSlice then begin
731+ x.typ := t; CopyToTemp(x)
732+ end else begin
733+ if x.mode = mStr then begin Address(x); SliceOf(x, t, x.val) end
734+ else begin
735+ if x.vol then MarkAt(x.pos, 'can''t compare through a volatile pointer');
736+ Address(x); SliceOf(x, t, x.typ^.len)
737+ end;
738+ end;
739+end;
740+
741+{ x, a BOOL, as a condition: a value compared with 0 if it isn't one }
742+procedure MakeCond(var x: TItem);
743+begin
744+ if x.mode = mCond then exit;
745+ Value(x);
746+ PushConst(kWord, 0);
747+ x.mode := mCond;
748+ x.rel := sNeq;
749+ x.relSigned := false;
750+ x.fj := NoLabel;
751+ x.tj := NoLabel;
752+end;
753+
754+procedure Op1(op: TSym; var x: TItem; var L: longint);
755+begin
756+ L := NoLabel;
757+ if (op in [sAnd, sOr]) and (x.typ^.form = fBool) then begin
758+ if x.mode = mConst then exit; { folded by Op2 }
759+ MakeCond(x);
760+ if op = sAnd then begin
761+ JumpOut(Negated[x.rel], x.relSigned, x.fj);
762+ Fix(x.tj);
763+ x.tj := NoLabel;
764+ end else begin
765+ JumpOut(x.rel, x.relSigned, x.tj);
766+ Fix(x.fj);
767+ x.fj := NoLabel;
768+ end;
769+ end else if (op in [sEql, sNeq]) and IsSeq(x.typ) then
770+ SeqSlice(x)
771+ else if (op = sPlus) and (x.mode = mStr) then
772+ { two string constants to be joined: nothing to compute }
773+ else if (op = sPlus) and IsSeq(x.typ) then
774+ MarkHelp(x.pos, '+ doesn''t join ' + What(x), 'strings are joined in a Buf: Buf.str(b, s)')
775+ else if x.mode in [mType, mBuiltin, mNone, mCase, mStr] then
776+ NotValue(x)
777+ else if x.mode <> mConst then
778+ Value(x);
779+end;
780+
781+function Log2(v: int64): longint;
782+var n: longint;
783+begin
784+ n := 0;
785+ while (v > 1) and (v and 1 = 0) do begin v := v shr 1; inc(n) end;
786+ if v <> 1 then n := -1;
787+ Log2 := n;
788+end;
789+
790+{ Whether a op b, for + - *, overflows an I64: an untyped constant
791+ doesn't wrap, it is an error (report section 4). }
792+function Overflows(op: TSym; a, b: int64): boolean;
793+begin
794+ case op of
795+ sPlus: Overflows := ((b > 0) and (a > high(int64) - b)) or ((b < 0) and (a < low(int64) - b));
796+ sMinus: Overflows := ((b < 0) and (a > high(int64) + b)) or ((b > 0) and (a < low(int64) + b));
797+ sTimes:
798+ if (a = 0) or (b = 0) then Overflows := false
799+ else if a = -1 then Overflows := b = low(int64)
800+ else if b = -1 then Overflows := a = low(int64)
801+ else Overflows := (a * b) div b <> a;
802+ else Overflows := false;
803+ end;
804+end;
805+
806+{ A type's width in bits; an untyped constant's is an I64's }
807+function Bits(t: PType): longint;
808+begin
809+ Bits := t^.size * 8;
810+end;
811+
812+function FoldInt(op: TSym; a, b: int64; t: PType; const p: TPos): int64;
813+var u: boolean;
814+begin
815+ u := (t^.form = fInt) and not t^.signed;
816+ if (t^.form = fConst) and Overflows(op, a, b) then MarkAt(p, 'the constant is too big for I64');
817+ case op of
818+ sPlus: FoldInt := a + b;
819+ sMinus: FoldInt := a - b;
820+ sTimes: FoldInt := a * b;
821+ sDiv, sMod: begin
822+ if b = 0 then MarkAt(p, 'division by zero');
823+ if u then begin
824+ if op = sDiv then FoldInt := int64(qword(a) div qword(b))
825+ else FoldInt := int64(qword(a) mod qword(b));
826+ end else if (b = -1) and (a = int64(-1) shl (Bits(t) - 1)) then MarkAt(p, 'division overflows')
827+ else if op = sDiv then FoldInt := a div b
828+ else FoldInt := a mod b;
829+ end;
830+ sAmp: FoldInt := a and b;
831+ sBar: FoldInt := a or b;
832+ sXor: FoldInt := a xor b;
833+ sShl: FoldInt := a shl (b and (Bits(t) - 1));
834+ sShr: if u then FoldInt := int64(qword(a) shr (b and (Bits(t) - 1)))
835+ else FoldInt := SarInt64(a, b and (Bits(t) - 1));
836+ sEql: FoldInt := ord(a = b);
837+ sNeq: FoldInt := ord(a <> b);
838+ sLss: if u then FoldInt := ord(qword(a) < qword(b)) else FoldInt := ord(a < b);
839+ sLeq: if u then FoldInt := ord(qword(a) <= qword(b)) else FoldInt := ord(a <= b);
840+ sGtr: if u then FoldInt := ord(qword(a) > qword(b)) else FoldInt := ord(a > b);
841+ sGeq: if u then FoldInt := ord(qword(a) >= qword(b)) else FoldInt := ord(a >= b);
842+ else MarkAt(p, 'bad operator'); FoldInt := 0;
843+ end;
844+end;
845+
846+{ Folds x op y, of the real type t: an F32 rounded at each step, as
847+ the machine would. }
848+function FoldReal(op: TSym; const x, y: TItem; t: PType; var r: TItem): boolean;
849+var a, b: double;
850+begin
851+ a := RealOf(x); b := RealOf(y);
852+ FoldReal := true;
853+ case op of
854+ sPlus: MakeReal(r, a + b);
855+ sMinus: MakeReal(r, a - b);
856+ sTimes: MakeReal(r, a * b);
857+ sSlash: MakeReal(r, a / b);
858+ sEql: MakeConst(r, tBool, ord(a = b));
859+ sNeq: MakeConst(r, tBool, ord(a <> b));
860+ sLss: MakeConst(r, tBool, ord(a < b));
861+ sLeq: MakeConst(r, tBool, ord(a <= b));
862+ sGtr: MakeConst(r, tBool, ord(a > b));
863+ sGeq: MakeConst(r, tBool, ord(a >= b));
864+ else FoldReal := false;
865+ end;
866+ if r.typ^.form = fReal then RealTo(r, t);
867+end;
868+
869+{ and, or and not are for BOOLs; &, |, xor and ~ for the bits of
870+ integers: x is the wrong kind for op, and the message names the
871+ operator it may have meant }
872+procedure WrongLogic(op: TSym; var x: TItem);
873+const Bits = 'the bits of integers take ';
874+begin
875+ case op of
876+ sAnd: if IsInt(x.typ) then MarkHelp(x.pos, '"and" needs BOOLs, found ' + What(x), Bits + '&');
877+ sOr: if IsInt(x.typ) then MarkHelp(x.pos, '"or" needs BOOLs, found ' + What(x), Bits + '|');
878+ sAmp: MarkHelp(x.pos, '"&" needs integers, found ' + What(x), 'BOOLs take and');
879+ sBar: MarkHelp(x.pos, '"|" needs integers, found ' + What(x), 'BOOLs take or');
880+ sXor: MarkHelp(x.pos, '"xor" needs integers, found ' + What(x), 'BOOLs that differ are #');
881+ end;
882+ MarkAt(x.pos, SymText(op) + ' needs BOOLs, found ' + What(x));
883+end;
884+
885+{ x + y, of two string constants: one string, in a chunk of its own
886+ (report section 4) }
887+procedure JoinStr(var x, y: TItem);
888+var p: PBytes; c: longint;
889+begin
890+ if y.mode <> mStr then MarkAt(y.pos, '"+" joins two strings, found ' + What(y));
891+ p := GetMem(x.val + y.val + 1);
892+ Move(rodata^[chunks^[x.chunk].start], p^[0], x.val);
893+ Move(rodata^[chunks^[y.chunk].start], p^[x.val], y.val + 1);
894+ c := NewChunk(secRodata, -1, -1);
895+ SetData(c, p, x.val + y.val + 1, 1);
896+ FreeMem(p);
897+ x.chunk := c;
898+ x.val := x.val + y.val;
899+end;
900+
901+{ A set's operations, as operations on its bits: the two values on top }
902+procedure SetOp(op: TSym);
903+begin
904+ case op of
905+ sPlus: gen.Op(sBar, kWord, 8, false);
906+ sTimes: gen.Op(sAmp, kWord, 8, false);
907+ sMinus: begin gen.Complement(8, false); gen.Op(sAmp, kWord, 8, false) end;
908+ sLeq, sGeq: begin
909+ { x <= y has no bit of x outside y }
910+ if op = sGeq then Swap;
911+ gen.Complement(8, false);
912+ gen.Op(sAmp, kWord, 8, false);
913+ PushConst(kWord, 0);
914+ Compare(sEql, kWord, false);
915+ end;
916+ sIn: begin
917+ Swap;
918+ gen.Op(sShr, kWord, 8, false);
919+ PushConst(kWord, 1);
920+ gen.Op(sAmp, kWord, 8, false);
921+ end;
922+ else Compare(op, kWord, false);
923+ end;
924+end;
925+
926+procedure Op2(op: TSym; var x, y: TItem; L: longint);
927+const
928+ Rel = [sEql, sNeq, sLss, sLeq, sGtr, sGeq];
929+var
930+ xt, yt, t, e: PType; r: TItem; scale: longint; isPtr: boolean; a, b: int64;
931+begin
932+ xt := x.typ; yt := y.typ;
933+ if y.mode in [mType, mBuiltin, mNone, mCase] then NotValue(y);
934+ if (op = sPlus) and (x.mode = mStr) then begin JoinStr(x, y); exit end;
935+
936+ if op in [sAnd, sOr] then begin
937+ if xt^.form <> fBool then WrongLogic(op, x);
938+ if yt^.form <> fBool then WrongLogic(op, y);
939+ if (x.mode = mConst) and (y.mode = mConst) then begin
940+ if op = sAnd then x.val := x.val and y.val else x.val := x.val or y.val;
941+ end else if x.mode = mConst then begin
942+ { true and y, false or y: y; else x, y computed and dropped }
943+ if (x.val = 1) = (op = sAnd) then x := y
944+ else Discard(y);
945+ end else begin
946+ MakeCond(y);
947+ if op = sAnd then begin x.fj := JoinJumps(x.fj, y.fj); x.tj := y.tj end
948+ else begin x.tj := JoinJumps(x.tj, y.tj); x.fj := y.fj end;
949+ x.rel := y.rel;
950+ x.relSigned := y.relSigned;
951+ end;
952+ exit;
953+ end;
954+
955+ if (op in [sAmp, sBar, sXor]) and (xt^.form = fBool) then WrongLogic(op, x);
956+ if (op in [sAmp, sBar, sXor]) and (yt^.form = fBool) then WrongLogic(op, y);
957+
958+ { the lengths, then the bytes, LEN * SIZE(T) of them: the elements
959+ are of types whose bytes say all there is to their values }
960+ if (op in [sEql, sNeq]) and IsSeq(xt) then begin
961+ e := ElemOf(xt);
962+ if not IsSeq(yt) then
963+ MarkAt(Join(x.pos, y.pos), 'can''t compare an array with ' + TypeName(yt))
964+ else if not Same(e, ElemOf(yt)) then
965+ MarkAt(Join(x.pos, y.pos), 'can''t compare an array of ' + TypeName(e) + ' with one of ' + TypeName(ElemOf(yt)));
966+ if e^.form = fReal then
967+ MarkHelp(Join(x.pos, y.pos), 'can''t compare arrays of reals with ' + SymText(op),
968+ '-0.0 = 0.0 and a NaN equals nothing, though their bytes say otherwise: write a loop')
969+ else if not (e^.form in [fInt, fBool, fEnum, fSet, fPtr]) then
970+ MarkHelp(Join(x.pos, y.pos), 'can''t compare arrays of ' + TypeName(e) + ' with ' + SymText(op), 'write a loop');
971+ SeqSlice(y);
972+ CompareSeq(x.off, y.off, Log2(e^.size), op = sEql);
973+ MakeConst(x, tBool, 0);
974+ x.mode := mStack;
975+ exit;
976+ end;
977+
978+ { the type of the result, and the checks }
979+ t := nil; scale := 1; isPtr := false;
980+ if IsInt(xt) and IsInt(yt) then begin
981+ if op = sSlash then MarkHelp(Join(x.pos, y.pos), '"/" divides reals, not integers', 'to divide integers, write ' + Source(x.pos) + ' div ' + Source(y.pos));
982+ if op in [sShl, sShr] then begin
983+ if xt^.form = fConst then t := tConst else t := xt
984+ end else if (xt^.form = fConst) and (yt^.form = fConst) then t := tConst
985+ else if xt^.form = fConst then begin
986+ if (x.mode = mConst) and not Fits(x.val, yt) then MarkAt(x.pos, IntStr(x.val) + ' doesn''t fit ' + TypeName(yt));
987+ t := yt
988+ end else if yt^.form = fConst then begin
989+ if (y.mode = mConst) and not Fits(y.val, xt) then MarkAt(y.pos, IntStr(y.val) + ' doesn''t fit ' + TypeName(xt));
990+ t := xt
991+ end else if Same(xt, yt) then t := xt
992+ else Mismatch(x, y, xt, yt);
993+ if not (op in Rel + [sPlus, sMinus, sTimes, sDiv, sMod, sAmp, sBar, sXor, sShl, sShr]) then
994+ MarkAt(Join(x.pos, y.pos), SymText(op) + ' doesn''t apply to ' + TypeName(t));
995+ end else if (xt^.form = fReal) and (yt^.form = fReal) then begin
996+ if not (op in Rel + [sPlus, sMinus, sTimes, sSlash]) then MarkAt(Join(x.pos, y.pos), SymText(op) + ' doesn''t apply to ' + TypeName(xt));
997+ if xt = tRConst then t := yt
998+ else if (yt = tRConst) or Same(xt, yt) then t := xt
999+ else Mismatch(x, y, xt, yt);
1000+ if (x.mode = mConst) and (x.typ <> t) then RealTo(x, t);
1001+ if (y.mode = mConst) and (y.typ <> t) then RealTo(y, t);
1002+ end else if (xt^.form = fBool) and (yt^.form = fBool) then begin
1003+ if not (op in [sEql, sNeq]) then MarkAt(Join(x.pos, y.pos), SymText(op) + ' doesn''t apply to ' + TypeName(xt));
1004+ t := tBool;
1005+ end else if (xt^.form = fPtr) and IsInt(yt) and (op in [sPlus, sMinus]) then begin
1006+ t := xt; scale := xt^.base^.size; isPtr := true;
1007+ if y.mode = mConst then y.typ := tInt;
1008+ end else if (xt^.form = fPtr) and (yt^.form = fPtr) and (op = sMinus) then begin
1009+ if not Same(xt, yt) then Mismatch(x, y, xt, yt);
1010+ t := tInt; scale := xt^.base^.size; isPtr := true;
1011+ end else if (xt^.form in [fPtr, fProc, fNil, fError]) and (yt^.form in [fPtr, fProc, fNil, fError]) then begin
1012+ if not (op in Rel) then MarkAt(Join(x.pos, y.pos), SymText(op) + ' doesn''t apply to ' + TypeName(xt));
1013+ if (xt^.form in [fProc, fError]) or (yt^.form in [fProc, fError]) then
1014+ if not (op in [sEql, sNeq]) then MarkAt(Join(x.pos, y.pos), SymText(op) + ' doesn''t apply to ' + TypeName(xt));
1015+ if (xt^.form <> fNil) and (yt^.form <> fNil) and not Same(xt, yt) then
1016+ if not ((xt^.form = fPtr) and (yt^.form = fPtr) and Same(xt^.base, yt^.base)) then
1017+ Mismatch(x, y, xt, yt);
1018+ t := tU64;
1019+ end else if (xt^.form = fEnum) and Same(xt, yt) then begin
1020+ if not (op in Rel) then MarkAt(Join(x.pos, y.pos), SymText(op) + ' doesn''t apply to ' + TypeName(xt));
1021+ t := xt;
1022+ end else if (xt^.form = fSet) and Same(xt, yt) then begin
1023+ if not (op in [sPlus, sTimes, sMinus, sEql, sNeq, sLeq, sGeq]) then MarkAt(Join(x.pos, y.pos), SymText(op) + ' doesn''t apply to ' + TypeName(xt));
1024+ t := xt;
1025+ end else if (op = sIn) and (yt^.form = fSet) and Same(xt, yt^.base) then
1026+ t := yt
1027+ else
1028+ Mismatch(x, y, xt, yt);
1029+
1030+ { constants }
1031+ if (x.mode = mConst) and (y.mode = mConst) and not isPtr then begin
1032+ if t^.form = fReal then begin
1033+ if not FoldReal(op, x, y, t, r) then MarkAt(Join(x.pos, y.pos), SymText(op) + ' doesn''t apply to ' + TypeName(xt));
1034+ x := r;
1035+ end else if t^.form = fSet then begin
1036+ a := x.val; b := y.val;
1037+ case op of
1038+ sPlus: MakeConst(x, t, a or b);
1039+ sTimes: MakeConst(x, t, a and b);
1040+ sMinus: MakeConst(x, t, a and not b);
1041+ sIn: MakeConst(x, tBool, (b shr a) and 1);
1042+ sLeq: MakeConst(x, tBool, ord(a and not b = 0));
1043+ sGeq: MakeConst(x, tBool, ord(b and not a = 0));
1044+ else MakeConst(x, tBool, ord((a = b) = (op = sEql)));
1045+ end;
1046+ end else if op in Rel then
1047+ MakeConst(x, tBool, FoldInt(op, x.val, y.val, t, Join(x.pos, y.pos)))
1048+ else
1049+ MakeConst(x, t, Cut(FoldInt(op, x.val, y.val, t, Join(x.pos, y.pos)), t));
1050+ exit;
1051+ end;
1052+
1053+ { x and y on the stack, x under y; a constant x goes on after y, and
1054+ is left on top where the order doesn't matter, as gen takes a
1055+ constant best on the right: 0.25 * e is mulsd xmm8, [0.25] }
1056+ Value(y);
1057+ if x.mode = mConst then begin
1058+ Value(x);
1059+ if not (op in [sPlus, sTimes, sAmp, sBar, sXor]) or isPtr then Swap;
1060+ end;
1061+
1062+ if t^.form = fReal then begin
1063+ if op in Rel then Compare(op, KindOf(t), false) else gen.Op(op, KindOf(t), 8, false)
1064+ end else if t^.form = fSet then
1065+ SetOp(op)
1066+ else if op in Rel then begin
1067+ x.mode := mCond;
1068+ x.rel := op;
1069+ x.relSigned := Signed(t);
1070+ x.fj := NoLabel;
1071+ x.tj := NoLabel;
1072+ x.typ := tBool;
1073+ exit;
1074+ end
1075+ else if isPtr then begin
1076+ if t <> tInt then ScaleBy(scale);
1077+ gen.Op(op, kWord, 8, false);
1078+ if (t = tInt) and (scale <> 1) then begin
1079+ PushConst(kWord, scale);
1080+ gen.Op(sDiv, kWord, 8, true);
1081+ end;
1082+ end else
1083+ gen.Op(op, KindOf(t), IntSize(t), Signed(t));
1084+ x.mode := mStack;
1085+ if op in Rel + [sIn] then x.typ := tBool else x.typ := t;
1086+end;
1087+
1088+{ INT and UINT, the integers as big as an address, through which
1089+ integers and pointers convert (report section 6.7) }
1090+function IsWord(t: PType): boolean;
1091+begin
1092+ IsWord := Same(t, tInt) or Same(t, tUInt);
1093+end;
1094+
1095+procedure Convert(var x: TItem; t: PType);
1096+var s: PType; r: double;
1097+begin
1098+ s := x.typ;
1099+ if x.mode in [mType, mBuiltin, mNone, mCase, mStr] then begin
1100+ if x.mode = mStr then MarkAt(x.pos, 'can''t convert a string');
1101+ NotValue(x);
1102+ end;
1103+ if Same(s, t) then exit;
1104+ if (IsInt(s) or (s^.form in [fEnum, fSet])) and (t^.form = fInt) then begin
1105+ if x.mode = mConst then x.val := Cut(x.val, t)
1106+ else begin Value(x); Narrow(t^.size, t^.signed) end;
1107+ end else if IsInt(s) and (t^.form = fEnum) then begin
1108+ if x.mode = mConst then begin
1109+ if (x.val < 0) or (x.val >= t^.len) then MarkAt(x.pos, IntStr(x.val) + ' isn''t a position of ' + TypeName(t))
1110+ end else begin Value(x); CheckEnum(t^.len, NameChunk(t), x.pos) end;
1111+ end else if IsInt(s) and (t^.form = fSet) then begin
1112+ if x.mode = mConst then begin
1113+ if t^.len < 64 then x.val := x.val and ((int64(1) shl t^.len) - 1)
1114+ end else begin
1115+ Value(x);
1116+ if t^.len < 64 then begin
1117+ PushConst(kWord, (int64(1) shl t^.len) - 1);
1118+ gen.Op(sAmp, kWord, 8, false);
1119+ end;
1120+ end;
1121+ end else if IsInt(s) and (t^.form = fReal) then begin
1122+ if x.mode = mConst then begin
1123+ if (s^.form = fInt) and not s^.signed then r := qword(x.val) else r := x.val;
1124+ MakeReal(x, r);
1125+ RealTo(x, t);
1126+ end else begin
1127+ Value(x);
1128+ IntToReal(KindOf(t), (s^.form = fInt) and not s^.signed and (s^.size = 8));
1129+ end;
1130+ end else if (s^.form = fReal) and (t^.form = fReal) then begin
1131+ { F32 to F64, F64 to F32, or a real constant to either }
1132+ if x.mode = mConst then RealTo(x, t)
1133+ else begin Value(x); RealToReal(KindOf(s)) end;
1134+ end else if (s^.form = fReal) and (t^.form = fInt) then begin
1135+ if x.mode = mConst then begin
1136+ r := RealOf(x);
1137+ { NaN or out of range folds to low(int64), the "integer
1138+ indefinite" cvttsd2si gives at run time }
1139+ if (r <> r) or (r >= 9.2233720368547758e18) or (r < -9.2233720368547758e18) then
1140+ x.val := Cut(low(int64), t)
1141+ else x.val := Cut(trunc(r), t);
1142+ end else begin
1143+ Value(x); RealToInt(KindOf(s)); Narrow(t^.size, t^.signed)
1144+ end;
1145+ end else if (IsWord(s) or (s^.form in [fConst, fPtr, fProc, fNil])) and (t^.form in [fPtr, fProc]) then begin
1146+ if x.mode <> mConst then Value(x);
1147+ end else if (s^.form in [fPtr, fProc]) and IsWord(t) then
1148+ Value(x)
1149+ else
1150+ MarkAt(x.pos, 'can''t convert ' + TypeName(s) + ' to ' + TypeName(t));
1151+ x.typ := t;
1152+end;
1153+
1154+{ Calls }
1155+
1156+procedure BeginCall(var c: TCall; var x: TItem);
1157+begin
1158+ if x.mode = mProc then begin
1159+ c.sig := x.obj^.typ; c.chunk := x.obj^.chunk; c.target := 0;
1160+ c.obj := x.obj; c.ext := x.obj^.ext;
1161+ end else begin
1162+ c.obj := nil; c.ext := false;
1163+ if x.typ^.form <> fProc then MarkAt(x.pos, 'expected a procedure, found ' + What(x));
1164+ c.sig := x.typ; c.chunk := -1;
1165+ c.target := ToSlot(x);
1166+ end;
1167+ c.param := c.sig^.fields;
1168+ c.n := 0;
1169+end;
1170+
1171+{ Too many arguments or too few, at p }
1172+procedure WrongCount(var c: TCall; const p: TPos; const what: shortstring);
1173+begin
1174+ if c.obj = nil then MarkAt(p, what);
1175+ Error(p, what + ': ' + NameOf(c.obj^.name) + ' takes ' + IntStr(c.sig^.len));
1176+ if c.obj^.module <> nil then Note(c.obj^.pos, 'the signature is here');
1177+ Fail;
1178+end;
1179+
1180+{ Pushes the two words of x, a slice or two results (InTwoRegs), read
1181+ from memory now, so that what comes after can't change them. }
1182+procedure PushWords(var x: TItem);
1183+var adr: TAdr; f: PObj;
1184+begin
1185+ if x.mode = mWords then exit; { there already }
1186+ { copied to a temporary unless its two words are in memory at a place
1187+ that a later argument can't change }
1188+ if (x.mode <> mVar) or x.vol or not (x.base in [bFrame, bGlobal, bSlot, bReg]) then CopyToTemp(x);
1189+ adr := AdrOf(x);
1190+ if x.typ^.form = fSlice then begin
1191+ PushVar(adr, 8, false, kWord);
1192+ inc(adr.off, 8);
1193+ PushVar(adr, 8, false, kWord);
1194+ end else begin
1195+ f := x.typ^.fields;
1196+ while f <> nil do begin
1197+ adr.off := AdrOf(x).off + f^.val;
1198+ PushVar(adr, ScalarSize(f^.typ), Signed(f^.typ), KindOf(f^.typ));
1199+ f := f^.next;
1200+ end;
1201+ end;
1202+end;
1203+
1204+procedure PassArg(var c: TCall; var a: TItem);
1205+var p: PObj;
1206+begin
1207+ p := c.param;
1208+ if c.n >= High(c.isF) then MarkAt(a.pos, 'too many arguments');
1209+ if p = nil then begin
1210+ { past the parameters of a C procedure that ends in ...: a string
1211+ goes as a C string, an integer constant as an INT, a real
1212+ constant as an F64; C takes no F32 there }
1213+ if not c.sig^.variadic then WrongCount(c, a.pos, 'too many arguments');
1214+ if a.mode = mStr then Coerce(a, tPtrU8)
1215+ else if a.typ^.form = fConst then Coerce(a, tInt)
1216+ else if a.typ = tRConst then Coerce(a, tReal)
1217+ else if IsF32(a.typ) then MarkAt(a.pos, 'an F32 goes to ... as F64(x)')
1218+ else if not IsScalar(a.typ) then MarkAt(a.pos, 'only a single value goes to ...');
1219+ c.isF[c.n] := a.typ^.form = fReal;
1220+ c.pair[c.n] := false;
1221+ Value(a);
1222+ inc(c.n);
1223+ exit;
1224+ end;
1225+ c.isF[c.n] := (p^.typ^.form = fReal) and not p^.isVar;
1226+ passing := p;
1227+ passingAt := a.pos;
1228+ if p^.isVar then begin
1229+ NotReadOnly(a);
1230+ if (a.mode <> mVar) or not a.isVar then MarkAt(a.pos, 'a var parameter needs a variable');
1231+ if a.odd then MarkAt(a.pos, 'a field of a packed record can''t be a var parameter');
1232+ if not Same(a.typ, p^.typ) then Mismatch(a, 'a var parameter needs exactly ' + TypeName(p^.typ) + ', found ' + What(a));
1233+ if a.vol then MarkAt(a.pos, 'can''t pass through a volatile pointer to a var parameter');
1234+ Address(a);
1235+ end else if p^.typ^.form = fSlice then begin
1236+ Coerce(a, p^.typ);
1237+ PushWords(a);
1238+ c.pair[c.n] := true;
1239+ inc(c.n);
1240+ c.isF[c.n] := false;
1241+ end else if IsAggregate(p^.typ) then begin
1242+ Coerce(a, p^.typ);
1243+ if a.isVar or a.vol or (a.base <> bFrame) then CopyToTemp(a);
1244+ Address(a);
1245+ end else begin
1246+ Coerce(a, p^.typ);
1247+ Value(a);
1248+ end;
1249+ c.pair[c.n] := false;
1250+ inc(c.n);
1251+ c.param := p^.next;
1252+end;
1253+
1254+{ The call c made, with x its result as an item: none; a temporary, for a
1255+ slice or a record; two results on gen's stack (mWords); else one value
1256+ on the stack. }
1257+procedure EndCall(var c: TCall; var x: TItem);
1258+var res: PType;
1259+begin
1260+ if c.param <> nil then WrongCount(c, TokPos, 'too few arguments');
1261+ Call(c);
1262+ res := c.sig^.base;
1263+ FillChar(x, SizeOf(x), 0);
1264+ if res = nil then begin
1265+ x.mode := mNone; x.typ := tNone; x.obj := c.obj
1266+ end else if c.ret <> 0 then
1267+ TempItem(x, res, c.ret)
1268+ else begin
1269+ x.mode := mStack; x.typ := res;
1270+ if res^.tuple then x.mode := mWords;
1271+ end;
1272+end;
1273+
1274+{ Variants }
1275+
1276+{ A temporary of type t, all zero: for variants and record literals. }
1277+procedure ZeroTemp(var x: TItem; t: PType);
1278+var tmp: int64;
1279+begin
1280+ tmp := AllocTemp(t^.size, t^.align);
1281+ ZeroVar(FrameAdr(tmp), t^.size);
1282+ TempItem(x, t, tmp);
1283+end;
1284+
1285+procedure Construct(var x: TItem; c: PObj);
1286+begin
1287+ ZeroTemp(x, c^.typ);
1288+ PushConst(kWord, c^.val);
1289+ PopVar(FrameAdr(x.off), 8);
1290+end;
1291+
1292+procedure SetField(const x: TItem; f: PObj; var a: TItem);
1293+begin
1294+ Coerce(a, f^.typ);
1295+ if IsScalar(f^.typ) then begin
1296+ Value(a);
1297+ PopVar(FrameAdr(x.off + f^.val), ScalarSize(f^.typ));
1298+ end else begin
1299+ if a.vol then MarkAt(a.pos, 'can''t copy through a volatile pointer');
1300+ Address(a);
1301+ CopyTo(FrameAdr(x.off + f^.val), f^.typ^.size);
1302+ end;
1303+end;
1304+
1305+{ The slot match tests: a variant's address, or an enumeration's or an
1306+ integer's value. }
1307+function MatchBegin(var x: TItem): int64;
1308+var p: int64;
1309+begin
1310+ if x.typ^.form in [fEnum, fInt] then exit(ToSlot(x));
1311+ if (x.mode <> mVar) or (x.typ^.form <> fVariant) then MarkAt(x.pos, 'match needs a variant, an enumeration or an integer, found ' + What(x));
1312+ if x.ro then CopyToTemp(x); { its arms' names stand for a copy's fields }
1313+ Address(x);
1314+ p := AllocTemp(8, 8);
1315+ PopVar(FrameAdr(p), 8);
1316+ MatchBegin := p;
1317+end;
1318+
1319+{ To L unless the tag of the variant whose address is in slot p is tag }
1320+procedure MatchTag(p: int64; tag: int64; var L: longint);
1321+var a: TAdr;
1322+begin
1323+ PushVar(FrameAdr(p), 8, false, kWord);
1324+ a.base := bStack; a.chunk := -1; a.off := 0;
1325+ PushVar(a, 8, false, kWord);
1326+ PushConst(kWord, tag);
1327+ JumpCmp(sNeq, false, L);
1328+end;
1329+
1330+{ To body if the integer in slot p is from lo to hi: less its lo, it is
1331+ then at most hi - lo, compared unsigned, which holds for a signed type
1332+ or not, with no second jump. }
1333+procedure MatchRange(p, lo, hi: int64; var body: longint);
1334+begin
1335+ PushVar(FrameAdr(p), 8, false, kWord);
1336+ if lo = hi then begin
1337+ PushConst(kWord, lo);
1338+ JumpCmp(sEql, false, body);
1339+ exit;
1340+ end;
1341+ if lo <> 0 then begin
1342+ PushConst(kWord, lo);
1343+ gen.Op(sMinus, kWord, 8, false);
1344+ end;
1345+ PushConst(kWord, hi - lo);
1346+ JumpCmp(sLeq, false, body);
1347+end;
1348+
1349+{ A for loop's variable o, stepped by step, wrapping as its type does }
1350+procedure ForStep(o: PObj; step: int64);
1351+var v, w: TItem;
1352+begin
1353+ MakeItem(v, o);
1354+ if v.base = bReg then begin
1355+ { a variable in a register is stepped in it }
1356+ PushConst(kWord, step);
1357+ IncDecReg(v.chunk, IntSize(o^.typ), Signed(o^.typ), false);
1358+ exit;
1359+ end;
1360+ MakeItem(w, o);
1361+ Value(w);
1362+ PushConst(kWord, step);
1363+ gen.Op(sPlus, kWord, IntSize(o^.typ), Signed(o^.typ));
1364+ Assign(v, w);
1365+end;
1366+
1367+{ For a for loop: pushes the variable o and the limit lim, a constant or
1368+ the slot it was put in, and jumps to L if the one is op the other, as
1369+ the type of o compares }
1370+procedure ForCmp(o: PObj; const lim: TItem; op: TSym; var L: longint);
1371+var v, b: TItem;
1372+begin
1373+ MakeItem(v, o);
1374+ Value(v);
1375+ b := lim;
1376+ Value(b);
1377+ JumpCmp(op, o^.typ^.signed, L);
1378+end;
1379+
1380+{ The end of a round of a for loop, for a positive step s, as the report
1381+ has it: if v <= b and b - v < s, the loop ends; otherwise v becomes
1382+ v + s and the loop goes on while v <= b. Counting the distance left,
1383+ rather than comparing after the step, can't be fooled by v wrapping
1384+ around. A negative step is the same the other way round: Before, Past
1385+ and Within are indexed by up, whether the step is positive.
1386+ For a step of 1: v < b goes on to top, where v is stepped; v = b
1387+ ends; otherwise the body moved v past b.
1388+ For another step: v past b goes to past; else b - v (unsigned, as
1389+ v <= b) >= |step| goes on to top, and else the loop ends.
1390+ Past: v is stepped here and tested, going to body if within b. }
1391+procedure ForNext(o: PObj; const lim: TItem; step: int64; var exitL: longint; top, body: longint);
1392+const
1393+ Before: array[boolean] of TSym = (sGtr, sLss); { by a negative step, by a positive }
1394+ Past: array[boolean] of TSym = (sLss, sGtr);
1395+ Within: array[boolean] of TSym = (sGeq, sLeq);
1396+var v, b: TItem; L, pastL: longint; up: boolean;
1397+begin
1398+ up := step > 0;
1399+ L := NoLabel;
1400+ pastL := NoLabel;
1401+ if abs(step) = 1 then begin
1402+ ForCmp(o, lim, Before[up], L);
1403+ FixTo(L, top);
1404+ ForCmp(o, lim, sEql, exitL);
1405+ end else begin
1406+ ForCmp(o, lim, Past[up], pastL);
1407+ MakeItem(v, o);
1408+ b := lim;
1409+ if up then begin Value(b); Value(v) end
1410+ else begin Value(v); Value(b) end;
1411+ gen.Op(sMinus, kWord, 8, false);
1412+ PushConst(kWord, abs(step));
1413+ JumpCmp(sGeq, false, L);
1414+ FixTo(L, top);
1415+ Jump(exitL);
1416+ end;
1417+ Fix(pastL);
1418+ ForStep(o, step);
1419+ L := NoLabel;
1420+ ForCmp(o, lim, Within[up], L);
1421+ FixTo(L, body);
1422+end;
1423+
1424+{ Jumps to L if the condition x is false. The jumps waiting in x.fj join
1425+ L; those in x.tj are placed here, as x is true past this. }
1426+procedure CondJump(var x: TItem; var L: longint);
1427+begin
1428+ if x.typ^.form <> fBool then MarkAt(x.pos, 'a condition is a BOOL, found ' + What(x));
1429+ if x.mode = mCond then begin
1430+ JumpCmp(Negated[x.rel], x.relSigned, L);
1431+ L := JoinJumps(L, x.fj);
1432+ Fix(x.tj);
1433+ exit;
1434+ end;
1435+ Value(x);
1436+ JumpIf(L, false);
1437+end;
1438+
1439+{ As CondJump, but the jump to L is taken where the condition is true;
1440+ x.tj joins L and x.fj is placed here }
1441+procedure CondJumpTrue(var x: TItem; var L: longint);
1442+begin
1443+ if x.typ^.form <> fBool then MarkAt(x.pos, 'a condition is a BOOL, found ' + What(x));
1444+ if x.mode = mCond then begin
1445+ JumpCmp(x.rel, x.relSigned, L);
1446+ L := JoinJumps(L, x.tj);
1447+ Fix(x.fj);
1448+ exit;
1449+ end;
1450+ Value(x);
1451+ JumpIf(L, true);
1452+end;
1453+
1454+{ Procedures }
1455+
1456+procedure BeginProc(sig: PType; params: PObj);
1457+begin
1458+ result := sig^.base;
1459+ gen.BeginProc(sig, params);
1460+end;
1461+
1462+{ The result of return x: a value on top, a slice's two words on top,
1463+ or one copied behind the hidden pointer }
1464+procedure ReturnValue(var x: TItem);
1465+begin
1466+ if result = nil then MarkAt(x.pos, 'this procedure returns nothing');
1467+ Coerce(x, result);
1468+ if InTwoRegs(result) then PushWords(x)
1469+ else if IsAggregate(result) then begin
1470+ if x.vol then MarkAt(x.pos, 'can''t copy through a volatile pointer');
1471+ Address(x);
1472+ CopyResult(0, result^.size);
1473+ end else Value(x);
1474+end;
1475+
1476+{ One of several results: of two words, a value left on top for
1477+ ReturnJump to put in rax or rdx; else into its place behind the
1478+ hidden pointer. }
1479+procedure ReturnField(f: PObj; var x: TItem);
1480+begin
1481+ Coerce(x, f^.typ);
1482+ if InTwoRegs(result) then Value(x)
1483+ else if IsScalar(f^.typ) then begin
1484+ Value(x);
1485+ ResultTo(f^.val, ScalarSize(f^.typ));
1486+ end else begin
1487+ if x.vol then MarkAt(x.pos, 'can''t copy through a volatile pointer');
1488+ Address(x);
1489+ CopyResult(f^.val, f^.typ^.size);
1490+ end;
1491+end;
1492+
1493+{ Several results at once, the call's that return f(x) passes on. }
1494+procedure ReturnAll(var x: TItem);
1495+begin
1496+ if InTwoRegs(result) then PushWords(x)
1497+ else begin
1498+ Address(x);
1499+ CopyResult(0, result^.size);
1500+ end;
1501+end;
1502+
1503+procedure ReturnNone;
1504+begin
1505+ if result <> nil then Mark('return needs a result of ' + TypeName(result));
1506+ ReturnJump;
1507+end;
1508+
1509+{ Keeps a variable's address in a frame slot, rather than on the stack,
1510+ while other code runs. }
1511+procedure Pin(var x: TItem);
1512+var s: int64;
1513+begin
1514+ if (x.mode = mVar) and (x.base = bStack) then begin
1515+ Address(x);
1516+ s := AllocTemp(8, 8);
1517+ PopVar(FrameAdr(s), 8);
1518+ x.base := bSlot;
1519+ x.chunk := s;
1520+ end;
1521+end;
1522+
1523+{ INC(v, k) or DEC: v's address is on the stack, from Address. }
1524+procedure IncDec(var v, k: TItem; dec: boolean);
1525+begin
1526+ CoerceExact(k, v.typ, '');
1527+ Value(k);
1528+ if v.base = bReg then IncDecReg(v.chunk, ScalarSize(v.typ), v.typ^.signed, dec)
1529+ else gen.IncDec(ScalarSize(v.typ), v.typ^.signed, dec);
1530+end;
1531+
1532+{ COPY(d, s): d, an array variable or a slice, as a slice in the frame,
1533+ before s is read }
1534+procedure CopyDest(var d: TItem);
1535+begin
1536+ if not IsSeq(d.typ) or (d.mode = mStr) or (d.typ^.form = fArray) and ((d.mode <> mVar) or not d.isVar) then
1537+ MarkAt(d.pos, 'COPY copies into an array variable or a slice, found ' + What(d));
1538+ if d.typ^.form = fArray then NotReadOnly(d);
1539+ SeqSlice(d);
1540+end;
1541+
1542+{ ... and the elements of s copied to its start }
1543+procedure CopyFrom(var d, s: TItem);
1544+begin
1545+ if not IsSeq(s.typ) or not Same(ElemOf(s.typ), d.typ^.base) then
1546+ MarkAt(s.pos, 'COPY copies elements of ' + TypeName(d.typ^.base) + ', found ' + What(s));
1547+ SeqSlice(s);
1548+ CopySlice(d.off, s.off, d.typ^.base^.size, checks, s.pos);
1549+end;
1550+
1551+{ An error is the address of its length, followed by its message. }
1552+function ErrorChunk(var x: TItem; module, name: longint): longint;
1553+var c: longint; p: PBytes;
1554+begin
1555+ if x.mode <> mStr then MarkAt(x.pos, 'an error is made from a string');
1556+ p := GetMem(x.val + 8);
1557+ PInt64(p)^ := x.val;
1558+ Move(rodata^[chunks^[x.chunk].start], p^[8], x.val);
1559+ c := NewChunk(secRodata, module, name);
1560+ SetData(c, p, x.val + 8, 8);
1561+ FreeMem(p);
1562+ ErrorChunk := c;
1563+end;
1564+
1565+procedure Msg(var x: TItem);
1566+var s: int64;
1567+begin
1568+ Coerce(x, tError);
1569+ Value(x);
1570+ s := AllocTemp(16, 8);
1571+ ErrorText(s);
1572+ TempItem(x, tBytes, s);
1573+end;
1574+
1575+end.

seed/link.pas added +334 -0

@@ -0,0 +1,334 @@
1+{ link.pas: tree shaking, layout and patching.
2+
3+ Starting from the entry chunk, marks every chunk the program can
4+ reach through fixups; the rest is left out. Then gives each live
5+ chunk its address and builds the images of text and rodata, with
6+ every fixup patched.
7+
8+ The file is laid out so that each section can be mapped as it lies:
9+ text right after the headers, rodata on the next page, then a
10+ writable page that starts with the table the dynamic loader reads
11+ (none in a static program) and goes on as bss, in memory only. The
12+ loader's other tables come at the end of rodata; elf.pas writes them
13+ in the room left there.
14+
15+ Depends on: chunk for chunks and fixups, scan for names and errors.
16+ Leaves out: the file format; that is elf.pas. }
17+
18+unit link;
19+
20+{$mode objfpc}{$H-}
21+
22+interface
23+
24+uses scan, diag, chunk;
25+
26+const
27+ Base = $400000;
28+ Page = 4096;
29+
30+var
31+ textOff, textSize: int64; { file offset and size of text, at Base + textOff }
32+ roOff, roSize: int64; { rodata, the room for the loader's tables included }
33+ roAdr: int64; { where rodata is loaded }
34+ extraAdr: int64; { that room }
35+ bssAdr, bssSize: int64; { the writable segment, the loader's table first }
36+ bssOff: int64; { the file offset of that table }
37+ textImg, roImg: PBytes;
38+ placesChunk: longint = -1; { the rodata chunk of the places, made here }
39+ linesOff, linesSize: int64; { the line table, in the places: .debug_line }
40+
41+procedure MarkLive(entry: longint);
42+procedure LinkAll(headerSize, roExtra, dynSize: int64);
43+
44+implementation
45+
46+{ Marks live each chunk reached from entry through the fixups. }
47+procedure MarkLive(entry: longint);
48+var stack: PLongs; sp, c, f, t: longint; fx: PFixups;
49+begin
50+ stack := GetMem(numChunks * 4);
51+ sp := 0;
52+ chunks^[entry].live := true;
53+ stack^[0] := entry;
54+ sp := 1;
55+ while sp > 0 do begin
56+ dec(sp);
57+ c := stack^[sp];
58+ if chunks^[c].size < 0 then Fatal(ChunkName(c) + ' is declared but never defined');
59+ { code and constants have fixups; variables start at zero, holding
60+ no addresses }
61+ case chunks^[c].sec of
62+ secText: fx := fixups;
63+ secRodata: fx := dataFixups;
64+ else continue;
65+ end;
66+ for f := chunks^[c].firstFix to chunks^[c].firstFix + chunks^[c].numFix - 1 do begin
67+ t := fx^[f].chunk;
68+ if not chunks^[t].live then begin
69+ chunks^[t].live := true;
70+ stack^[sp] := t;
71+ inc(sp);
72+ end;
73+ end;
74+ end;
75+ FreeMem(stack);
76+end;
77+
78+{ Gives the live chunks of one section their places, from start;
79+ returns the end. }
80+function Place(sec: TSection; start: int64): int64;
81+var c: longint; a: int64;
82+begin
83+ a := start;
84+ for c := 0 to numChunks - 1 do
85+ if chunks^[c].live and (chunks^[c].sec = sec) then begin
86+ a := (a + chunks^[c].align - 1) div chunks^[c].align * chunks^[c].align;
87+ chunks^[c].adr := a;
88+ a := a + chunks^[c].size;
89+ end;
90+ Place := a;
91+end;
92+
93+{ The line table, DWARF 4's line program, which gdb reads as
94+ .debug_line and Rt to say where code comes from: one sequence for
95+ each live procedure with lines, a row for each place noted, its
96+ address, file, line and column. A row whose address and line move a
97+ little is one byte, a special opcode; the others are made of the
98+ standard ones. Made in lp, lpLen bytes long. }
99+const
100+ LineBase = -5; LineRange = 14; OpcodeBase = 13; { the special opcodes' }
101+
102+var
103+ lp: PBytes;
104+ lpLen, lpCap: longint;
105+
106+procedure PutB(v: int64);
107+begin
108+ if lpLen = lpCap then begin
109+ lpCap := lpCap * 2 + 256;
110+ lp := ReAllocMem(lp, lpCap);
111+ end;
112+ lp^[lpLen] := byte(v);
113+ inc(lpLen);
114+end;
115+
116+procedure PutN(v: int64; n: longint);
117+var i: longint;
118+begin
119+ for i := 1 to n do begin PutB(v); v := v shr 8 end;
120+end;
121+
122+{ LEB128, unsigned and signed }
123+procedure PutU(v: int64);
124+begin
125+ while v >= $80 do begin PutB(v and $7F or $80); v := v shr 7 end;
126+ PutB(v);
127+end;
128+
129+procedure PutS(v: int64);
130+begin
131+ while (v < -64) or (v >= 64) do begin PutB(v and $7F or $80); v := SarInt64(v, 7) end;
132+ PutB(v and $7F);
133+end;
134+
135+{ The line program of the files paths, nfiles of them, numbered from
136+ 1, as they are written in the table }
137+procedure MakeLines(paths: PLongs; nfiles: longint);
138+var i, f, c, cf, cl, cc, op: longint; at, da, dl: int64; s: shortstring;
139+begin
140+ lpLen := 0;
141+ PutN(0, 4); { unit_length, patched below }
142+ PutN(4, 2); { version }
143+ PutN(0, 4); { header_length, patched below }
144+ PutB(1); PutB(1); { minimum_instruction_length, maximum_operations }
145+ PutB(1); { default_is_stmt }
146+ PutB(LineBase); PutB(LineRange); PutB(OpcodeBase);
147+ for i := 1 to OpcodeBase - 1 do PutB(ord(i in [2, 3, 4, 5, 9, 12])); { their operands }
148+ PutB(0); { no include directories }
149+ for f := 0 to nfiles - 1 do begin
150+ s := ShownPath(NameOf(paths^[f]));
151+ for i := 1 to length(s) do PutB(ord(s[i]));
152+ PutN(0, 4); { its end, directory, time, length }
153+ end;
154+ PutB(0);
155+ PLongint(@lp^[6])^ := lpLen - 10;
156+ i := 0;
157+ while i < numLines do begin
158+ c := lines^[i].chunk;
159+ if not chunks^[c].live then begin inc(i); continue end;
160+ PutB(0); PutU(9); PutB(2); { DW_LNE_set_address }
161+ PutN(chunks^[c].adr + lines^[i].at - chunks^[c].start, 8);
162+ at := lines^[i].at; cf := 1; cl := 1; cc := 0;
163+ while (i < numLines) and (lines^[i].chunk = c) do begin
164+ f := 1;
165+ while paths^[f - 1] <> lines^[i].path do inc(f);
166+ if f <> cf then begin PutB(4); PutU(f); cf := f end; { DW_LNS_set_file }
167+ if lines^[i].col <> cc then begin PutB(5); PutU(lines^[i].col); cc := lines^[i].col end; { DW_LNS_set_column }
168+ da := lines^[i].at - at;
169+ dl := lines^[i].line - cl;
170+ op := (dl - LineBase) + LineRange * da + OpcodeBase;
171+ if (dl >= LineBase) and (dl < LineBase + LineRange) and (op <= 255) then PutB(op) { a special opcode: a row }
172+ else begin
173+ if da > 0 then begin PutB(2); PutU(da) end; { DW_LNS_advance_pc }
174+ if dl <> 0 then begin PutB(3); PutS(dl) end; { DW_LNS_advance_line }
175+ PutB(1); { DW_LNS_copy: a row }
176+ end;
177+ at := lines^[i].at; cl := lines^[i].line;
178+ inc(i);
179+ end;
180+ PutB(2); PutU(chunks^[c].start + chunks^[c].size - at);
181+ PutB(0); PutU(1); PutB(1); { DW_LNE_end_sequence }
182+ end;
183+ PLongint(@lp^[0])^ := lpLen - 4;
184+end;
185+
186+{ The places that Rt reads to say where a failed check or a signal
187+ was, and what calls were under way: where the line table is in them,
188+ where text starts and stops, the numbers of procedures and of their
189+ variables (I64s); for each live procedure where it starts and stops,
190+ the offset of its name, its first variable and how many it has, and
191+ the registers of variables it saves, as bits of gen's VarRegs, and
192+ the frame offset they are saved at (U32s); for each variable the
193+ offset of its name, its place in the frame and its kind, as
194+ parse.pas's VarKind (U32s); then the names, each ending in a zero
195+ byte; then the line table (MakeLines), at linesOff. They are in no
196+ order, since Rt looks at them only as the program stops. }
197+procedure MakePlaces(start, stop: int64);
198+var
199+ files, first, count: PLongs; buf: PBytes;
200+ i, f, nfiles, k, np, nv, c, v, at, names: longint;
201+
202+ procedure Name(const s: shortstring);
203+ begin
204+ PLongint(@buf^[at])^ := names - k;
205+ Move(s[1], buf^[names], length(s));
206+ buf^[names + length(s)] := 0;
207+ names := names + length(s) + 1;
208+ at := at + 4;
209+ end;
210+
211+begin
212+ files := GetMem(numLines * 4 + 4);
213+ first := GetMem(numChunks * 4);
214+ count := GetMem(numChunks * 4);
215+ FillChar(count^, numChunks * 4, 0);
216+ for v := numVarNotes - 1 downto 0 do begin
217+ first^[varNotes[v].chunk] := v;
218+ inc(count^[varNotes[v].chunk]);
219+ end;
220+ nfiles := 0; k := 0; np := 0; nv := 0;
221+ for i := 0 to numLines - 1 do
222+ if chunks^[lines^[i].chunk].live then begin
223+ f := 0;
224+ while (f < nfiles) and (files^[f] <> lines^[i].path) do inc(f);
225+ if f = nfiles then begin
226+ files^[f] := lines^[i].path;
227+ inc(nfiles);
228+ end;
229+ end;
230+ MakeLines(files, nfiles);
231+ for c := 0 to numChunks - 1 do
232+ if chunks^[c].live and (chunks^[c].sec = secText) and (chunks^[c].module >= 0) then begin
233+ inc(np);
234+ k := k + length(ChunkName(c)) + 1;
235+ for v := first^[c] to first^[c] + count^[c] - 1 do k := k + length(NameOf(varNotes[v].name)) + 1;
236+ nv := nv + count^[c];
237+ end;
238+ buf := GetMem(40 + 28 * np + 12 * nv + k + lpLen);
239+ { the pool of names starts at k, the line table after it }
240+ k := 40 + 28 * np + 12 * nv;
241+ names := k;
242+ at := 40;
243+ v := 0;
244+ for c := 0 to numChunks - 1 do
245+ if chunks^[c].live and (chunks^[c].sec = secText) and (chunks^[c].module >= 0) then begin
246+ PLongint(@buf^[at])^ := chunks^[c].adr;
247+ PLongint(@buf^[at + 4])^ := chunks^[c].adr + chunks^[c].size;
248+ at := at + 8;
249+ Name(ChunkName(c));
250+ PLongint(@buf^[at])^ := v;
251+ PLongint(@buf^[at + 4])^ := count^[c];
252+ PLongint(@buf^[at + 8])^ := chunks^[c].saveMask;
253+ PLongint(@buf^[at + 12])^ := chunks^[c].saveAt;
254+ at := at + 16;
255+ v := v + count^[c];
256+ end;
257+ for c := 0 to numChunks - 1 do
258+ if chunks^[c].live and (chunks^[c].sec = secText) and (chunks^[c].module >= 0) then
259+ for v := first^[c] to first^[c] + count^[c] - 1 do begin
260+ Name(NameOf(varNotes[v].name));
261+ PLongint(@buf^[at])^ := varNotes[v].off;
262+ PLongint(@buf^[at + 4])^ := varNotes[v].kind;
263+ at := at + 8;
264+ end;
265+ linesOff := names;
266+ linesSize := lpLen;
267+ Move(lp^, buf^[names], lpLen);
268+ PInt64(@buf^[0])^ := linesOff;
269+ PInt64(@buf^[8])^ := start;
270+ PInt64(@buf^[16])^ := stop;
271+ PInt64(@buf^[24])^ := np;
272+ PInt64(@buf^[32])^ := nv;
273+ SetData(placesChunk, buf, names + lpLen, 8);
274+ FreeMem(buf); FreeMem(files); FreeMem(first); FreeMem(count);
275+end;
276+
277+{ Places the live chunks, leaving roExtra bytes at the end of rodata
278+ and dynSize at the start of the writable segment. The segments follow
279+ each other in the file with no padding, and each is loaded a page
280+ further from its file offset than the one before: rodata at Base +
281+ Page + roOff, the writable segment at Base + 2 * Page + bssOff. So an
282+ address and its offset agree within a page, as the loader needs, and
283+ no two segments, with their different permissions, share a page.
284+ The bss of a program without the loader's table has no bytes in the
285+ file, and starts on a page of its own. }
286+procedure LinkAll(headerSize, roExtra, dynSize: int64);
287+var c, f, at: longint; e, p, v: int64;
288+begin
289+ textOff := (headerSize + 31) div 32 * 32; { as each code chunk is }
290+ e := Place(secText, Base + textOff);
291+ textSize := e - (Base + textOff);
292+ if placesChunk >= 0 then MakePlaces(Base + textOff, e);
293+ roOff := (textOff + textSize + 31) div 32 * 32;
294+ roAdr := Base + Page + roOff;
295+ e := Place(secRodata, roAdr);
296+ extraAdr := (e + 7) div 8 * 8;
297+ if roExtra > 0 then e := extraAdr + roExtra;
298+ roSize := e - roAdr;
299+ bssOff := (roOff + roSize + 31) div 32 * 32;
300+ if dynSize > 0 then bssAdr := Base + 2 * Page + bssOff
301+ else bssAdr := (roAdr + roSize + Page - 1) div Page * Page;
302+ e := Place(secBss, bssAdr + dynSize);
303+ bssSize := e - bssAdr;
304+
305+ textImg := GetMem(textSize + 1);
306+ { the gaps between code chunks are int3, a trap if ever run }
307+ FillChar(textImg^, textSize + 1, $CC);
308+ roImg := GetMem(roSize + 1);
309+ FillChar(roImg^, roSize + 1, 0);
310+ for c := 0 to numChunks - 1 do
311+ if chunks^[c].live then
312+ case chunks^[c].sec of
313+ secText: begin
314+ p := chunks^[c].adr - (Base + textOff);
315+ Move(code^[chunks^[c].start], textImg^[p], chunks^[c].size);
316+ for f := chunks^[c].firstFix to chunks^[c].firstFix + chunks^[c].numFix - 1 do begin
317+ at := fixups^[f].at - chunks^[c].start;
318+ { rel32: from the end of the field to the target }
319+ v := chunks^[fixups^[f].chunk].adr + fixups^[f].addend
320+ - (chunks^[c].adr + at + 4);
321+ PLongint(@textImg^[p + at])^ := longint(v);
322+ end;
323+ end;
324+ secRodata: begin
325+ p := chunks^[c].adr - roAdr;
326+ Move(rodata^[chunks^[c].start], roImg^[p], chunks^[c].size);
327+ for f := chunks^[c].firstFix to chunks^[c].firstFix + chunks^[c].numFix - 1 do
328+ PInt64(@roImg^[p + dataFixups^[f].at])^ :=
329+ chunks^[dataFixups^[f].chunk].adr + dataFixups^[f].addend;
330+ end;
331+ end;
332+end;
333+
334+end.

seed/parse.pas added +3285 -0

@@ -0,0 +1,3285 @@
1+{ parse.pas: the parser.
2+
3+ Reads modules by recursive descent and has gen.pas emit code as it
4+ goes: one pass, no tree. Importing a module that isn't compiled yet
5+ compiles it there and then, so modules are finished in an order where
6+ each comes after the modules it imports; that is the order in which
7+ their bodies run.
8+
9+ A module may come in one file per target (Name.linux-x86_64.raz and
10+ so on). The file for this target is compiled; the others beside it
11+ are read for their declarations only, and must export the same
12+ interface.
13+
14+ Depends on: scan, sym, chunk for data, item and gen for code.
15+ Leaves out: linking; a module only records the libraries it names,
16+ and whether it uses C or says link static. }
17+
18+unit parse;
19+
20+{$mode objfpc}{$H-}
21+
22+interface
23+
24+uses scan, diag, sym, chunk, gen, item;
25+
26+const
27+ Target = 'linux-x86_64';
28+ TargetOS = 'linux';
29+ TargetArch = 'x86_64';
30+ { Whether the target has reals (report, appendix A): x86-64 always has
31+ SSE2. Without them, used code that computes with one is an error,
32+ which raz.pas reports once it knows what the program uses. }
33+ HasReals: boolean = true;
34+
35+var
36+ libDir, mainDir: shortstring;
37+ incDirs: array[0..15] of shortstring;
38+ numInc: longint;
39+ firstModule, lastModule: PModule; { in the order they were finished }
40+
41+function CompileMain(const path: shortstring): PModule;
42+function ImportModule(name: longint; const args: TArgs): PModule;
43+
44+implementation
45+
46+uses BaseUnix;
47+
48+type
49+ PLoop = ^TLoop;
50+ TLoop = record
51+ brk: longint; { the chain of its breaks }
52+ base: longint; { the deferred statements in force outside it }
53+ end;
54+
55+ { A generic module's import whose instance isn't made yet (deferred,
56+ numDeferred); not to be confused with a defer statement (defers) }
57+ TDeferred = record
58+ o: PObj; { the name it imports as }
59+ m: PModule; { the module that imports it }
60+ mname: longint; { the generic module }
61+ args: TScanState; { at the "(" of its arguments }
62+ at: TPos; { the import }
63+ end;
64+
65+var
66+ checkMode: boolean; { reading a file only for its interface }
67+ inTypes: boolean; { in a type section: ^T may name a later type }
68+ fwdTypes: array[0..255] of PType;
69+ fwdPos: array[0..255] of TPos; { where each names its type }
70+ numFwd: longint;
71+ lastCalled: PObj; { the procedure the last call was of, if it had a name }
72+ passOn: boolean; { the next factor may be a call with several results, for return }
73+ curProc: PObj; { the procedure being compiled, or nil }
74+ declExported: boolean; { the export mark of the declaration being read }
75+ curLoop: PLoop; { the innermost loop, or nil }
76+ defers: array[0..63] of longint; { the defer statements in force, their code's addresses }
77+ numDefers: longint;
78+ deferring: boolean; { compiling a defer statement's statement }
79+ directDefer: boolean; { ... as the statement itself, not in a list }
80+ deferSlot: int64; { keeps a result while deferred statements run }
81+ curResult: PType; { the result type of the procedure being compiled }
82+ inExtern: boolean; { reading an extern's signature: ... allowed }
83+ tArgv, tBodySig: PType;
84+ nameRt, nameFail, nameMain, nameBody, nameStatic, nameCheck, nameOff, nameAdr: longint;
85+ declaring: array[0..63] of longint; { the names the declaration being read declares }
86+ numDeclaring: longint;
87+ skipped: boolean; { the last statement had an error and was skipped }
88+ deferred: array[0..63] of TDeferred; { generic imports not yet made, not defer statements }
89+ numDeferred: longint;
90+ making: boolean; { reading an instance's arguments, at its first use }
91+ stray: boolean; { an "end" in this procedure stood left of its statement's line }
92+ strayAt: TPos; { ... the first such statement }
93+ elseIf: boolean; { an "else if" in this procedure }
94+ drops: array[0..4095] of record
95+ at: TPos; { a call standing on its own that drops results }
96+ n: longint; { ... how many }
97+ end;
98+ numDrops: longint; { the module being compiled has those from its
99+ first one, saved by CompileFile, to here }
100+ ends: boolean; { the statements just read never go on past
101+ their end: each way through them returns }
102+ useAt: TPos; { ... which is here }
103+
104+procedure Expression(var x: TItem; want: PType); forward;
105+function ParseType: PType; forward;
106+procedure Statements; forward;
107+procedure Statement; forward;
108+
109+{ Little helpers }
110+
111+{ A missing symbol is reported just after the one before it. }
112+procedure Expected(const what: shortstring);
113+begin
114+ if tok = sBlank then Mark('_ isn''t a name: it is the blank, which stands only left of :=');
115+ MarkAt(MissingPos, 'expected ' + what + ', found ' + Found);
116+end;
117+
118+procedure Expect(s: TSym);
119+begin
120+ if (tok = sLbrace) and (s in [sThen, sDo]) then
121+ MarkHelp(MissingPos, 'expected ' + SymText(s) + ', found ' + Found, 'a block is written ' + SymText(s) + ' ... end');
122+ if tok <> s then Expected(SymText(s));
123+ Next;
124+end;
125+
126+{ The end of a block statement at start, whose line is indented to
127+ ind. An "end" left of that was most likely meant for a block around
128+ the statement, which leaves the statement's own "end" missing: the
129+ first such is kept for EndMissing. }
130+procedure CloseEnd(const start: TPos; ind: longint);
131+begin
132+ if (tok = sEnd) and not stray and (Indent < ind) then begin
133+ stray := true;
134+ strayAt := start;
135+ end;
136+ Expect(sEnd);
137+end;
138+
139+{ The error of a procedure or module whose own "end" isn't where it
140+ should be, with what CloseEnd saw }
141+procedure EndMissing(const p: TPos; const msg: shortstring);
142+begin
143+ Error(p, msg);
144+ if stray then Note(strayAt, 'is this statement''s "end" missing? one further left closes it');
145+ if elseIf then Help('raz writes elsif: "else if" begins an if that needs its own "end"');
146+ Fail;
147+end;
148+
149+function Name(const s: shortstring): longint;
150+begin
151+ Name := Intern(@s[1], length(s));
152+end;
153+
154+{ A name being declared, and whether it is exported; at is the name }
155+procedure IdentDef(var n: longint; var exp: boolean; var at: TPos);
156+begin
157+ if tok <> sIdent then Expected('a name');
158+ n := id;
159+ at := TokPos;
160+ Next;
161+ exp := false;
162+ if tok = sTimes then begin
163+ exp := true;
164+ Next;
165+ end;
166+end;
167+
168+{ Declares o in the innermost scope. Its module keeps its declarations
169+ in order: its own, for the interface check, and its procedures', to
170+ warn of those never used. }
171+procedure Declare(o: PObj);
172+begin
173+ Insert(o, TopScope);
174+ if TopScope = curModule^.scope then begin
175+ if curModule^.last = nil then curModule^.first := o
176+ else curModule^.last^.link := o;
177+ curModule^.last := o;
178+ end else begin
179+ if curModule^.lastLocal = nil then curModule^.locals := o
180+ else curModule^.lastLocal^.link := o;
181+ curModule^.lastLocal := o;
182+ end;
183+end;
184+
185+{ o is named: a procedure naming itself doesn't count }
186+procedure Named(o: PObj);
187+begin
188+ if o <> curProc then begin
189+ o^.used := true;
190+ o^.read := true;
191+ end;
192+end;
193+
194+{ Recovery
195+
196+ After an error the parser goes on with the next statement or
197+ declaration, so that one run reports every error. Each statement and
198+ declaration is a recovery point: it notes the state of the scanner
199+ and the parser where it starts, and an error (MarkAt) jumps back to
200+ it. The state is put back, the scanner reads the construct again
201+ from its start, skipping to its end, and the parser carries on after
202+ it. Nothing is generated after an error, so the code half made for
203+ the construct does no harm. A name that isn't declared is declared
204+ where it is used, with type tPoison, and what follows from it is not
205+ reported again; so are the names of a declaration that had an error.
206+
207+ Skipping counts the words that open and close blocks. A symbol at
208+ the start of a line is taken to start a declaration of the module,
209+ as layout has it: a statement skipped up to one gives up its
210+ procedure, and the procedure is skipped up to its end. }
211+
212+type
213+ TRecover = record
214+ jb: jmp_buf;
215+ outer: ^jmp_buf;
216+ scan: TScanState;
217+ scopes, depth, pushed, numDefers: longint;
218+ loop: PLoop;
219+ result: PType;
220+ deferring, directDefer, quiet: boolean;
221+ end;
222+
223+procedure Guard(var r: TRecover);
224+begin
225+ r.outer := recovery;
226+ SaveScan(r.scan);
227+ r.scopes := ScopeDepth; r.depth := depth; r.pushed := pushed; r.numDefers := numDefers;
228+ r.loop := curLoop; r.result := curResult;
229+ r.deferring := deferring; r.directDefer := directDefer; r.quiet := quiet;
230+ recovery := @r.jb;
231+ quiet := false;
232+end;
233+
234+procedure Unguard(var r: TRecover);
235+begin
236+ recovery := r.outer;
237+ quiet := r.quiet;
238+ skipping := false;
239+end;
240+
241+{ After an error: the state as it was at the start of r's construct,
242+ whose first symbol is again the current one }
243+procedure Restore(var r: TRecover);
244+begin
245+ RestoreScan(r.scan);
246+ skipping := true;
247+ CutScopes(r.scopes); ResetStack(r.depth, r.pushed); numDefers := r.numDefers;
248+ curLoop := r.loop; curResult := r.result;
249+ deferring := r.deferring; directDefer := r.directDefer;
250+ inTypes := false; declExported := false; inExtern := false; making := false;
251+end;
252+
253+{ Gives up the construct r is for, and the one around it }
254+procedure GiveUp(var r: TRecover);
255+begin
256+ Unguard(r);
257+ if recovery = nil then Finish;
258+ longjmp(recovery^, 1);
259+end;
260+
261+{ Reads to the end of a statement or declaration, from its first
262+ symbol: up to the ";" that ends it, not read, or to the "end",
263+ "else", "elsif", "until" or "|" of the statement around it (an arm's
264+ "|" comes after a ";", the operator's after an operand). False if it
265+ stopped at a symbol that starts a line, or the end of the file. }
266+function SkipConstruct: boolean;
267+var d, p: longint; prev: TSym;
268+begin
269+ d := 0; p := 0; prev := sSemicolon;
270+ repeat
271+ case tok of
272+ sIf, sWhile, sFor, sMatch, sRepeat, sRecord, sVariant: inc(d);
273+ sEnd, sUntil: if d = 0 then exit(true) else dec(d);
274+ sElse, sElsif: if (d = 0) and (p = 0) then exit(true);
275+ sBar: if (d = 0) and (p = 0) and (prev = sSemicolon) then exit(true);
276+ sLparen, sLbrak, sLbrace: inc(p);
277+ sRparen, sRbrak, sRbrace: if p > 0 then dec(p);
278+ sSemicolon: if (d = 0) and (p = 0) then exit(true);
279+ sEof: exit(false);
280+ end;
281+ prev := tok;
282+ Next;
283+ until AtLineStart;
284+ SkipConstruct := false;
285+end;
286+
287+{ Declares n where it is used, after it was reported as not declared,
288+ or after the declaration of it had an error }
289+function Poison(n: longint): PObj;
290+var o: PObj;
291+begin
292+ o := NewObj(oConst, n, tPoison);
293+ Insert(o, TopScope);
294+ Poison := o;
295+end;
296+
297+procedure WillDeclare(n: longint);
298+begin
299+ if numDeclaring <= High(declaring) then declaring[numDeclaring] := n;
300+ inc(numDeclaring);
301+end;
302+
303+{ After a declaration had an error: its names are poison, and reading
304+ goes on after it }
305+procedure SkipDeclaration;
306+var i: longint;
307+begin
308+ for i := 0 to numDeclaring - 1 do
309+ if (i <= High(declaring)) and (Find(TopScope, declaring[i]) = nil) then
310+ Poison(declaring[i]);
311+ if SkipConstruct and (tok = sSemicolon) then Next;
312+end;
313+
314+function ConstValue(var x: TItem): int64;
315+begin
316+ if x.mode <> mConst then MarkAt(x.pos, 'expected a constant');
317+ ConstValue := x.val;
318+end;
319+
320+function ConstExpr: int64;
321+var x: TItem;
322+begin
323+ Expression(x, nil);
324+ if not IsInt(x.typ) then MarkAt(x.pos, 'expected an integer constant, found ' + What(x));
325+ ConstExpr := ConstValue(x);
326+end;
327+
328+{ Help after a name that isn't found: o, the closest name in reach }
329+procedure DidYouMean(o: PObj);
330+begin
331+ if o <> nil then Help('did you mean ' + NameOf(o^.name) + '?');
332+end;
333+
334+{ Where module n is found, if it is: dir and the file in it }
335+function ModuleFile(n: longint; var dir, f: shortstring): boolean; forward;
336+
337+{ Reports name n at p as not declared, with what it may have meant }
338+procedure NotDeclared(const p: TPos; n: longint);
339+var dir, f: shortstring;
340+begin
341+ Error(p, NameOf(n) + ' isn''t declared');
342+ if ModuleFile(n, dir, f) then Help(NameOf(n) + ' is a module: import ' + NameOf(n))
343+ else if (NameOf(n) = 'elif') or (NameOf(n) = 'elseif') then Help('raz writes elsif')
344+ else if Reserved(Name(LowerCase(NameOf(n)))) then Help('a reserved word is written in lower case: ' + LowerCase(NameOf(n)))
345+ else DidYouMean(Closest(n, -1));
346+end;
347+
348+procedure FirstUse(o: PObj; const at: TPos); forward;
349+procedure InstancesFor(wholeRest: boolean); forward;
350+procedure AddImport(m, im: PModule); forward;
351+
352+function QualIdent: PObj;
353+var o: PObj; m: PModule; at: TPos;
354+begin
355+ if tok <> sIdent then Expected('a name');
356+ at := TokPos;
357+ o := Lookup(id);
358+ if o = nil then begin
359+ if not making then Poison(id); { it may yet be declared }
360+ quiet := false;
361+ NotDeclared(at, id);
362+ if making then Note(useAt, 'the instance is made here, where it is first used');
363+ Fail;
364+ end;
365+ if o^.typ = tPoison then quiet := true;
366+ Named(o);
367+ Next;
368+ if o^.cls = oModule then begin
369+ if o^.module = nil then FirstUse(o, at);
370+ Expect(sPeriod);
371+ if tok <> sIdent then Expected('a name');
372+ m := o^.module;
373+ o := Find(m^.scope, id);
374+ if (o = nil) or not o^.exported then begin
375+ Error(TokPos, NameOf(id) + ' isn''t exported by ' + NameOf(m^.name));
376+ if o <> nil then Note(o^.pos, NameOf(id) + ' is declared here, without a *')
377+ else DidYouMean(Closest(id, m^.scope));
378+ Fail;
379+ end;
380+ Next;
381+ end;
382+ QualIdent := o;
383+end;
384+
385+{ The field of record type t named by the current symbol }
386+function FieldOf(t: PType): PObj;
387+var f: PObj;
388+begin
389+ f := Find(t^.scope, id);
390+ if f = nil then begin
391+ Error(TokPos, TypeName(t) + ' has no field ' + NameOf(id));
392+ DidYouMean(Closest(id, t^.scope));
393+ Fail;
394+ end;
395+ if not f^.exported and (t^.module <> curModule) then begin
396+ Error(TokPos, 'field ' + NameOf(id) + ' of ' + TypeName(t) + ' isn''t exported');
397+ Note(f^.pos, NameOf(id) + ' is declared here, without a *');
398+ Fail;
399+ end;
400+ FieldOf := f;
401+end;
402+
403+function NewPtr(base: PType; vol: boolean): PType;
404+var t: PType;
405+begin
406+ t := NewType(fPtr, 8, 8);
407+ t^.base := base;
408+ t^.vol := vol;
409+ NewPtr := t;
410+end;
411+
412+{ Types }
413+
414+function RecordType: PType;
415+var
416+ t, ft: PType; f, last: PObj; names: array[0..63] of longint;
417+ exps: array[0..63] of boolean; poss: array[0..63] of TPos;
418+ n, i: longint; off, a, maxA: int64;
419+begin
420+ t := NewType(fRecord, 0, 1);
421+ if tok = sPacked then begin t^.packd := true; Next end;
422+ Expect(sRecord);
423+ t^.scope := NewScope;
424+ off := 0; maxA := 1; last := nil;
425+ while tok = sIdent do begin
426+ n := 0;
427+ repeat
428+ if n > High(names) then Mark('more than ' + IntStr(High(names) + 1) + ' names in one declaration');
429+ IdentDef(names[n], exps[n], poss[n]);
430+ inc(n);
431+ if tok <> sComma then break;
432+ Next;
433+ until false;
434+ Expect(sColon);
435+ ft := ParseType;
436+ if t^.packd then a := 1 else a := ft^.align;
437+ for i := 0 to n - 1 do begin
438+ off := AlignUp(off, a);
439+ f := NewObj(oField, names[i], ft);
440+ f^.exported := exps[i];
441+ f^.pos := poss[i];
442+ f^.val := off;
443+ Insert(f, t^.scope);
444+ if last = nil then t^.fields := f else last^.next := f;
445+ last := f;
446+ off := off + ft^.size;
447+ end;
448+ if a > maxA then maxA := a;
449+ Expect(sSemicolon);
450+ end;
451+ Expect(sEnd);
452+ t^.align := maxA;
453+ t^.size := AlignUp(off, maxA);
454+ RecordType := t;
455+end;
456+
457+function VariantType: PType;
458+var t, ft: PType; c, lastC, f, lastF: PObj; tag, off, maxSize: int64; n: longint;
459+begin
460+ Expect(sVariant);
461+ t := NewType(fVariant, 8, 8);
462+ tag := 0; maxSize := 8; lastC := nil;
463+ while tok = sIdent do begin
464+ c := NewObj(oCase, id, t);
465+ c^.val := tag;
466+ c^.exported := declExported;
467+ Declare(c);
468+ if lastC = nil then t^.fields := c else lastC^.next := c;
469+ lastC := c;
470+ Next;
471+ off := 8;
472+ if tok = sLparen then begin
473+ Next;
474+ lastF := nil;
475+ repeat
476+ n := 0;
477+ repeat
478+ if tok <> sIdent then Expected('a name');
479+ f := NewObj(oField, id, nil);
480+ f^.exported := true;
481+ if lastF = nil then c^.fields := f else lastF^.next := f;
482+ lastF := f;
483+ inc(n);
484+ Next;
485+ if tok <> sComma then break;
486+ Next;
487+ until false;
488+ Expect(sColon);
489+ ft := ParseType;
490+ f := c^.fields;
491+ while f^.typ <> nil do f := f^.next;
492+ while f <> nil do begin
493+ f^.typ := ft;
494+ off := AlignUp(off, ft^.align);
495+ f^.val := off;
496+ off := off + ft^.size;
497+ f := f^.next;
498+ end;
499+ if ft^.align > t^.align then t^.align := ft^.align;
500+ if tok <> sSemicolon then break;
501+ Next;
502+ until false;
503+ Expect(sRparen);
504+ end;
505+ if off > maxSize then maxSize := off;
506+ Expect(sSemicolon);
507+ inc(tag);
508+ end;
509+ Expect(sEnd);
510+ t^.len := tag;
511+ t^.size := AlignUp(maxSize, t^.align);
512+ VariantType := t;
513+end;
514+
515+{ Several results: a record of them, laid out as C would, and
516+ returned in rax and rdx if they are two words (InTwoRegs), or else
517+ through a hidden pointer. }
518+function Results: PType;
519+var t, ft: PType; f, last: PObj; off: int64;
520+begin
521+ Next;
522+ t := NewType(fRecord, 0, 1);
523+ t^.tuple := true;
524+ off := 0; last := nil;
525+ repeat
526+ ft := ParseType;
527+ off := AlignUp(off, ft^.align);
528+ f := NewObj(oField, -1, ft);
529+ f^.val := off;
530+ off := off + ft^.size;
531+ if ft^.align > t^.align then t^.align := ft^.align;
532+ if last = nil then t^.fields := f else last^.next := f;
533+ last := f;
534+ inc(t^.len);
535+ if tok <> sComma then break;
536+ Next;
537+ until false;
538+ Expect(sRparen);
539+ t^.size := AlignUp(off, t^.align);
540+ if t^.len = 1 then Results := t^.fields^.typ else Results := t;
541+end;
542+
543+function Signature: PType;
544+var
545+ t, pt: PType; p, first, last: PObj; isVar: boolean; n: longint;
546+begin
547+ t := NewType(fProc, 8, 8);
548+ last := nil; n := 0;
549+ if tok = sLparen then begin
550+ Next;
551+ if tok <> sRparen then
552+ repeat
553+ if tok = sEllipsis then begin
554+ if not inExtern then Mark('... is only for extern procedures');
555+ Next; t^.variadic := true; break
556+ end;
557+ isVar := tok = sVar;
558+ if isVar then Next;
559+ first := nil;
560+ repeat
561+ if tok <> sIdent then Expected('a name');
562+ p := NewObj(oVar, id, nil);
563+ p^.isVar := isVar;
564+ p^.lev := 1;
565+ if last = nil then t^.fields := p else last^.next := p;
566+ last := p;
567+ if first = nil then first := p;
568+ inc(n);
569+ Next;
570+ if tok <> sComma then break;
571+ Next;
572+ until false;
573+ Expect(sColon);
574+ pt := ParseType;
575+ while first <> nil do begin first^.typ := pt; first := first^.next end;
576+ if tok <> sSemicolon then break;
577+ Next;
578+ until false;
579+ Expect(sRparen);
580+ end;
581+ t^.len := n;
582+ if tok = sColon then begin
583+ Next;
584+ if tok = sLparen then t^.base := Results else t^.base := ParseType;
585+ end;
586+ Signature := t;
587+end;
588+
589+function EnumType: PType;
590+var t: PType; o, last: PObj; start: TPos;
591+begin
592+ start := TokPos;
593+ t := NewType(fEnum, 1, 1);
594+ last := nil;
595+ repeat
596+ Next;
597+ if tok <> sIdent then Expected('a name');
598+ o := NewObj(oConst, id, t);
599+ o^.val := t^.len;
600+ o^.exported := declExported;
601+ o^.used := true; { an enumeration's names are its type's, warned of with it }
602+ Declare(o);
603+ if last = nil then t^.fields := o else last^.next := o;
604+ last := o;
605+ inc(t^.len);
606+ Next;
607+ until tok <> sComma;
608+ Expect(sRparen);
609+ if t^.len > 256 then MarkAt(SpanFrom(start), 'an enumeration has at most 256 names');
610+ EnumType := t;
611+end;
612+
613+function SetOf(e: PType; const at: TPos): PType;
614+var t: PType;
615+begin
616+ if (e^.form <> fEnum) or (e^.len > 64) then MarkAt(at, 'a set needs an enumeration of at most 64 names, found ' + TypeName(e));
617+ t := NewType(fSet, 8, 8);
618+ if e^.len <= 8 then t^.size := 1
619+ else if e^.len <= 16 then t^.size := 2
620+ else if e^.len <= 32 then t^.size := 4;
621+ t^.align := t^.size;
622+ t^.base := e;
623+ t^.len := e^.len;
624+ SetOf := t;
625+end;
626+
627+function ParseType: PType;
628+var t: PType; o: PObj; n: int64; vol: boolean; start: TPos;
629+begin
630+ start := TokPos;
631+ case tok of
632+ sIdent: begin
633+ o := QualIdent;
634+ if o^.cls <> oType then MarkAt(SpanFrom(start), NameOf(o^.name) + ' isn''t a type');
635+ t := o^.typ;
636+ end;
637+ sLbrak: begin
638+ Next;
639+ if tok = sRbrak then begin
640+ Next;
641+ t := NewType(fSlice, 16, 8);
642+ t^.base := ParseType();
643+ end else begin
644+ start := TokPos;
645+ n := ConstExpr;
646+ if (n <= 0) or (n > (int64(1) shl 40)) then MarkAt(SpanFrom(start), 'an array''s length is from 1 to 2^40, found ' + IntStr(n));
647+ Expect(sRbrak);
648+ t := NewType(fArray, 0, 1);
649+ t^.len := n;
650+ t^.base := ParseType();
651+ t^.size := n * t^.base^.size;
652+ t^.align := t^.base^.align;
653+ end;
654+ end;
655+ sArrow: begin
656+ Next;
657+ vol := tok = sVolatile;
658+ if vol then Next;
659+ if inTypes and (tok = sIdent) and (Lookup(id) = nil) then begin
660+ { a type declared later in this section }
661+ t := NewPtr(nil, vol);
662+ t^.fwd := id;
663+ if numFwd > High(fwdTypes) then Mark('more than ' + IntStr(High(fwdTypes) + 1) + ' pointers to types not yet declared');
664+ fwdTypes[numFwd] := t;
665+ fwdPos[numFwd] := TokPos;
666+ inc(numFwd);
667+ Next;
668+ end else
669+ t := NewPtr(ParseType(), vol);
670+ end;
671+ sPacked, sRecord: t := RecordType;
672+ sVariant: t := VariantType;
673+ sProc: begin Next; t := Signature end;
674+ sLparen: t := EnumType;
675+ sSet: begin
676+ Next;
677+ Expect(sOf);
678+ start := TokPos;
679+ t := SetOf(ParseType(), start);
680+ end;
681+ else Expected('a type');
682+ end;
683+ ParseType := t;
684+end;
685+
686+{ Expressions }
687+
688+procedure Call(var x: TItem);
689+var c: TCall; a: TItem; want: PType;
690+begin
691+ BeginCall(c, x);
692+ Expect(sLparen);
693+ if tok <> sRparen then
694+ repeat
695+ if c.param <> nil then want := c.param^.typ else want := nil;
696+ Expression(a, want);
697+ PassArg(c, a);
698+ if tok <> sComma then break;
699+ Next;
700+ until false;
701+ Expect(sRparen);
702+ EndCall(c, x);
703+end;
704+
705+procedure Atomic(var x: TItem; which: longint);
706+var p, a: TItem; t: PType; i, n: longint;
707+begin
708+ Expression(p, nil);
709+ if p.typ^.form <> fPtr then MarkAt(p.pos, 'expected a pointer, found ' + What(p));
710+ t := p.typ^.base;
711+ if not (IsWord(t) or ((t^.form = fPtr) and (which <> bXadd))) then
712+ if which = bXadd then MarkAt(p.pos, 'expected a pointer to an INT or a UINT, found ' + TypeName(p.typ))
713+ else MarkAt(p.pos, 'expected a pointer to an INT, a UINT or a pointer, found ' + TypeName(p.typ));
714+ Value(p);
715+ if which = bCas then n := 2 else n := 1;
716+ for i := 1 to n do begin
717+ Expect(sComma);
718+ Expression(a, t);
719+ Coerce(a, t);
720+ Value(a);
721+ end;
722+ gen.Atomic(which);
723+ MakeConst(x, t, 0);
724+ if which = bCas then x.typ := tBool;
725+ x.mode := mStack;
726+end;
727+
728+{ NEW(p, a): p := a^.alloc(a, SIZE(T), alignment), zeroed if not nil.
729+ a is a ^Mem.Allocator, the one interface the compiler knows. }
730+procedure New_(var x: TItem);
731+var y, z: TItem; t: PType; f: PObj; s: int64; c: TCall;
732+begin
733+ Expression(x, nil);
734+ NotReadOnly(x);
735+ if (x.mode <> mVar) or not x.isVar or (x.typ^.form <> fPtr) then MarkAt(x.pos, 'NEW needs a pointer variable');
736+ t := x.typ^.base;
737+ Expect(sComma);
738+ Expression(y, nil);
739+ if (y.typ^.form <> fPtr) or (y.typ^.base^.obj = nil) or (y.typ^.base^.obj^.module = nil)
740+ or (NameOf(y.typ^.base^.obj^.name) <> 'Allocator')
741+ or (NameOf(y.typ^.base^.obj^.module^.name) <> 'Mem') then MarkAt(y.pos, 'NEW needs a ^Mem.Allocator, found ' + What(y));
742+ f := Find(y.typ^.base^.scope, Name('alloc'));
743+ s := ToSlot(y);
744+ PushVar(FrameAdr(s), 8, false, kWord);
745+ MakeConst(z, f^.typ, 0);
746+ z.mode := mVar; z.base := bStack; z.off := f^.val;
747+ BeginCall(c, z);
748+ PushVar(FrameAdr(s), 8, false, kWord);
749+ MakeConst(z, y.typ, 0);
750+ z.mode := mStack;
751+ PassArg(c, z);
752+ MakeConst(z, tInt, t^.size);
753+ PassArg(c, z);
754+ MakeConst(z, tInt, t^.align);
755+ PassArg(c, z);
756+ EndCall(c, z);
757+ ZeroNew(t^.size);
758+ z.typ := x.typ;
759+ Assign(x, z);
760+ MakeConst(x, tNone, 0);
761+ x.mode := mNone;
762+end;
763+
764+function IncOrDec(which: longint): shortstring;
765+begin
766+ if which = bDec then IncOrDec := 'DEC' else IncOrDec := 'INC';
767+end;
768+
769+procedure Builtin(var x: TItem);
770+var which, n: longint; y: TItem; t: PType;
771+begin
772+ which := x.obj^.val;
773+ if which in [bFence, bArgc, bArgv] then begin
774+ if tok = sLparen then begin Next; Expect(sRparen) end;
775+ MakeConst(x, tNone, 0);
776+ case which of
777+ bFence: begin Fence; x.mode := mNone end;
778+ bArgc: begin PushVar(GlobalAdr(argcChunk), 8, false, kWord); x.typ := tInt; x.mode := mStack end;
779+ bArgv: begin PushVar(GlobalAdr(argvChunk), 8, false, kWord); x.typ := tArgv; x.mode := mStack end;
780+ end;
781+ exit;
782+ end;
783+ Expect(sLparen);
784+ case which of
785+ bSize: begin
786+ t := ParseType;
787+ MakeConst(x, tConst, t^.size);
788+ end;
789+ bAdr: begin
790+ Expression(y, nil);
791+ NotReadOnly(y);
792+ if (y.mode <> mVar) or not y.isVar then MarkAt(y.pos, 'ADR needs a variable');
793+ if y.odd then MarkAt(y.pos, 'a field of a packed record has no address');
794+ t := NewPtr(y.typ, y.vol);
795+ Address(y);
796+ MakeConst(x, t, 0);
797+ x.mode := mStack;
798+ end;
799+ bLen: begin
800+ Expression(y, nil);
801+ if y.mode = mStr then MakeConst(x, tConst, y.val)
802+ else if y.typ^.form = fArray then begin
803+ Discard(y);
804+ MakeConst(x, tConst, y.typ^.len)
805+ end else if (y.typ^.form = fSlice) and (y.mode = mVar) then begin
806+ { its length, the word after its pointer }
807+ y.off := y.off + 8;
808+ y.typ := tInt;
809+ Value(y);
810+ x := y;
811+ end else MarkAt(y.pos, 'LEN needs an array or a slice, found ' + What(y));
812+ end;
813+ bSyscall: begin
814+ n := 0;
815+ repeat
816+ if n > 0 then Next;
817+ Expression(y, nil);
818+ if not (IsScalar(y.typ) and (y.typ^.form <> fReal)) then MarkAt(y.pos, 'expected an integer or a pointer, found ' + What(y));
819+ if y.typ^.form = fConst then Coerce(y, tInt);
820+ Value(y);
821+ inc(n);
822+ until (tok <> sComma) or (n = 7);
823+ SysCall(n);
824+ MakeConst(x, tInt, 0);
825+ x.mode := mStack;
826+ end;
827+ bCas, bXchg, bXadd: Atomic(x, which);
828+ bMsg: begin Expression(x, tError); Msg(x) end;
829+ bInc, bDec: begin
830+ Expression(x, nil);
831+ NotReadOnly(x);
832+ if (x.mode <> mVar) or not x.isVar or (x.typ^.form <> fInt) then
833+ MarkAt(x.pos, IncOrDec(which) + ' needs an integer variable');
834+ if x.base <> bReg then Address(x);
835+ if tok = sComma then begin
836+ Next;
837+ Expression(y, x.typ);
838+ end else MakeConst(y, x.typ, 1);
839+ IncDec(x, y, which = bDec);
840+ MakeConst(x, tNone, 0);
841+ x.mode := mNone;
842+ end;
843+ bNew: New_(x);
844+ bCopy: begin
845+ Expression(x, nil);
846+ CopyDest(x);
847+ Expect(sComma);
848+ Expression(y, nil);
849+ CopyFrom(x, y);
850+ MakeConst(x, tNone, 0);
851+ x.mode := mNone;
852+ end;
853+ end;
854+ Expect(sRparen);
855+end;
856+
857+procedure ConstructCase(var x: TItem; c: PObj; const at: TPos);
858+var f: PObj; a: TItem;
859+begin
860+ Construct(x, c);
861+ f := c^.fields;
862+ if tok = sLparen then begin
863+ Next;
864+ while f <> nil do begin
865+ Expression(a, f^.typ);
866+ SetField(x, f, a);
867+ f := f^.next;
868+ if f <> nil then Expect(sComma);
869+ end;
870+ Expect(sRparen);
871+ end else if f <> nil then MarkAt(at, NameOf(c^.name) + ' needs its fields');
872+end;
873+
874+{ x, before ".", has no fields; tok is what follows. Other languages
875+ write p.f through a pointer and s.len for a length. }
876+procedure FieldOfWhat(const x: TItem);
877+var msg, f: shortstring;
878+begin
879+ msg := 'expected a record, found ' + What(x);
880+ if tok = sIdent then f := NameOf(id) else f := '';
881+ if (x.typ^.form = fPtr) and (x.typ^.base^.form = fRecord) then
882+ MarkHelp(x.pos, msg, 'through a pointer, write ' + Source(x.pos) + '^.' + f)
883+ else if (x.typ^.form in [fArray, fSlice]) and ((f = 'len') or (f = 'length') or (f = 'size') or (f = 'count')) then
884+ MarkHelp(x.pos, msg, 'its length is LEN(' + Source(x.pos) + ')');
885+ MarkAt(x.pos, msg);
886+end;
887+
888+{ A designator, with any selectors and calls after it. called tells
889+ whether the last thing done was a call. }
890+procedure Designator(var x: TItem; var called: boolean);
891+var o, f: PObj; y, z: TItem; t: PType; start: TPos;
892+begin
893+ start := TokPos;
894+ o := QualIdent;
895+ called := false;
896+ if o^.cls = oModule then MarkAt(SpanFrom(start), NameOf(o^.name) + ' is a module, not a value');
897+ MakeItem(x, o);
898+ if x.mode = mBuiltin then begin
899+ Builtin(x);
900+ called := true;
901+ end else if x.mode = mCase then begin
902+ ConstructCase(x, o, SpanFrom(start));
903+ end;
904+ repeat
905+ x.pos := SpanFrom(start);
906+ case tok of
907+ sPeriod: begin
908+ Next;
909+ if (x.mode <> mVar) or (x.typ^.form <> fRecord) then FieldOfWhat(x);
910+ if tok <> sIdent then Expected('a field');
911+ f := FieldOf(x.typ);
912+ Next;
913+ Field(x, f);
914+ called := false;
915+ end;
916+ sArrow: begin Next; Deref(x); called := false end;
917+ sLbrak: begin
918+ Next;
919+ IndexPrep(x);
920+ Expression(y, nil);
921+ if tok = sUpto then begin
922+ Next;
923+ SliceLo(y);
924+ Expression(z, nil);
925+ Slice(x, y, z);
926+ end else Index(x, y);
927+ Expect(sRbrak);
928+ called := false;
929+ end;
930+ sLparen: begin
931+ if x.mode = mType then begin
932+ t := x.typ;
933+ Next;
934+ Expression(x, nil);
935+ Expect(sRparen);
936+ Convert(x, t);
937+ end else begin
938+ if x.mode = mProc then lastCalled := x.obj else lastCalled := nil;
939+ Call(x);
940+ called := true;
941+ end;
942+ end;
943+ else break;
944+ end;
945+ until false;
946+ x.pos := SpanFrom(start);
947+ NilTest(x);
948+end;
949+
950+procedure ArrayLiteral(var x: TItem; want: PType);
951+var
952+ et, at: PType; e: TItem; slots: array[0..1023] of int64; n, i: longint;
953+ off, es: int64; start: TPos;
954+begin
955+ start := TokPos;
956+ if (want = nil) or not (want^.form in [fArray, fSlice]) then
957+ Mark('an array literal needs a known array or slice type');
958+ et := want^.base;
959+ es := et^.size;
960+ Next;
961+ n := 0;
962+ if tok <> sRbrak then
963+ repeat
964+ if n > High(slots) then Mark('more than ' + IntStr(High(slots) + 1) + ' elements');
965+ Expression(e, et);
966+ Coerce(e, et);
967+ if IsScalar(et) then slots[n] := ToSlot(e)
968+ else begin
969+ if e.isVar or e.vol or (e.mode <> mVar) or (e.base <> bFrame) then CopyToTemp(e);
970+ slots[n] := e.off;
971+ end;
972+ inc(n);
973+ if tok <> sComma then break;
974+ Next;
975+ until false;
976+ Expect(sRbrak);
977+ if (want^.form = fArray) and (n <> want^.len) then MarkAt(SpanFrom(start), 'expected ' + IntStr(want^.len) + ' elements, found ' + IntStr(n));
978+ if n = 0 then begin
979+ PushConst(kWord, 0);
980+ SliceOf(x, want, 0);
981+ exit;
982+ end;
983+ if want^.form = fArray then begin
984+ at := want;
985+ off := AllocTemp(at^.size, at^.align);
986+ end else begin
987+ at := NewType(fArray, n * es, et^.align);
988+ at^.len := n;
989+ at^.base := et;
990+ off := AllocPerm(at^.size, at^.align); { lives as long as the call }
991+ end;
992+ for i := 0 to n - 1 do
993+ if IsScalar(et) then begin
994+ PushVar(FrameAdr(slots[i]), 8, false, KindOf(et));
995+ PopVar(FrameAdr(off + i * es), ScalarSize(et));
996+ end else begin
997+ PushAdr(FrameAdr(slots[i]));
998+ CopyTo(FrameAdr(off + i * es), es);
999+ end;
1000+ TempItem(x, at, off);
1001+end;
1002+
1003+{ A record literal: a zeroed temporary, with the fields named filled in. }
1004+procedure RecordLiteral(var x: TItem; t: PType);
1005+var f: PObj; a: TItem; seen: array[0..63] of longint; n, i: longint;
1006+begin
1007+ Next;
1008+ ZeroTemp(x, t);
1009+ FillChar(seen, SizeOf(seen), 0);
1010+ n := 0;
1011+ if tok <> sRbrace then
1012+ repeat
1013+ if tok <> sIdent then Expected('a field');
1014+ f := FieldOf(t);
1015+ for i := 0 to n - 1 do if seen[i] = id then Mark('field ' + NameOf(id) + ' is given twice');
1016+ if n <= High(seen) then begin seen[n] := id; inc(n) end;
1017+ Next;
1018+ Expect(sColon);
1019+ Expression(a, f^.typ);
1020+ SetField(x, f, a);
1021+ if tok <> sComma then break;
1022+ Next;
1023+ until false;
1024+ Expect(sRbrace);
1025+end;
1026+
1027+{ A set literal: the bits of the constant names, or'd at run time with
1028+ those of the others. }
1029+procedure SetLiteral(var x: TItem; t: PType);
1030+var e: TItem; bits, slot: int64; start: TPos; s: shortstring;
1031+begin
1032+ start := TokPos;
1033+ Next;
1034+ if (t <> nil) and (t^.form <> fSet) then MarkAt(SpanFrom(start), 'expected a set type, found ' + TypeName(t));
1035+ bits := 0;
1036+ slot := 0;
1037+ if tok <> sRbrace then
1038+ repeat
1039+ if t = nil then Expression(e, nil) else Expression(e, t^.base);
1040+ if t = nil then begin
1041+ if e.typ^.form <> fEnum then MarkAt(e.pos, 'a set holds names of an enumeration, found ' + What(e));
1042+ t := SetOf(e.typ, e.pos);
1043+ end;
1044+ if not Same(e.typ, t^.base) then begin
1045+ if e.obj <> nil then s := NameOf(e.obj^.name) else s := What(e);
1046+ MarkAt(e.pos, s + ' isn''t a name of ' + TypeName(t^.base));
1047+ end;
1048+ if e.mode = mConst then bits := bits or (int64(1) shl e.val)
1049+ else begin
1050+ if slot = 0 then begin
1051+ slot := AllocTemp(8, 8);
1052+ PushConst(kWord, 0);
1053+ PopVar(FrameAdr(slot), 8);
1054+ end;
1055+ Value(e);
1056+ PushConst(kWord, 1);
1057+ Swap;
1058+ Op(sShl, kWord, 8, false);
1059+ PushVar(FrameAdr(slot), 8, false, kWord);
1060+ Op(sBar, kWord, 8, false);
1061+ PopVar(FrameAdr(slot), 8);
1062+ end;
1063+ if tok <> sComma then break;
1064+ Next;
1065+ until false;
1066+ Expect(sRbrace);
1067+ if t = nil then MarkAt(SpanFrom(start), '{} needs a known set type');
1068+ MakeConst(x, t, bits);
1069+ if slot <> 0 then begin
1070+ PushVar(FrameAdr(slot), 8, false, kWord);
1071+ PushConst(kWord, bits);
1072+ Op(sBar, kWord, 8, false);
1073+ x.mode := mStack;
1074+ end;
1075+end;
1076+
1077+procedure RunDefers(base: longint); forward;
1078+
1079+{ The type of the last result of t, the results of a procedure: t if
1080+ it has one, else the last of its several. }
1081+function LastResult(t: PType): PType;
1082+var f: PObj;
1083+begin
1084+ if not t^.tuple then exit(t);
1085+ f := t^.fields;
1086+ while f^.next <> nil do f := f^.next;
1087+ LastResult := f^.typ;
1088+end;
1089+
1090+{ The results of the tuple t but the last: the same fields, one fewer }
1091+function WithoutLast(t: PType): PType;
1092+var r: PType;
1093+begin
1094+ r := NewType(fRecord, t^.size, t^.align);
1095+ r^.tuple := true;
1096+ r^.fields := t^.fields;
1097+ r^.len := t^.len - 1;
1098+ WithoutLast := r;
1099+end;
1100+
1101+{ try c (the report, 7.8): the call c, then the error it returned, its
1102+ last result: if that isn't nil, the procedure returns it, and a zero
1103+ for each of its other results, after running the deferred statements
1104+ in force. x is left c's other results: none (mNone), one (a value) or
1105+ several (a tuple, for a multiple assignment). The error is kept in a
1106+ slot of the frame, and tested there; the code for it, out of line,
1107+ is made with the stack of values as it stands, and leaves it so,
1108+ since what follows is the code for an error that is nil. }
1109+procedure TryCall(var x: TItem);
1110+var
1111+ called: boolean; c: TCall; start, at: TPos; res: PType; last: PObj; slot: int64; ok: longint;
1112+begin
1113+ start := TokPos;
1114+ Next;
1115+ if deferring then MarkAt(SpanFrom(start), 'try can''t leave a deferred statement');
1116+ if curResult = nil then
1117+ MarkAt(SpanFrom(start), 'try needs a procedure that ends in an ERROR result, and this returns nothing')
1118+ else if LastResult(curResult) <> tError then
1119+ MarkAt(SpanFrom(start), 'try needs a procedure that ends in an ERROR result, and this returns ' + TypeName(curResult));
1120+ Designator(x, called);
1121+ if not called and ((x.mode = mProc) or ((x.mode in [mVar, mStack]) and (x.typ^.form = fProc))) then begin
1122+ { a procedure without parameters, written without parentheses }
1123+ at := x.pos;
1124+ BeginCall(c, x);
1125+ EndCall(c, x);
1126+ x.pos := at;
1127+ called := true;
1128+ end;
1129+ if not called then MarkAt(x.pos, 'try needs a call, found ' + What(x));
1130+ if x.mode = mNone then
1131+ MarkAt(x.pos, 'try needs a call that returns an ERROR last, and this returns nothing');
1132+ if LastResult(x.typ) <> tError then
1133+ MarkAt(x.pos, 'try needs a call that returns an ERROR last, and this returns ' + TypeName(x.typ));
1134+ res := x.typ;
1135+ if x.mode = mStack then begin
1136+ { an ERROR alone }
1137+ slot := AllocTemp(8, 8);
1138+ PopVar(FrameAdr(slot), 8);
1139+ x.mode := mNone; x.typ := tNone;
1140+ end else if x.mode = mWords then begin
1141+ { two words, the error on top }
1142+ slot := AllocTemp(8, 8);
1143+ PopVar(FrameAdr(slot), 8);
1144+ x.mode := mStack; x.typ := res^.fields^.typ;
1145+ end else begin
1146+ { several, in a temporary: the error is where it is }
1147+ last := res^.fields;
1148+ while last^.next <> nil do last := last^.next;
1149+ slot := x.off + last^.val;
1150+ if res^.len = 2 then Field(x, res^.fields) else x.typ := WithoutLast(res);
1151+ end;
1152+ ok := NoLabel;
1153+ PushVar(FrameAdr(slot), 8, false, kWord);
1154+ JumpIf(ok, false);
1155+ if numDefers > 0 then TryAlign;
1156+ RunDefers(0);
1157+ TryReturn(slot);
1158+ Fix(ok);
1159+ x.pos := SpanFrom(start);
1160+end;
1161+
1162+procedure Factor(var x: TItem; want: PType);
1163+var called, vol, several: boolean; t: PType; start: TPos; s: shortstring;
1164+begin
1165+ several := passOn;
1166+ passOn := false;
1167+ start := TokPos;
1168+ case tok of
1169+ sInt, sChar: begin
1170+ { only a hex number can be above high(I64), and it is a U64 }
1171+ if ival < 0 then MakeConst(x, tU64, ival) else MakeConst(x, tConst, ival);
1172+ Next;
1173+ end;
1174+ sReal: begin MakeReal(x, rval); UsesReals(TokPos); Next end;
1175+ sString: begin MakeStr(x); Next end;
1176+ sIdent: begin
1177+ Designator(x, called);
1178+ if x.mode = mNone then begin
1179+ if lastCalled <> nil then s := NameOf(lastCalled^.name) else s := 'this procedure';
1180+ MarkAt(x.pos, s + ' returns nothing');
1181+ end;
1182+ if x.typ^.tuple and not several then begin
1183+ if lastCalled <> nil then s := NameOf(lastCalled^.name) else s := 'this procedure';
1184+ MarkHelp(x.pos, s + ' returns several results', 'they go to variables: a, b := ' + s + '(...)');
1185+ if x.mode = mWords then CopyToTemp(x);
1186+ end;
1187+ end;
1188+ sLparen: begin Next; Expression(x, want); Expect(sRparen) end;
1189+ sTry: begin
1190+ TryCall(x);
1191+ if x.mode = mNone then MarkAt(x.pos, 'this try has no value');
1192+ if x.typ^.tuple then
1193+ MarkHelp(x.pos, 'this try has several values', 'they go to variables: a, b := try f(...)');
1194+ end;
1195+ sNot: begin Next; Factor(x, nil); NotOp(x) end;
1196+ sTilde: begin Next; Factor(x, nil); Complement(x) end;
1197+ sLbrak: ArrayLiteral(x, want);
1198+ sLbrace: if (want <> nil) and (want^.form = fRecord) then RecordLiteral(x, want)
1199+ else SetLiteral(x, want);
1200+ sArrow: begin
1201+ Next;
1202+ vol := tok = sVolatile;
1203+ if vol then Next;
1204+ t := NewPtr(ParseType, vol);
1205+ Expect(sLparen);
1206+ Expression(x, nil);
1207+ Expect(sRparen);
1208+ Convert(x, t);
1209+ { a conversion is a factor, not a designator: nothing selects from it }
1210+ if tok = sArrow then
1211+ MarkHelp(TokPos, 'a conversion can''t be dereferenced', 'convert into a pointer variable, then dereference that');
1212+ end;
1213+ else Expected('an expression');
1214+ end;
1215+ x.pos := SpanFrom(start);
1216+end;
1217+
1218+procedure Term(var x: TItem; want: PType);
1219+var op: TSym; y: TItem; L: longint; start: TPos;
1220+begin
1221+ start := TokPos;
1222+ Factor(x, want);
1223+ while tok in [sTimes, sSlash, sDiv, sMod, sAmp, sShl, sShr] do begin
1224+ op := tok;
1225+ Next;
1226+ Op1(op, x, L);
1227+ Factor(y, nil);
1228+ Op2(op, x, y, L);
1229+ x.pos := SpanFrom(start);
1230+ end;
1231+end;
1232+
1233+procedure SimpleExpr(var x: TItem; want: PType);
1234+var op: TSym; y: TItem; L: longint; start: TPos;
1235+begin
1236+ start := TokPos;
1237+ if tok = sMinus then begin
1238+ Next;
1239+ Term(x, nil);
1240+ x.pos := SpanFrom(start);
1241+ Neg(x);
1242+ end else Term(x, want);
1243+ while tok in [sPlus, sMinus, sBar, sXor] do begin
1244+ op := tok;
1245+ Next;
1246+ Op1(op, x, L);
1247+ Term(y, nil);
1248+ Op2(op, x, y, L);
1249+ x.pos := SpanFrom(start);
1250+ end;
1251+end;
1252+
1253+procedure Relation(var x: TItem; want: PType);
1254+var op: TSym; y: TItem; L: longint;
1255+begin
1256+ SimpleExpr(x, want);
1257+ if tok in [sEql, sNeq, sLss, sLeq, sGtr, sGeq, sIn] then begin
1258+ op := tok;
1259+ Next;
1260+ Op1(op, x, L);
1261+ if op = sIn then SimpleExpr(y, nil) else SimpleExpr(y, x.typ);
1262+ Op2(op, x, y, L);
1263+ x.pos := Join(x.pos, y.pos);
1264+ end;
1265+end;
1266+
1267+{ and binds tighter than or, and both below the relations }
1268+procedure Conjunct(var x: TItem; want: PType);
1269+var y: TItem; L: longint; start: TPos;
1270+begin
1271+ start := TokPos;
1272+ Relation(x, want);
1273+ while tok = sAnd do begin
1274+ Next;
1275+ Op1(sAnd, x, L);
1276+ Relation(y, nil);
1277+ Op2(sAnd, x, y, L);
1278+ x.pos := SpanFrom(start);
1279+ end;
1280+end;
1281+
1282+procedure Expression(var x: TItem; want: PType);
1283+var y: TItem; L: longint; start: TPos;
1284+begin
1285+ start := TokPos;
1286+ Conjunct(x, want);
1287+ while tok = sOr do begin
1288+ Next;
1289+ Op1(sOr, x, L);
1290+ Conjunct(y, nil);
1291+ Op2(sOr, x, y, L);
1292+ x.pos := SpanFrom(start);
1293+ end;
1294+end;
1295+
1296+{ Statements }
1297+
1298+procedure Loop(var lp: TLoop; var old: PLoop);
1299+begin
1300+ lp.brk := NoLabel;
1301+ lp.base := numDefers;
1302+ old := curLoop;
1303+ curLoop := @lp;
1304+end;
1305+
1306+{ Runs the deferred statements in force above base, newest first. }
1307+procedure RunDefers(base: longint);
1308+var i: longint;
1309+begin
1310+ for i := numDefers - 1 downto base do RunDefer(defers[i]);
1311+end;
1312+
1313+{ Whether what follows "then" is a lone "break;", with no deferred
1314+ statement to run on the way out of the loop: the break must be the
1315+ branch's last statement, so ";" and then end, elsif or else follow. }
1316+function LoneBreak: boolean;
1317+var st: TScanState;
1318+begin
1319+ LoneBreak := false;
1320+ if (tok <> sBreak) or (curLoop = nil) or (numDefers <> curLoop^.base) then exit;
1321+ SaveScan(st);
1322+ Next;
1323+ if tok = sSemicolon then begin
1324+ Next;
1325+ LoneBreak := tok in [sEnd, sElsif, sElse];
1326+ end;
1327+ RestoreScan(st);
1328+end;
1329+
1330+{ The condition x of if or elsif, and the statements it guards, which
1331+ L skips when it is false. "if c then break; end" is one jump out of
1332+ the loop when c holds, not one past a jump out. }
1333+procedure ThenPart(var x: TItem; var L: longint);
1334+begin
1335+ Expect(sThen);
1336+ L := NoLabel; { stays so with a lone break: there is nothing to skip }
1337+ if LoneBreak then begin
1338+ NoteLine(CurLine, CurCol); { the jump gets the break's line }
1339+ CondJumpTrue(x, curLoop^.brk);
1340+ Next; Next; { skip "break" and ";" }
1341+ ends := true;
1342+ end else begin
1343+ CondJump(x, L);
1344+ Statements;
1345+ end;
1346+end;
1347+
1348+{ if, elsif and else: each condition's jump skips its branch to the
1349+ next; each branch that doesn't end jumps to the end. A branch that
1350+ ends, in return or break, needs no jump past the others, and all of
1351+ them ending is told to the caller in the global ends. }
1352+procedure IfStatement(const start: TPos; ind: longint);
1353+var x: TItem; L, endL: longint; all: boolean;
1354+begin
1355+ Next;
1356+ Expression(x, nil);
1357+ ThenPart(x, L);
1358+ all := ends;
1359+ endL := NoLabel;
1360+ while tok = sElsif do begin
1361+ if not ends then Jump(endL);
1362+ Fix(L);
1363+ Next;
1364+ Expression(x, nil);
1365+ ThenPart(x, L);
1366+ all := all and ends;
1367+ end;
1368+ if tok = sElse then begin
1369+ if not ends then Jump(endL);
1370+ Fix(L);
1371+ Next;
1372+ if tok = sIf then elseIf := true;
1373+ Statements;
1374+ all := all and ends;
1375+ end else begin
1376+ Fix(L);
1377+ all := false;
1378+ end;
1379+ CloseEnd(start, ind);
1380+ Fix(endL);
1381+ ends := all;
1382+end;
1383+
1384+{ while c do s end: the test comes after the body, and the loop jumps to
1385+ it first, so that a round takes one jump, back to the top if c holds:
1386+
1387+ jmp test rather than top: c, jump to out if false
1388+ top: s s
1389+ test: c, jump to top if true jmp top
1390+ out:
1391+
1392+ One pass reads c before s: so c is compiled where it is written, for
1393+ its messages, and its code taken back (Rewind); then read again, and
1394+ compiled, after s (SaveScan, RestoreScan). }
1395+procedure WhileStatement(const start: TPos; ind: longint);
1396+var x: TItem; top, L, test: longint; lp: TLoop; old: PLoop; cond, after: TScanState; m: TCodeMark;
1397+begin
1398+ Next;
1399+ SaveScan(cond);
1400+ MarkCode(m);
1401+ Expression(x, nil);
1402+ Discard(x);
1403+ Rewind(m);
1404+ Expect(sDo);
1405+ test := NoLabel;
1406+ Jump(test);
1407+ AlignLoop;
1408+ top := pc;
1409+ Loop(lp, old);
1410+ Statements;
1411+ curLoop := old;
1412+ SaveScan(after);
1413+ RestoreScan(cond);
1414+ Fix(test);
1415+ NoteLine(CurLine, CurCol);
1416+ Expression(x, nil);
1417+ ends := (x.mode = mConst) and (x.val <> 0) and (lp.brk = NoLabel); { while true }
1418+ if (x.mode = mConst) and (x.typ^.form = fBool) then begin
1419+ if x.val <> 0 then JumpBack(top);
1420+ end else begin
1421+ L := NoLabel;
1422+ CondJumpTrue(x, L);
1423+ FixTo(L, top);
1424+ end;
1425+ RestoreScan(after);
1426+ CloseEnd(start, ind);
1427+ Fix(lp.brk);
1428+end;
1429+
1430+procedure RepeatStatement;
1431+var x: TItem; top, L: longint; lp: TLoop; old: PLoop;
1432+begin
1433+ Next;
1434+ top := pc;
1435+ Loop(lp, old);
1436+ Statements;
1437+ curLoop := old;
1438+ Expect(sUntil);
1439+ Expression(x, nil);
1440+ ends := (x.mode = mConst) and (x.val = 0) and (lp.brk = NoLabel); { until false }
1441+ L := NoLabel;
1442+ CondJump(x, L);
1443+ FixTo(L, top);
1444+ Fix(lp.brk);
1445+end;
1446+
1447+{ for v := a to b by s do ... end, laid out as
1448+ v := a; the limit b, in a slot unless it is a constant
1449+ if v is past b then goto exit
1450+ goto body
1451+ top: v := v + s
1452+ body: the statements
1453+ the end of a round: goto top, or exit (ForNext)
1454+ exit:
1455+ so that a round of a loop by 1 takes one compare and one jump. }
1456+procedure ForStatement(const start: TPos; ind: longint);
1457+var
1458+ o: PObj; v, a, b, s: TItem; step: int64; top, body, bodyL, exitL: longint;
1459+ lp: TLoop; old: PLoop;
1460+begin
1461+ Next;
1462+ if tok <> sIdent then Expected('a name');
1463+ o := Lookup(id);
1464+ if o = nil then begin NotDeclared(TokPos, id); Fail end;
1465+ Named(o);
1466+ if (o^.cls <> oVar) or not (o^.typ^.form in [fInt, fEnum]) then
1467+ if o^.cls = oVar then
1468+ Mark('a for loop needs an integer or enumeration variable, found ' + TypeName(o^.typ))
1469+ else Mark(NameOf(id) + ' isn''t a variable');
1470+ Next;
1471+ Expect(sBecomes);
1472+ MakeItem(v, o);
1473+ Expression(a, o^.typ);
1474+ CoerceExact(a, o^.typ, '');
1475+ Assign(v, a);
1476+ Expect(sTo);
1477+ Expression(b, o^.typ);
1478+ CoerceExact(b, o^.typ, '');
1479+ { the limit, evaluated once: a constant as it is, else in a slot }
1480+ if b.mode <> mConst then TempItem(b, b.typ, ToSlot(b));
1481+ step := 1;
1482+ if tok = sBy then begin
1483+ Next;
1484+ Expression(s, nil);
1485+ step := ConstValue(s);
1486+ if step = 0 then MarkAt(s.pos, 'the step can''t be zero');
1487+ end;
1488+ Expect(sDo);
1489+ exitL := NoLabel;
1490+ if step > 0 then ForCmp(o, b, sGtr, exitL) else ForCmp(o, b, sLss, exitL);
1491+ bodyL := NoLabel;
1492+ Jump(bodyL);
1493+ AlignLoop;
1494+ top := pc;
1495+ ForStep(o, step);
1496+ Fix(bodyL);
1497+ body := pc;
1498+ Loop(lp, old);
1499+ Statements;
1500+ curLoop := old;
1501+ CloseEnd(start, ind);
1502+ ForNext(o, b, step, exitL, top, body);
1503+ Fix(exitL);
1504+ Fix(lp.brk);
1505+end;
1506+
1507+type
1508+ TLabels = record
1509+ lo, hi: array[0..1023] of int64; { the ranges of the labels so far }
1510+ at: array[0..1023] of longint; { where the arm of each starts }
1511+ n: longint;
1512+ end;
1513+
1514+{ a < b, for values of an integer type, unsigned or not }
1515+function Below(a, b: int64; unsign: boolean): boolean;
1516+begin
1517+ if unsign then Below := qword(a) < qword(b) else Below := a < b;
1518+end;
1519+
1520+{ An arm of a match on an integer of type t: its labels, each a
1521+ constant or a range, none overlapping another (report section 7.4),
1522+ then its statements. No code tests the labels here; Dispatch does,
1523+ after the last arm, for which each label notes where its arm starts. }
1524+procedure IntArm(t: PType; var ls: TLabels; var endL: longint);
1525+var lo, hi: TItem; first, i: longint; u: boolean; start: TPos;
1526+begin
1527+ u := not t^.signed;
1528+ first := ls.n;
1529+ repeat
1530+ start := TokPos;
1531+ Expression(lo, t);
1532+ Coerce(lo, t);
1533+ ConstValue(lo);
1534+ hi := lo;
1535+ if tok = sUpto then begin
1536+ Next;
1537+ Expression(hi, t);
1538+ Coerce(hi, t);
1539+ ConstValue(hi);
1540+ if Below(hi.val, lo.val, u) then MarkAt(SpanFrom(start), 'the range is empty');
1541+ end;
1542+ for i := 0 to ls.n - 1 do
1543+ if not Below(hi.val, ls.lo[i], u) and not Below(ls.hi[i], lo.val, u) then
1544+ if lo.val = hi.val then MarkAt(SpanFrom(start), Source(SpanFrom(start)) + ' is in another label too')
1545+ else MarkAt(SpanFrom(start), Source(SpanFrom(start)) + ' overlaps another label');
1546+ if ls.n > High(ls.lo) then MarkAt(SpanFrom(start), 'more than ' + IntStr(High(ls.lo) + 1) + ' labels in one match');
1547+ ls.lo[ls.n] := lo.val; ls.hi[ls.n] := hi.val;
1548+ inc(ls.n);
1549+ if tok <> sComma then break;
1550+ Next;
1551+ until false;
1552+ Expect(sColon);
1553+ for i := first to ls.n - 1 do ls.at[i] := pc;
1554+ Statements;
1555+ Jump(endL);
1556+end;
1557+
1558+const
1559+ MinTable = 4; { fewer labels are tested one by one }
1560+ TableDensity = 8; { a table has at most this many entries to a label }
1561+
1562+{ The code that picks the arm, after the last one, which the match's
1563+ start jumped to: label by label, as a chain of compares each to its
1564+ arm; or, for four or more labels not far apart, a jump table (JumpTable),
1565+ which takes the same few instructions for any of them. It is here and
1566+ not before the arms, since a table can only be made once every arm's
1567+ place is known; an arm is entered by a jump back to it. elseAt is where
1568+ the else arm starts, or NoLabel. }
1569+procedure Dispatch(t: PType; p: int64; const ls: TLabels; elseAt: longint; var endL: longint);
1570+var
1571+ lo, hi: int64; i, start: longint; v: int64; u: boolean; body: longint;
1572+ entry: array[0..1023] of longint;
1573+begin
1574+ u := (t^.form = fInt) and not t^.signed;
1575+ lo := 0; hi := 0;
1576+ if ls.n > 0 then begin
1577+ lo := ls.lo[0]; hi := ls.hi[0];
1578+ for i := 1 to ls.n - 1 do begin
1579+ if Below(ls.lo[i], lo, u) then lo := ls.lo[i];
1580+ if Below(hi, ls.hi[i], u) then hi := ls.hi[i];
1581+ end;
1582+ end;
1583+ if (ls.n >= MinTable) and (lo >= low(longint)) and (lo <= high(longint))
1584+ and (qword(hi - lo) < qword(TableDensity) * ls.n) and (hi - lo <= High(entry)) then begin
1585+ start := JumpTable(p, lo, hi - lo + 1, elseAt, endL);
1586+ for v := 0 to hi - lo do
1587+ if elseAt <> NoLabel then entry[v] := elseAt else entry[v] := start;
1588+ for i := 0 to ls.n - 1 do
1589+ for v := ls.lo[i] - lo to ls.hi[i] - lo do entry[v] := ls.at[i];
1590+ for v := 0 to hi - lo do TableEntry(start, entry[v]);
1591+ exit;
1592+ end;
1593+ for i := 0 to ls.n - 1 do begin
1594+ body := NoLabel;
1595+ MatchRange(p, ls.lo[i], ls.hi[i], body);
1596+ FixTo(body, ls.at[i]);
1597+ end;
1598+ if elseAt <> NoLabel then JumpBack(elseAt);
1599+end;
1600+
1601+procedure MatchStatement(const start: TPos; ind: longint);
1602+var
1603+ x: TItem; t: PType; c, f, o: PObj; p: int64; L, endL, n, first, disp, elseAt: longint;
1604+ seen: array[0..255] of boolean; hasElse, all, byValue: boolean; endAt: TPos; ls: TLabels;
1605+begin
1606+ Next;
1607+ Expression(x, nil);
1608+ if x.typ^.form = fConst then Coerce(x, tI64);
1609+ p := MatchBegin(x);
1610+ t := x.typ;
1611+ Expect(sOf);
1612+ FillChar(seen, SizeOf(seen), 0);
1613+ hasElse := false;
1614+ all := true;
1615+ endL := NoLabel;
1616+ ls.n := 0;
1617+ { an integer or an enumeration is matched by its value, and the arms
1618+ are picked by Dispatch, after them; a variant by its tag, arm by arm }
1619+ byValue := t^.form in [fInt, fEnum];
1620+ disp := NoLabel;
1621+ elseAt := NoLabel;
1622+ if byValue then Jump(disp);
1623+ while tok = sBar do begin
1624+ Next;
1625+ if hasElse then Mark('else must be the last arm');
1626+ if tok = sElse then begin
1627+ Next;
1628+ Expect(sColon);
1629+ elseAt := pc;
1630+ Statements;
1631+ if byValue then Jump(endL);
1632+ hasElse := true;
1633+ end else if t^.form = fInt then
1634+ IntArm(t, ls, endL)
1635+ else begin
1636+ first := ls.n;
1637+ L := NoLabel;
1638+ repeat
1639+ if tok <> sIdent then Expected('a case');
1640+ c := t^.fields;
1641+ while (c <> nil) and (c^.name <> id) do c := c^.next;
1642+ if c = nil then Mark(NameOf(id) + ' isn''t a case of ' + TypeName(t));
1643+ if (c^.val <= High(seen)) and seen[c^.val] then Mark(NameOf(c^.name) + ' has two arms');
1644+ if c^.val <= High(seen) then seen[c^.val] := true;
1645+ Next;
1646+ if t^.form <> fEnum then begin MatchTag(p, c^.val, L); break end;
1647+ { an enumeration's arm may name several, which share its place }
1648+ ls.lo[ls.n] := c^.val; ls.hi[ls.n] := c^.val;
1649+ inc(ls.n);
1650+ if tok <> sComma then break;
1651+ Next;
1652+ until false;
1653+ OpenScope(NewScope);
1654+ if tok = sLparen then begin
1655+ Next;
1656+ f := c^.fields;
1657+ n := 0;
1658+ repeat
1659+ if tok <> sIdent then Expected('a name');
1660+ if f = nil then Mark('more names than ' + NameOf(c^.name) + ' has fields');
1661+ o := NewObj(oVar, id, f^.typ);
1662+ o^.lev := 1; o^.ind := true; o^.isVar := true;
1663+ o^.val := p; o^.off := f^.val;
1664+ Declare(o);
1665+ f := f^.next;
1666+ inc(n);
1667+ Next;
1668+ if tok <> sComma then break;
1669+ Next;
1670+ until false;
1671+ if f <> nil then Mark('name all the fields of ' + NameOf(c^.name) + ', or none');
1672+ Expect(sRparen);
1673+ end;
1674+ Expect(sColon);
1675+ for n := first to ls.n - 1 do ls.at[n] := pc;
1676+ Statements;
1677+ CloseScope;
1678+ Jump(endL);
1679+ if t^.form <> fEnum then Fix(L);
1680+ end;
1681+ all := all and ends;
1682+ end;
1683+ endAt := TokPos;
1684+ CloseEnd(start, ind);
1685+ ends := all;
1686+ if (t^.form = fInt) and not hasElse then
1687+ MarkHelp(endAt, 'a match on an integer needs an else arm', 'it may be empty: | else:');
1688+ if not hasElse then begin
1689+ c := t^.fields;
1690+ while c <> nil do begin
1691+ if (c^.val > High(seen)) or not seen[c^.val] then MarkAt(endAt, 'no arm for ' + NameOf(c^.name));
1692+ c := c^.next;
1693+ end;
1694+ end;
1695+ if byValue then begin
1696+ Fix(disp);
1697+ Dispatch(t, p, ls, elseAt, endL);
1698+ end;
1699+ Fix(endL);
1700+end;
1701+
1702+{ What a message calls x: its name n when x is just that name, else what
1703+ it is. }
1704+function Subject(const x: TItem; n: longint): shortstring;
1705+begin
1706+ if x.pos.b - x.pos.a = length(NameOf(n)) then Subject := NameOf(n)
1707+ else if x.mode = mConst then Subject := 'a constant'
1708+ else Subject := 'a value';
1709+end;
1710+
1711+{ x, named first n, is a variable the program may assign: not an
1712+ array constant, nor any part of one. }
1713+procedure Assignable(const x: TItem; n: longint);
1714+begin
1715+ if (x.mode = mConst) and (Subject(x, n) = NameOf(n)) then
1716+ MarkAt(x.pos, NameOf(n) + ' is a constant, and can''t be changed');
1717+ if (x.mode = mVar) and (x.obj <> nil) and (x.obj^.cls = oConst) then
1718+ MarkAt(x.pos, NameOf(x.obj^.name) + ' is a constant, and can''t be changed');
1719+ if (x.mode <> mVar) or not x.isVar then MarkAt(x.pos, 'can''t assign to ' + Subject(x, n));
1720+end;
1721+
1722+{ The designator a statement starts with. A variable named whole
1723+ before := is assigned, not read: naming it there leaves it as unread
1724+ as it was. }
1725+procedure LeftSide(var x: TItem; var called: boolean);
1726+var o: PObj; wasRead: boolean; n: longint;
1727+begin
1728+ n := id;
1729+ o := Lookup(n);
1730+ wasRead := (o <> nil) and o^.read;
1731+ Designator(x, called);
1732+ if (tok in [sBecomes, sComma]) and (x.pos.b - x.pos.a = length(NameOf(n))) then
1733+ o^.read := wasRead;
1734+end;
1735+
1736+{ a, b := f(x): the variables first, left to right, then the call;
1737+ then each result to its variable, in order. x is the first variable,
1738+ first its name, blank whether it is _. }
1739+procedure MultiAssign(var x: TItem; first: longint; blank: boolean);
1740+var
1741+ d: array[0..15] of TItem; dn: array[0..15] of longint; blanks: array[0..15] of boolean;
1742+ y, z: TItem; n, i: longint; called: boolean; f: PObj;
1743+begin
1744+ n := 0;
1745+ d[0] := x;
1746+ dn[0] := first;
1747+ blanks[0] := blank;
1748+ repeat
1749+ if not blanks[n] then begin
1750+ NotReadOnly(d[n]);
1751+ Assignable(d[n], dn[n]);
1752+ Pin(d[n]); { works out the address now, so that the call can't change it }
1753+ end;
1754+ inc(n);
1755+ if tok <> sComma then break;
1756+ if n > High(d) then Mark('more than ' + IntStr(High(d) + 1) + ' variables in one assignment');
1757+ Next;
1758+ blanks[n] := tok = sBlank;
1759+ if blanks[n] then Next
1760+ else begin
1761+ dn[n] := id;
1762+ LeftSide(d[n], called);
1763+ end;
1764+ until false;
1765+ Expect(sBecomes);
1766+ if tok = sTry then begin
1767+ TryCall(y);
1768+ called := true;
1769+ end else Designator(y, called);
1770+ if not called or not y.typ^.tuple or (y.typ^.len <> n) then begin
1771+ MarkAt(y.pos, 'expected a call with ' + IntStr(n) + ' results');
1772+ if y.mode = mWords then CopyToTemp(y);
1773+ end;
1774+ { two results on the stack: the first is brought to the top, and each
1775+ is popped into its variable in turn, as one value; else each is
1776+ read from the temporary they came back in }
1777+ if y.mode = mWords then Swap;
1778+ f := y.typ^.fields;
1779+ for i := 0 to n - 1 do begin
1780+ z := y;
1781+ if y.mode = mWords then begin z.mode := mStack; z.typ := f^.typ end
1782+ else Field(z, f);
1783+ if blanks[i] then Discard(z)
1784+ else begin
1785+ CoerceExact(z, d[i].typ, 'several results go to variables of just their types');
1786+ Assign(d[i], z);
1787+ end;
1788+ f := f^.next;
1789+ end;
1790+end;
1791+
1792+{ return a, b; or return f(x); with f's several results passed on }
1793+procedure ReturnResults;
1794+var f: PObj; x: TItem;
1795+begin
1796+ f := curResult^.fields;
1797+ passOn := true;
1798+ while f <> nil do begin
1799+ Expression(x, f^.typ);
1800+ if x.typ^.tuple then begin
1801+ if not Same(x.typ, curResult) then
1802+ MarkAt(x.pos, 'expected the results ' + TypeName(curResult) + ', found ' + TypeName(x.typ));
1803+ ReturnAll(x);
1804+ exit;
1805+ end;
1806+ ReturnField(f, x);
1807+ f := f^.next;
1808+ if f <> nil then Expect(sComma);
1809+ end;
1810+end;
1811+
1812+{ defer s: s is compiled where it stands, as a little subroutine of the
1813+ procedure, jumped over; each way out of the statement list calls it. }
1814+procedure Defer;
1815+var L, pos, saved: longint; oldLoop: PLoop; oldDeferring: boolean; start: TPos;
1816+begin
1817+ start := TokPos;
1818+ Next;
1819+ if directDefer then MarkAt(SpanFrom(start), 'defer can''t be deferred');
1820+ if numDefers > High(defers) then MarkAt(SpanFrom(start), 'more than ' + IntStr(High(defers) + 1) + ' deferred statements in one procedure');
1821+ L := NoLabel;
1822+ pos := DeferBegin(L, saved);
1823+ oldLoop := curLoop; oldDeferring := deferring;
1824+ curLoop := nil;
1825+ deferring := true;
1826+ directDefer := true;
1827+ Statement;
1828+ directDefer := false;
1829+ curLoop := oldLoop; deferring := oldDeferring;
1830+ DeferEnd(L, saved);
1831+ defers[numDefers] := pos;
1832+ inc(numDefers);
1833+end;
1834+
1835+{ Whether the expression of x := ..., which starts at the current
1836+ symbol, is x changed by adding to it, taking from it or its bits:
1837+ x + e, x - e, x | e or x xor e, with x nowhere in e, so that it can be
1838+ worked out in x's own register, if x is in one (gen's inPlace). }
1839+function ChangesItself(const x: TItem): boolean;
1840+var st: TScanState; wasSkipping: boolean; d: longint;
1841+begin
1842+ ChangesItself := false;
1843+ if (x.mode <> mVar) or (x.base <> bReg) or (x.typ^.form = fSlice) or (tok <> sIdent) or (id <> x.obj^.name) then exit;
1844+ SaveScan(st);
1845+ wasSkipping := skipping;
1846+ skipping := true; { its slips are told when it is compiled }
1847+ Next;
1848+ if tok in [sPlus, sMinus, sBar, sXor] then begin
1849+ ChangesItself := true;
1850+ d := 0;
1851+ while not ((d = 0) and (tok in [sSemicolon, sEnd])) and (tok <> sEof) do begin
1852+ if (tok = sIdent) and (id = x.obj^.name) then ChangesItself := false;
1853+ if tok in [sLparen, sLbrak, sLbrace] then inc(d)
1854+ else if tok in [sRparen, sRbrak, sRbrace] then dec(d);
1855+ Next;
1856+ end;
1857+ end;
1858+ RestoreScan(st);
1859+ skipping := wasSkipping;
1860+end;
1861+
1862+procedure OneStatement;
1863+var x, y: TItem; called: boolean; m: int64; c: TCall; start: TPos; first, n, i: longint; k: TKind;
1864+begin
1865+ start := TokPos;
1866+ first := id;
1867+ NoteLine(CurLine, CurCol);
1868+ m := TempMark;
1869+ ends := false;
1870+ case tok of
1871+ sIdent: begin
1872+ LeftSide(x, called);
1873+ if tok = sBecomes then begin
1874+ NotReadOnly(x);
1875+ Assignable(x, first);
1876+ Next;
1877+ if ChangesItself(x) then inPlace := x.chunk;
1878+ Expression(y, x.typ);
1879+ inPlace := -1;
1880+ Assign(x, y);
1881+ end else if tok = sComma then
1882+ MultiAssign(x, first, false)
1883+ else if not called then begin
1884+ if (x.mode = mProc) or ((x.mode in [mVar, mStack]) and (x.typ^.form = fProc)) then begin
1885+ BeginCall(c, x);
1886+ EndCall(c, x);
1887+ Discard(x);
1888+ end else if tok = sEql then
1889+ MarkHelp(x.pos, Subject(x, first) + ' isn''t a statement', 'assignment is written :=')
1890+ else MarkAt(x.pos, Subject(x, first) + ' isn''t a statement');
1891+ end else begin
1892+ if (x.mode <> mNone) and (numDrops <= High(drops)) then begin
1893+ drops[numDrops].at := x.pos;
1894+ if x.typ^.tuple then drops[numDrops].n := x.typ^.len else drops[numDrops].n := 1;
1895+ inc(numDrops);
1896+ end;
1897+ Discard(x);
1898+ end;
1899+ end;
1900+ sBlank: begin
1901+ Next;
1902+ if tok = sComma then MultiAssign(x, 0, true)
1903+ else begin
1904+ Expect(sBecomes);
1905+ Expression(x, nil);
1906+ { evaluated and dropped: a single value is loaded, so that a
1907+ volatile one is read }
1908+ if (x.mode in [mType, mBuiltin, mNone, mCase]) or (x.mode <> mStr) and not IsAggregate(x.typ) then
1909+ Value(x);
1910+ Discard(x);
1911+ end;
1912+ end;
1913+ sIf: IfStatement(start, Indent);
1914+ sWhile: WhileStatement(start, Indent);
1915+ sRepeat: RepeatStatement;
1916+ sFor: ForStatement(start, Indent);
1917+ sMatch: MatchStatement(start, Indent);
1918+ sReturn: begin
1919+ Next;
1920+ if deferring then MarkAt(SpanFrom(start), 'return can''t leave a deferred statement');
1921+ if tok = sSemicolon then begin
1922+ RunDefers(0);
1923+ ReturnNone;
1924+ end else begin
1925+ if (curResult <> nil) and curResult^.tuple then ReturnResults
1926+ else begin
1927+ Expression(x, curResult);
1928+ ReturnValue(x);
1929+ end;
1930+ { the result, one value or two words on top, waits in the frame
1931+ while the deferred statements run }
1932+ if (numDefers > 0) and (curResult <> nil) and not BehindPointer(curResult) then begin
1933+ n := 1; k := KindOf(curResult);
1934+ if InTwoRegs(curResult) then begin n := 2; k := kWord end;
1935+ if deferSlot = 0 then deferSlot := AllocPerm(16, 8);
1936+ for i := n - 1 downto 0 do PopVar(FrameAdr(deferSlot + 8 * i), 8);
1937+ RunDefers(0);
1938+ for i := 0 to n - 1 do PushVar(FrameAdr(deferSlot + 8 * i), 8, false, k);
1939+ end else RunDefers(0);
1940+ ReturnJump;
1941+ ends := true;
1942+ end;
1943+ end;
1944+ sBreak: begin
1945+ Next;
1946+ if curLoop = nil then MarkAt(SpanFrom(start), 'break outside a loop');
1947+ RunDefers(curLoop^.base);
1948+ Jump(curLoop^.brk);
1949+ end;
1950+ sDefer: Defer;
1951+ sTry: begin
1952+ TryCall(x);
1953+ if (x.mode <> mNone) and (numDrops <= High(drops)) then begin
1954+ drops[numDrops].at := x.pos;
1955+ if x.typ^.tuple then drops[numDrops].n := x.typ^.len else drops[numDrops].n := 1;
1956+ inc(numDrops);
1957+ end;
1958+ Discard(x);
1959+ end;
1960+ sArrow: MarkHelp(TokPos, 'a statement starts with a name', 'convert into a pointer variable, then assign through that');
1961+ else if AtLineStart then EndMissing(MissingPos, 'expected "end", found ' + Found)
1962+ else Expected('a statement');
1963+ end;
1964+ ReleaseTemps(m);
1965+end;
1966+
1967+procedure Statement;
1968+var r: TRecover; m: int64;
1969+begin
1970+ m := TempMark;
1971+ Guard(r);
1972+ if setjmp(r.jb) = 0 then begin
1973+ OneStatement;
1974+ skipped := false;
1975+ end else begin
1976+ Restore(r);
1977+ { a statement never starts a line: this is the next declaration }
1978+ if AtLineStart or not SkipConstruct then GiveUp(r);
1979+ ReleaseTemps(m);
1980+ skipped := true;
1981+ end;
1982+ Unguard(r);
1983+end;
1984+
1985+procedure Statements;
1986+var base: longint; old: boolean;
1987+begin
1988+ base := numDefers;
1989+ old := directDefer;
1990+ directDefer := false;
1991+ ends := false;
1992+ while not (tok in [sEnd, sElse, sElsif, sUntil, sBar, sEof]) do begin
1993+ Statement;
1994+ if not skipped or (tok = sSemicolon) then Expect(sSemicolon);
1995+ end;
1996+ RunDefers(base);
1997+ numDefers := base;
1998+ directDefer := old;
1999+end;
2000+
2001+{ Declarations }
2002+
2003+{ In a file read for its interface only: skip a procedure's body, from
2004+ its local declarations to the end that closes it. }
2005+procedure SkipBody;
2006+var d: longint; sawBegin: boolean;
2007+begin
2008+ d := 0;
2009+ sawBegin := false;
2010+ repeat
2011+ case tok of
2012+ sBegin: begin if d = 0 then sawBegin := true; inc(d) end;
2013+ sIf, sWhile, sFor, sMatch, sRecord, sVariant: inc(d);
2014+ sEnd: begin
2015+ dec(d);
2016+ if (d = 0) and sawBegin then begin Next; exit end;
2017+ end;
2018+ sEof: Expected('"end"');
2019+ end;
2020+ Next;
2021+ until false;
2022+end;
2023+
2024+procedure Declarations(top: boolean); forward;
2025+
2026+{ How Rt shows a variable of o's type in the trap report: 1 a signed
2027+ integer, 2 an unsigned one, 3 a BOOL, 4 an address, 5 a real; plus
2028+ its size times 16, and 256 if the frame holds its address, or 512
2029+ times 1 + i if it is in register VarRegs[i]; 0 if it isn't shown. }
2030+function VarKind(o: PObj): longint;
2031+var k, i: longint;
2032+begin
2033+ case o^.typ^.form of
2034+ fInt: k := 2 - ord(o^.typ^.signed);
2035+ fEnum, fSet: k := 2;
2036+ fBool: k := 3;
2037+ fPtr, fProc, fError: k := 4;
2038+ fReal: k := 5;
2039+ else exit(0);
2040+ end;
2041+ VarKind := k + o^.typ^.size * 16 + ord(o^.ind) * 256;
2042+ for i := 0 to High(ShownRegs) do
2043+ if o^.reg = ShownRegs[i] then VarKind := k + o^.typ^.size * 16 + (i + 1) * 512;
2044+end;
2045+
2046+{ Whether variable o could live in registers: a single value, a real
2047+ in an xmm register, or a slice, in two, that isn't C's }
2048+function RegFit(o: PObj): boolean;
2049+begin
2050+ RegFit := (o^.cls = oVar) and not o^.ind and not o^.ext
2051+ and ((o^.typ^.form in [fInt, fBool, fEnum, fPtr, fProc, fError, fSlice, fReal])
2052+ or (o^.typ^.form = fSet) and (o^.typ^.size <= 8));
2053+end;
2054+
2055+{ The first local of the procedure being compiled. Locals are chained
2056+ by link in the order declared, the module's own first; before is the
2057+ last one declared before the procedure's, or nil if there was none. }
2058+function FirstLocal(before: PObj): PObj;
2059+begin
2060+ if before = nil then FirstLocal := curModule^.locals else FirstLocal := before^.link;
2061+end;
2062+
2063+{ Puts the busiest variables of the procedure, whose parameters are
2064+ params and whose locals follow before, in registers: read ahead from
2065+ its "begin" to its end, a use counts 1, in a loop 4, in two 16, in
2066+ three or more 64, and a variable ADR is taken of can't have one. A register costs a save
2067+ and a restore, so a variable used less than three times keeps its
2068+ place in memory. A slice takes two, its pointer's and its length's;
2069+ a real one of the xmm registers, stored and loaded again around each
2070+ call, as System V keeps none through one. In a procedure that names no procedure, so calls nothing, the
2071+ parameters that arrive in the registers no call needs stay there
2072+ (KeepArrived), at no cost. }
2073+procedure ChooseRegs(params, before: PObj);
2074+var
2075+ cand: array[0..63] of PObj; weight: array[0..63] of longint;
2076+ isLoop: array[0..255] of boolean;
2077+ n, i, k, kx, d, loops, best, need: longint; o, q, qual: PObj; st: TScanState;
2078+ afterDot, wasSkipping, leaf: boolean;
2079+
2080+ function Candidate(name: longint): longint;
2081+ var j: longint;
2082+ begin
2083+ for j := 0 to n - 1 do if cand[j]^.name = name then exit(j);
2084+ Candidate := -1;
2085+ end;
2086+
2087+ procedure Add(o: PObj);
2088+ begin
2089+ if RegFit(o) and (n <= High(cand)) then begin cand[n] := o; weight[n] := 0; inc(n) end;
2090+ end;
2091+
2092+ { Whether naming o may make a call: a procedure, a procedure variable,
2093+ or NEW, SYSCALL or COPY, which use the registers a call would }
2094+ function Calls(o: PObj): boolean;
2095+ begin
2096+ Calls := (o <> nil) and ((o^.cls = oProc) or (o^.cls = oVar) and (o^.typ^.form = fProc)
2097+ or (o^.cls = oBuiltin) and ((o^.val = bNew) or (o^.val = bSyscall) or (o^.val = bCopy)));
2098+ end;
2099+
2100+begin
2101+ n := 0;
2102+ o := params;
2103+ while o <> nil do begin Add(o); o := o^.next end;
2104+ o := FirstLocal(before);
2105+ while o <> nil do begin Add(o); o := o^.link end;
2106+ if n > 0 then begin
2107+ SaveScan(st);
2108+ wasSkipping := skipping;
2109+ skipping := true; { its slips are told when it is compiled }
2110+ d := 0; loops := 0; afterDot := false; leaf := true; qual := nil;
2111+ repeat
2112+ { a name, or a module's name and one of its exports, that calls }
2113+ if (tok = sIdent) and not afterDot then begin
2114+ q := Lookup(id);
2115+ if Calls(q) then leaf := false;
2116+ qual := nil;
2117+ if (q <> nil) and (q^.cls = oModule) then qual := q;
2118+ end else if (tok = sIdent) and (qual <> nil) then begin
2119+ if (qual^.module = nil) or Calls(Find(qual^.module^.scope, id)) then leaf := false;
2120+ qual := nil;
2121+ end;
2122+ case tok of
2123+ sBegin, sIf, sMatch, sWhile, sFor, sRepeat:
2124+ if d < High(isLoop) then begin
2125+ inc(d);
2126+ isLoop[d] := tok in [sWhile, sFor, sRepeat];
2127+ if isLoop[d] then inc(loops);
2128+ end;
2129+ sEnd, sUntil: begin
2130+ if isLoop[d] then dec(loops);
2131+ dec(d);
2132+ end;
2133+ sIdent:
2134+ if id = nameAdr then begin
2135+ Next;
2136+ if tok = sLparen then Next;
2137+ { a hugely negative weight bars it from a register, whatever
2138+ its uses add }
2139+ if (tok = sIdent) and (Candidate(id) >= 0) then weight[Candidate(id)] := low(longint) div 2;
2140+ end else if not afterDot and (Candidate(id) >= 0) then begin
2141+ k := Candidate(id);
2142+ if loops > 2 then inc(weight[k], 64) else inc(weight[k], 1 shl (2 * loops));
2143+ end;
2144+ end;
2145+ afterDot := tok = sPeriod; { a name after a dot is a field, not a variable }
2146+ if (d > 0) and (tok <> sEof) then Next;
2147+ until (d = 0) or (tok = sEof);
2148+ RestoreScan(st);
2149+ skipping := wasSkipping;
2150+ if leaf then begin
2151+ o := params;
2152+ while o <> nil do begin
2153+ k := Candidate(o^.name);
2154+ if (k >= 0) and (weight[k] >= 0) then KeepArrived(o); { a candidate whose ADR isn't taken }
2155+ o := o^.next;
2156+ end;
2157+ end;
2158+ { a slice's weight is shared by its two registers }
2159+ for i := 0 to n - 1 do
2160+ if cand[i]^.typ^.form = fSlice then weight[i] := weight[i] div 2;
2161+ { the heaviest, each used at least three times a register, take the
2162+ five registers in turn, while there are enough for each, and the
2163+ reals the four xmm registers of XVarRegs }
2164+ k := 0; kx := 0;
2165+ repeat
2166+ best := -1;
2167+ for i := 0 to n - 1 do
2168+ if (cand[i]^.reg = 0) and (weight[i] >= 3) and ((best < 0) or (weight[i] > weight[best])) then best := i;
2169+ if best < 0 then break;
2170+ need := 1 + ord(cand[best]^.typ^.form = fSlice);
2171+ if cand[best]^.typ^.form = fReal then begin
2172+ if kx < 4 then begin cand[best]^.reg := XVarRegs[kx]; inc(kx) end
2173+ else weight[best] := 0;
2174+ end else if k + need <= 5 then begin
2175+ cand[best]^.reg := VarRegs[k];
2176+ if need = 2 then cand[best]^.reg2 := VarRegs[k + 1];
2177+ inc(k, need);
2178+ end else weight[best] := 0; { too big for what is left }
2179+ until false;
2180+ end;
2181+end;
2182+
2183+{ The registers the variables of the procedure are in, as bits: bit i
2184+ is VarRegs[i], bit XBit + i XVarRegs[i] }
2185+function RegsOf(params, before: PObj): longint;
2186+var o: PObj; m, k: longint;
2187+begin
2188+ m := 0;
2189+ o := params;
2190+ while o <> nil do begin
2191+ for k := 0 to 4 do if (o^.reg = VarRegs[k]) or (o^.reg2 = VarRegs[k]) then m := m or (1 shl k);
2192+ for k := 0 to 3 do if o^.reg = XVarRegs[k] then m := m or (1 shl (XBit + k));
2193+ o := o^.next;
2194+ end;
2195+ o := FirstLocal(before);
2196+ while o <> nil do begin
2197+ if o^.cls = oVar then begin
2198+ for k := 0 to 4 do if (o^.reg = VarRegs[k]) or (o^.reg2 = VarRegs[k]) then m := m or (1 shl k);
2199+ for k := 0 to 3 do if o^.reg = XVarRegs[k] then m := m or (1 shl (XBit + k));
2200+ end;
2201+ o := o^.link;
2202+ end;
2203+ RegsOf := m;
2204+end;
2205+
2206+{ Gives each local not in a register its slot in the frame, the slots
2207+ the prologue zeroes, and then tells gen which registers the
2208+ variables are in. A variable in a register has no slot: it starts at
2209+ zero in its register, and the trap report finds it there. }
2210+procedure PlaceLocals(params, before: PObj);
2211+var o: PObj;
2212+begin
2213+ ResetLocals;
2214+ o := FirstLocal(before);
2215+ while o <> nil do begin
2216+ if (o^.cls = oVar) and (o^.reg = 0) then o^.val := AllocPerm(o^.typ^.size, o^.typ^.align)
2217+ else if (o^.cls = oVar) and (o^.reg >= XmmVar) then begin
2218+ o^.val := AllocPerm(8, 8);
2219+ XHome(o^.reg, o^.val);
2220+ end;
2221+ o := o^.link;
2222+ end;
2223+ o := params;
2224+ while o <> nil do begin
2225+ if o^.reg >= XmmVar then XHome(o^.reg, o^.val);
2226+ o := o^.next;
2227+ end;
2228+ UseRegs(RegsOf(params, before));
2229+end;
2230+
2231+procedure Body(p: PObj; sig: PType; line: longint);
2232+var
2233+ q, params, last, o, before: PObj; old: PType; st: TScanState;
2234+ mark: TCodeMark; drops0, errs: longint;
2235+begin
2236+ OpenScope(NewScope);
2237+ params := nil; last := nil;
2238+ q := sig^.fields;
2239+ while q <> nil do begin
2240+ o := NewObj(oVar, q^.name, q^.typ);
2241+ o^.pos := q^.pos;
2242+ o^.lev := 1;
2243+ o^.isVar := q^.isVar;
2244+ o^.param := true;
2245+ if last = nil then params := o else last^.next := o;
2246+ last := o;
2247+ q := q^.next;
2248+ end;
2249+ BeginProc(sig, params);
2250+ deferSlot := 0;
2251+ o := params;
2252+ while o <> nil do begin
2253+ q := o^.next;
2254+ Declare(o);
2255+ o := q;
2256+ end;
2257+ curProc := p;
2258+ before := curModule^.lastLocal;
2259+ Declarations(false);
2260+ ChooseRegs(params, before);
2261+ PlaceLocals(params, before);
2262+ { the body, made again if a variable in a register must be in memory }
2263+ SaveScan(st);
2264+ MarkCode(mark); drops0 := numDrops; errs := errors;
2265+ old := curResult;
2266+ repeat
2267+ demoted := false;
2268+ Expect(sBegin);
2269+ curResult := sig^.base;
2270+ EnterBody(p^.chunk, line);
2271+ stray := false; elseIf := false; deferSlot := 0;
2272+ Statements;
2273+ p^.openEnd := (curResult <> nil) and not ends;
2274+ NoteLine(CurLine, CurCol);
2275+ Expect(sEnd);
2276+ if not (demoted or lost) or (errors <> errs) then break;
2277+ { a parameter kept where it arrived goes to memory: a call or a copy
2278+ wanted its register }
2279+ if lost then begin
2280+ o := params;
2281+ while o <> nil do begin
2282+ if KeptIn(o) then begin o^.reg := 0; o^.reg2 := 0 end;
2283+ o := o^.next;
2284+ end;
2285+ end;
2286+ numDrops := drops0;
2287+ Redo(mark);
2288+ PlaceLocals(params, before);
2289+ RestoreScan(st);
2290+ until false;
2291+ EndProc(p^.chunk, p^.openEnd);
2292+ { its parameters and variables, for the trap report }
2293+ o := FirstLocal(before);
2294+ q := params;
2295+ while q <> nil do begin
2296+ if VarKind(q) <> 0 then NoteVar(p^.chunk, q^.name, q^.val, VarKind(q));
2297+ q := q^.next;
2298+ end;
2299+ while o <> nil do begin
2300+ if (o^.cls = oVar) and (VarKind(o) <> 0) then NoteVar(p^.chunk, o^.name, o^.val, VarKind(o));
2301+ o := o^.link;
2302+ end;
2303+ curResult := old;
2304+ curProc := nil;
2305+ CloseScope;
2306+end;
2307+
2308+{ An integer constant in a code procedure, for the assembler: a whole
2309+ expression, or a single factor where an expression would read on
2310+ too far }
2311+function AsmConst(whole: boolean): int64;
2312+var x: TItem;
2313+begin
2314+ if whole then exit(ConstExpr);
2315+ Factor(x, nil);
2316+ if not IsInt(x.typ) then MarkAt(x.pos, 'expected an integer constant, found ' + What(x));
2317+ AsmConst := ConstValue(x);
2318+end;
2319+
2320+procedure CodeBody(p: PObj; sig: PType; const at: TPos);
2321+var q: PObj; ni, nf: longint;
2322+begin
2323+ ni := 0; nf := 0;
2324+ q := sig^.fields;
2325+ while q <> nil do begin
2326+ if not q^.isVar and (q^.typ^.form = fSlice) then inc(ni, 2) { address, then length }
2327+ else begin
2328+ if not q^.isVar and not IsScalar(q^.typ) then
2329+ MarkAt(at, 'a code procedure takes integers, BOOL, reals, pointers, procedures and slices');
2330+ if (q^.typ^.form = fReal) and not q^.isVar then inc(nf) else inc(ni);
2331+ end;
2332+ q := q^.next;
2333+ end;
2334+ if (ni > 6) or (nf > 8) or sig^.variadic then MarkAt(at, 'too many parameters for a code procedure');
2335+ if sig^.base <> nil then
2336+ if sig^.base^.tuple then begin
2337+ q := sig^.base^.fields;
2338+ if (sig^.base^.len <> 2) or (q^.typ^.size <> 8) or (q^.next^.typ^.size <> 8)
2339+ or not IsScalar(q^.typ) or not IsScalar(q^.next^.typ)
2340+ or (q^.typ^.form = fReal) or (q^.next^.typ^.form = fReal) then
2341+ MarkAt(at, 'a code procedure returns two results only in rax and rdx');
2342+ end else if not IsScalar(sig^.base) and (sig^.base^.form <> fSlice) then
2343+ MarkAt(at, 'a code procedure returns a single value');
2344+ CodeProc(p^.chunk, @AsmConst);
2345+ Expect(sEnd);
2346+end;
2347+
2348+procedure ProcDecl;
2349+var n, line: longint; exp: boolean; sig: PType; p: PObj; at: TPos;
2350+begin
2351+ InstancesFor(false);
2352+ line := CurLine;
2353+ Next;
2354+ IdentDef(n, exp, at);
2355+ sig := Signature;
2356+ Expect(sSemicolon);
2357+ p := Find(TopScope, n);
2358+ if (p <> nil) and (p^.cls = oProc) and p^.fwd then begin
2359+ if not Same(p^.typ, sig) then begin
2360+ Error(at, NameOf(n) + ' doesn''t have the signature it was declared forward with');
2361+ Note(p^.pos, 'the signature is here');
2362+ Fail;
2363+ end;
2364+ if tok = sForward then Mark(NameOf(n) + ' is declared forward twice');
2365+ p^.exported := p^.exported or exp;
2366+ end else begin
2367+ p := NewObj(oProc, n, sig);
2368+ p^.pos := at;
2369+ p^.exported := exp;
2370+ if (curModule^.name = nameRt) and not checkMode and (n = nameFail) then p^.chunk := rtFail
2371+ else p^.chunk := NewChunk(secText, curModule^.sname, n);
2372+ Declare(p);
2373+ end;
2374+ if tok = sForward then begin
2375+ Next;
2376+ p^.fwd := true;
2377+ exit;
2378+ end;
2379+ p^.fwd := false;
2380+ if tok = sCode then begin
2381+ Next;
2382+ p^.isCode := true;
2383+ CodeBody(p, sig, at);
2384+ end else if checkMode then SkipBody else Body(p, sig, line);
2385+ if tok = sIdent then begin
2386+ if id = curModule^.name then EndMissing(TokPos, NameOf(n) + ' has no "end": this one closes the module')
2387+ else if id <> n then EndMissing(TokPos, 'expected ' + NameOf(n) + ', found ' + NameOf(id));
2388+ Next;
2389+ end;
2390+end;
2391+
2392+{ An extern procedure or variable: C's, reached through the quadword
2393+ that holds its address. }
2394+procedure ExternDecl;
2395+var n: longint; exp: boolean; o, q: PObj; t: PType; at: TPos;
2396+begin
2397+ Next;
2398+ curModule^.usesC := true;
2399+ if tok = sProc then begin
2400+ Next;
2401+ IdentDef(n, exp, at);
2402+ WillDeclare(n);
2403+ inExtern := true;
2404+ t := Signature;
2405+ inExtern := false;
2406+ q := t^.fields;
2407+ while q <> nil do begin
2408+ if q^.isVar or not IsScalar(q^.typ) then
2409+ MarkAt(at, 'C takes integers, BOOL, reals, pointers and procedures');
2410+ q := q^.next;
2411+ end;
2412+ if (t^.base <> nil) and not IsScalar(t^.base) then MarkAt(at, 'C returns a single value');
2413+ o := NewObj(oProc, n, t);
2414+ end else begin
2415+ if tok <> sVar then Expected('"proc" or "var"');
2416+ Next;
2417+ IdentDef(n, exp, at);
2418+ WillDeclare(n);
2419+ Expect(sColon);
2420+ declExported := exp;
2421+ t := ParseType;
2422+ declExported := false;
2423+ o := NewObj(oVar, n, t);
2424+ end;
2425+ o^.pos := at;
2426+ o^.exported := exp;
2427+ o^.ext := true;
2428+ o^.chunk := ExternChunk(n);
2429+ Declare(o);
2430+end;
2431+
2432+{ An array or record constant: a literal of constants, which become
2433+ the bytes of a read-only chunk, as a string constant's do (report
2434+ section 4). An address in it, of a string, an array constant, a
2435+ procedure or an ERROR, waits in fixes until the chunk is made, then
2436+ is a fixup the linker patches. The bytes are the compiler's own
2437+ machine's, little-endian, as the target's are. }
2438+var
2439+ constBytes: PBytes;
2440+ fixes: array[0..4095] of record off: int64; chunk: longint; end;
2441+ numFixes: longint;
2442+
2443+procedure ConstFix(off: int64; chunk: longint);
2444+begin
2445+ if numFixes > High(fixes) then MarkAt(TokPos, 'more than ' + IntStr(High(fixes) + 1) + ' addresses in one constant');
2446+ fixes[numFixes].off := off;
2447+ fixes[numFixes].chunk := chunk;
2448+ inc(numFixes);
2449+end;
2450+
2451+{ The part of type t at offset off of the constant }
2452+procedure ConstPart(t: PType; off: int64);
2453+var e: TItem; f: PObj; k: int64; r: single; start: TPos;
2454+begin
2455+ start := TokPos;
2456+ if (t^.form = fArray) and (tok = sLbrak) then begin
2457+ Next;
2458+ k := 0;
2459+ if tok <> sRbrak then
2460+ repeat
2461+ if k < t^.len then ConstPart(t^.base, off + k * t^.base^.size)
2462+ else ConstPart(t^.base, off);
2463+ inc(k);
2464+ if tok <> sComma then break;
2465+ Next;
2466+ until false;
2467+ Expect(sRbrak);
2468+ if k <> t^.len then MarkAt(SpanFrom(start), 'expected ' + IntStr(t^.len) + ' elements, found ' + IntStr(k));
2469+ exit;
2470+ end;
2471+ if (t^.form = fRecord) and not t^.tuple and (tok = sLbrace) then begin
2472+ Next;
2473+ if tok <> sRbrace then
2474+ repeat
2475+ if tok <> sIdent then Expected('a field');
2476+ f := FieldOf(t);
2477+ Next;
2478+ Expect(sColon);
2479+ ConstPart(f^.typ, off + f^.val);
2480+ if tok <> sComma then break;
2481+ Next;
2482+ until false;
2483+ Expect(sRbrace);
2484+ exit;
2485+ end;
2486+ Expression(e, t);
2487+ if (e.mode = mStr) and ((t^.form = fSlice) or (t^.form = fArray)) and (t^.base = tU8) then begin
2488+ if t^.form = fSlice then begin
2489+ ConstFix(off, e.chunk);
2490+ Move(e.val, constBytes^[off + 8], 8);
2491+ end else if e.val > t^.len then MarkAt(e.pos, 'the string is longer than ' + TypeName(t))
2492+ else Move(rodata^[chunks^[e.chunk].start], constBytes^[off], e.val);
2493+ end else if t^.form = fSlice then begin
2494+ if (e.mode <> mVar) or (e.obj = nil) or (e.obj^.cls <> oConst) or (e.typ^.form <> fArray)
2495+ or (e.pos.b - e.pos.a <> length(NameOf(e.obj^.name))) or not Same(e.typ^.base, t^.base) then
2496+ MarkAt(e.pos, 'a constant slice is a string or an array constant of its elements, found ' + What(e));
2497+ ConstFix(off, e.chunk);
2498+ Move(e.typ^.len, constBytes^[off + 8], 8);
2499+ end else if t^.form = fVariant then MarkAt(e.pos, 'a constant holds no variant')
2500+ else if t^.form in [fArray, fRecord] then MarkAt(e.pos, 'expected a literal of ' + TypeName(t))
2501+ else begin
2502+ Coerce(e, t);
2503+ if (e.mode = mProc) and not e.obj^.ext then ConstFix(off, e.obj^.chunk)
2504+ else if e.mode <> mConst then MarkAt(e.pos, 'expected a constant, found ' + What(e))
2505+ else if (t^.form = fError) and (e.val > 0) then ConstFix(off, e.val - 1)
2506+ else if (t^.form = fPtr) and (e.val <> 0) then MarkAt(e.pos, 'a constant pointer is nil')
2507+ else if (t^.form = fReal) and (t^.size = 4) then begin
2508+ r := RealOf(e);
2509+ Move(r, constBytes^[off], 4);
2510+ end else Move(e.val, constBytes^[off], t^.size);
2511+ end;
2512+end;
2513+
2514+{ The chunk of n, a constant of type t whose literal is next }
2515+function AggregateConst(t: PType; n: longint): longint;
2516+var c, i: longint;
2517+begin
2518+ constBytes := AllocMem(t^.size + 8);
2519+ numFixes := 0;
2520+ ConstPart(t, 0);
2521+ c := NewChunk(secRodata, curModule^.sname, n);
2522+ SetData(c, constBytes, t^.size, t^.align);
2523+ for i := 0 to numFixes - 1 do AddDataFixup(c, fixes[i].off, fixes[i].chunk, 0);
2524+ FreeMem(constBytes);
2525+ AggregateConst := c;
2526+end;
2527+
2528+procedure ConstDecl(top: boolean);
2529+var n: longint; exp: boolean; x: TItem; o: PObj; t: PType; start, at: TPos;
2530+begin
2531+ IdentDef(n, exp, at);
2532+ WillDeclare(n);
2533+ t := nil;
2534+ if tok = sColon then begin
2535+ Next;
2536+ start := TokPos;
2537+ t := ParseType;
2538+ if (t <> tError) and not ((t^.form = fArray) or (t^.form = fRecord) and not t^.tuple) then
2539+ MarkAt(SpanFrom(start), 'only an ERROR, an array or a record constant has a type');
2540+ end;
2541+ Expect(sEql);
2542+ if (t <> nil) and (t^.form in [fArray, fRecord]) then begin
2543+ o := NewObj(oConst, n, t);
2544+ o^.chunk := AggregateConst(t, n);
2545+ o^.pos := at;
2546+ o^.exported := exp and top;
2547+ Declare(o);
2548+ Expect(sSemicolon);
2549+ exit;
2550+ end;
2551+ Expression(x, nil);
2552+ o := NewObj(oConst, n, x.typ);
2553+ o^.pos := at;
2554+ o^.exported := exp and top;
2555+ if t = tError then begin
2556+ o^.typ := tError;
2557+ o^.val := ErrorChunk(x, curModule^.sname, n) + 1;
2558+ end else if x.mode = mStr then begin o^.val := x.val; o^.chunk := x.chunk end
2559+ else o^.val := ConstValue(x);
2560+ Declare(o);
2561+ Expect(sSemicolon);
2562+end;
2563+
2564+procedure TypeDecl(top: boolean);
2565+var n: longint; exp: boolean; o: PObj; t: PType; at: TPos;
2566+begin
2567+ IdentDef(n, exp, at);
2568+ WillDeclare(n);
2569+ Expect(sEql);
2570+ declExported := exp and top;
2571+ inTypes := true;
2572+ t := ParseType;
2573+ o := NewObj(oType, n, t);
2574+ o^.pos := at;
2575+ o^.exported := exp and top;
2576+ if t^.obj = nil then t^.obj := o;
2577+ Declare(o);
2578+ Expect(sSemicolon);
2579+end;
2580+
2581+procedure VarDecl(top: boolean);
2582+var
2583+ i, k: longint; o: PObj; t: PType;
2584+ names: array[0..63] of longint; exps: array[0..63] of boolean;
2585+ poss: array[0..63] of TPos;
2586+begin
2587+ k := 0;
2588+ repeat
2589+ if k > High(names) then Mark('more than ' + IntStr(High(names) + 1) + ' names in one declaration');
2590+ IdentDef(names[k], exps[k], poss[k]);
2591+ WillDeclare(names[k]);
2592+ inc(k);
2593+ if tok <> sComma then break;
2594+ Next;
2595+ until false;
2596+ Expect(sColon);
2597+ declExported := top and exps[0];
2598+ t := ParseType;
2599+ declExported := false;
2600+ for i := 0 to k - 1 do begin
2601+ o := NewObj(oVar, names[i], t);
2602+ o^.pos := poss[i];
2603+ o^.exported := exps[i] and top;
2604+ o^.isVar := false;
2605+ if top then begin
2606+ o^.lev := 0;
2607+ o^.chunk := NewChunk(secBss, curModule^.sname, names[i]);
2608+ SetBss(o^.chunk, t^.size, t^.align);
2609+ end else
2610+ o^.lev := 1; { its slot comes from PlaceLocals, if it needs one }
2611+ Declare(o);
2612+ end;
2613+ Expect(sSemicolon);
2614+end;
2615+
2616+{ After a procedure had an error: its name is poison if it wasn't
2617+ declared, and reading goes on after the "end Name;" that closes it,
2618+ or at the next procedure if that is missing }
2619+procedure SkipProc;
2620+var st: TScanState;
2621+begin
2622+ Next;
2623+ if (tok = sIdent) and (Find(TopScope, id) = nil) then Poison(id);
2624+ repeat
2625+ repeat Next until AtLineStart or (tok = sEof);
2626+ if tok in [sProc, sExtern, sEof] then exit;
2627+ if tok = sEnd then begin
2628+ SaveScan(st);
2629+ Next;
2630+ if tok = sIdent then Next;
2631+ if tok = sSemicolon then begin Next; exit end;
2632+ RestoreScan(st);
2633+ exit;
2634+ end;
2635+ until false;
2636+end;
2637+
2638+{ One declaration, of the kind k, as a recovery point }
2639+procedure Declaration(k: TSym; top: boolean);
2640+var r: TRecover;
2641+begin
2642+ Guard(r);
2643+ numDeclaring := 0;
2644+ if setjmp(r.jb) = 0 then
2645+ case k of
2646+ sConst: ConstDecl(top);
2647+ sType: TypeDecl(top);
2648+ sVar: VarDecl(top);
2649+ sProc: begin
2650+ if not top then Mark('procedures don''t nest');
2651+ ProcDecl;
2652+ Expect(sSemicolon);
2653+ end;
2654+ sExtern: begin
2655+ if not top then Mark('extern is only for the top of a module');
2656+ ExternDecl;
2657+ Expect(sSemicolon);
2658+ end;
2659+ end
2660+ else begin
2661+ Restore(r);
2662+ if k = sProc then SkipProc else SkipDeclaration;
2663+ end;
2664+ Unguard(r);
2665+end;
2666+
2667+procedure Declarations(top: boolean);
2668+var i: longint; o: PObj; k: TSym;
2669+begin
2670+ repeat
2671+ k := tok;
2672+ case k of
2673+ sConst, sVar: begin
2674+ Next;
2675+ while tok = sIdent do Declaration(k, top);
2676+ end;
2677+ sType: begin
2678+ Next;
2679+ numFwd := 0;
2680+ while tok = sIdent do Declaration(sType, top);
2681+ inTypes := false;
2682+ for i := 0 to numFwd - 1 do begin
2683+ o := Lookup(fwdTypes[i]^.fwd);
2684+ if (o = nil) or (o^.cls <> oType) then begin
2685+ NotDeclared(fwdPos[i], fwdTypes[i]^.fwd);
2686+ fwdTypes[i]^.base := tPoison;
2687+ end else begin
2688+ fwdTypes[i]^.base := o^.typ;
2689+ Named(o);
2690+ end;
2691+ fwdTypes[i]^.fwd := -1;
2692+ end;
2693+ end;
2694+ sProc, sExtern: Declaration(k, top);
2695+ else exit;
2696+ end;
2697+ until false;
2698+end;
2699+
2700+{ Modules }
2701+
2702+{ Whether m is module n with these arguments. }
2703+function IsModule(m: PModule; n: longint; const args: TArgs): boolean;
2704+var i: longint;
2705+begin
2706+ IsModule := false;
2707+ if (m^.name <> n) or (m^.args.n <> args.n) then exit;
2708+ for i := 0 to args.n - 1 do
2709+ if (m^.args.o[i] <> args.o[i]) or not Same(m^.args.t[i], args.t[i]) then exit;
2710+ IsModule := true;
2711+end;
2712+
2713+function FindModule(n: longint; const args: TArgs): PModule;
2714+var m: PModule;
2715+begin
2716+ m := firstModule;
2717+ while (m <> nil) and not IsModule(m, n, args) do m := m^.next;
2718+ FindModule := m;
2719+end;
2720+
2721+{ The arguments of an instance: types, or procedures named. }
2722+procedure ParseArgs(var args: TArgs; const mname: shortstring);
2723+var o: PObj; start: TPos;
2724+begin
2725+ Next;
2726+ repeat
2727+ if args.n > High(args.t) then Mark('too many type arguments for ' + mname);
2728+ args.o[args.n] := nil;
2729+ start := TokPos;
2730+ if tok = sIdent then begin
2731+ o := QualIdent;
2732+ if o^.cls = oProc then args.o[args.n] := o
2733+ else if o^.cls <> oType then MarkAt(SpanFrom(start), NameOf(o^.name) + ' isn''t a type or a procedure');
2734+ args.t[args.n] := o^.typ;
2735+ end else args.t[args.n] := ParseType;
2736+ args.pos[args.n] := SpanFrom(start);
2737+ inc(args.n);
2738+ if tok <> sComma then break;
2739+ Next;
2740+ until false;
2741+ Expect(sRparen);
2742+end;
2743+
2744+{ Past an instance's arguments, to be read when it is made }
2745+procedure SkipArgs;
2746+var p: longint;
2747+begin
2748+ p := 0;
2749+ repeat
2750+ if tok = sLparen then inc(p)
2751+ else if tok = sRparen then dec(p)
2752+ else if tok in [sSemicolon, sEof] then Expected('")"');
2753+ Next;
2754+ until p = 0;
2755+end;
2756+
2757+{ A generic module's parameters, bound to the instance's arguments: a
2758+ type parameter names its type, a procedure parameter its procedure. }
2759+procedure Params(m: PModule);
2760+var i: longint; o, a: PObj; sig: PType; s: shortstring; at: TPos;
2761+begin
2762+ i := 0;
2763+ s := NameOf(m^.name) + '(';
2764+ Next;
2765+ repeat
2766+ if tok <> sIdent then Expected('a name');
2767+ if i >= m^.args.n then MarkAt(m^.args.at, NameOf(m^.name) + ' needs a type for ' + NameOf(id));
2768+ if m^.args.o[i] <> nil then MarkAt(m^.args.pos[i], NameOf(m^.name) + ' needs a type for ' + NameOf(id));
2769+ o := NewObj(oType, id, m^.args.t[i]);
2770+ o^.used := true; { a parameter of the module, not a declaration }
2771+ Declare(o);
2772+ s := s + TypeName(m^.args.t[i]) + ',';
2773+ inc(i);
2774+ Next;
2775+ if tok <> sComma then break;
2776+ Next;
2777+ until false;
2778+ while tok = sSemicolon do begin
2779+ Next;
2780+ if tok <> sIdent then Expected('a name');
2781+ at := TokPos;
2782+ o := NewObj(oProc, id, nil);
2783+ Next;
2784+ Expect(sColon);
2785+ Expect(sProc);
2786+ sig := Signature;
2787+ if i >= m^.args.n then MarkAt(m^.args.at, NameOf(m^.name) + ' needs a procedure for ' + NameOf(o^.name));
2788+ a := m^.args.o[i];
2789+ if a = nil then MarkAt(m^.args.pos[i], NameOf(m^.name) + ' needs a procedure for ' + NameOf(o^.name));
2790+ if not Same(a^.typ, sig) then begin
2791+ Error(m^.args.pos[i], NameOf(a^.name) + ' doesn''t have the signature of ' + NameOf(o^.name));
2792+ Note(at, 'the signature is here');
2793+ Finish;
2794+ end;
2795+ o^.typ := a^.typ; o^.chunk := a^.chunk; o^.isCode := a^.isCode; o^.ext := a^.ext;
2796+ o^.used := true;
2797+ Declare(o);
2798+ s := s + NameOf(a^.module^.name) + '.' + NameOf(a^.name) + ',';
2799+ inc(i);
2800+ end;
2801+ Expect(sRparen);
2802+ if i <> m^.args.n then MarkAt(m^.args.at, 'too many type arguments for ' + NameOf(m^.name));
2803+ s[length(s)] := ')';
2804+ m^.sname := Name(s);
2805+end;
2806+
2807+{ Warns of o if it is never used, or a variable only assigned. What
2808+ is exported may be used elsewhere, and a name that starts with _ says
2809+ it is meant to go unused. Writing a var parameter, a match's name for
2810+ a field or C's variable is what it is for. }
2811+procedure Warn(o: PObj);
2812+var s: shortstring;
2813+begin
2814+ s := NameOf(o^.name);
2815+ if (o^.cls = oProc) and o^.openEnd then
2816+ Warning(o^.pos, s + ' may reach its end without return, and then returns zero');
2817+ if o^.exported or (s[1] = '_') then exit;
2818+ if o^.used and (o^.read or (o^.cls <> oVar) or o^.isVar or o^.ext) then exit;
2819+ case o^.cls of
2820+ oConst: s := 'constant ' + s;
2821+ oType: s := 'type ' + s;
2822+ oVar: if o^.param then s := 'parameter ' + s else s := 'variable ' + s;
2823+ oProc: s := 'procedure ' + s;
2824+ oModule: s := 'module ' + s;
2825+ else exit;
2826+ end;
2827+ if o^.used then Warning(o^.pos, s + ' is assigned but never read')
2828+ else if o^.cls = oModule then Warning(o^.pos, s + ' is imported but never used')
2829+ else Warning(o^.pos, s + ' is never used');
2830+ if not o^.used and (o^.param or o^.ind) then
2831+ Help('if it must be there, call it _' + NameOf(o^.name));
2832+end;
2833+
2834+{ Warns of the call at p, which drops its n results }
2835+procedure Dropped(const p: TPos; n: longint);
2836+var s, blanks: shortstring; i: longint;
2837+begin
2838+ s := Source(p);
2839+ i := Pos('(', s);
2840+ if i > 0 then s := copy(s, 1, i - 1);
2841+ blanks := '_';
2842+ for i := 2 to n do blanks := blanks + ', _';
2843+ if n = 1 then Warning(p, 'the result of ' + s + ' is dropped')
2844+ else Warning(p, 'the results of ' + s + ' are dropped');
2845+ Help('if that is meant, write ' + blanks + ' := ' + s + '(...)');
2846+end;
2847+
2848+{ The warnings of module m, by where each declaration is: its own
2849+ declarations and its procedures' are two lists, each in order, and
2850+ firstDrop on are the calls that drop results. The
2851+ instances of a generic module share its text, and so its warnings:
2852+ only the first is warned of. }
2853+procedure Warnings(m: PModule; firstDrop: longint);
2854+var a, b: PObj; n: PModule; i: longint;
2855+begin
2856+ n := firstModule;
2857+ while (n <> nil) and (n^.name <> m^.name) do n := n^.next;
2858+ if n <> nil then exit;
2859+ a := m^.first; b := m^.locals;
2860+ i := firstDrop;
2861+ while (a <> nil) or (b <> nil) or (i < numDrops) do
2862+ if (i < numDrops) and ((a = nil) or (drops[i].at.a < a^.pos.a)) and ((b = nil) or (drops[i].at.a < b^.pos.a)) then begin
2863+ Dropped(drops[i].at, drops[i].n);
2864+ inc(i);
2865+ end else if (b = nil) or (a <> nil) and (a^.pos.a < b^.pos.a) then begin
2866+ Warn(a);
2867+ a := a^.link;
2868+ end else begin
2869+ Warn(b);
2870+ b := b^.link;
2871+ end;
2872+end;
2873+
2874+{ Modules being compiled, not yet finished: for finding a cycle. }
2875+var
2876+ pending: array[0..63] of PModule;
2877+ numPending: longint;
2878+
2879+function Exists(const path: shortstring): boolean;
2880+var st: Stat; p: shortstring;
2881+begin
2882+ p := path + #0;
2883+ Exists := (FpStat(@p[1], st) = 0) and ((st.st_mode and S_IFMT) = S_IFREG);
2884+end;
2885+
2886+{ Compiles module n from path, an instance if args are given, or only
2887+ reads its interface if checkOnly; returns it. An import calls this in
2888+ the middle of reading another file, so it is re-entrant: it saves the
2889+ scanner's state, the open scopes, the current module and file and
2890+ whether checks are on, and puts them back at the end. }
2891+function CompileFile(const path: shortstring; n: longint; const args: TArgs; checkOnly: boolean): PModule;
2892+var
2893+ st: TScanState; saved: array[0..MaxDepth - 1] of longint; d: longint;
2894+ oldMod: PModule; oldCheck, oldChecks: boolean; m: PModule;
2895+ lib: PLib; start: TPos; alias, mname, line, oldPath: longint; o: PObj; body: longint; iargs: TArgs;
2896+ generic: boolean; argsAt: TScanState; why: shortstring; firstDrop: longint;
2897+begin
2898+ firstDrop := numDrops;
2899+ SaveScan(st);
2900+ SaveScopes(d, saved);
2901+ oldMod := curModule; oldCheck := checkMode; oldPath := curFile; oldChecks := checks;
2902+ checks := true;
2903+ curFile := Name(path);
2904+ why := Open(path);
2905+ if why <> '' then Fatal('can''t read ' + path + ': ' + why);
2906+ New(m);
2907+ FillChar(m^, SizeOf(TModule), 0);
2908+ m^.name := n;
2909+ m^.sname := n;
2910+ m^.args := args;
2911+ m^.scope := NewScope;
2912+ m^.path := path;
2913+ m^.body := -1;
2914+ m^.checkOnly := checkOnly;
2915+ curModule := m;
2916+ checkMode := checkOnly;
2917+ if not checkOnly then begin
2918+ if numPending > High(pending) then Mark('imports nested more than ' + IntStr(High(pending) + 1) + ' deep');
2919+ pending[numPending] := m;
2920+ inc(numPending);
2921+ end;
2922+ OpenScope(m^.scope);
2923+ Next;
2924+ Expect(sModule);
2925+ if (tok <> sIdent) or (id <> n) then Mark('expected module ' + NameOf(n) + ', found ' + Found);
2926+ Next;
2927+ { the module first pending is the one named on the command line,
2928+ which nothing imports, so no arguments come with it }
2929+ if (tok = sLparen) and not checkOnly and (numPending = 1) then
2930+ Mark(NameOf(n) + ' is generic: it is compiled where a module imports it')
2931+ else if tok = sLparen then Params(m)
2932+ else if args.n > 0 then MarkAt(args.at, NameOf(n) + ' isn''t generic');
2933+ Expect(sSemicolon);
2934+ while tok = sImport do begin
2935+ Next;
2936+ repeat
2937+ if tok <> sIdent then Expected('a module name');
2938+ start := TokPos;
2939+ alias := id;
2940+ mname := id;
2941+ iargs.n := 0;
2942+ generic := false;
2943+ Next;
2944+ if tok = sBecomes then begin
2945+ Next;
2946+ if tok <> sIdent then Expected('a module name');
2947+ mname := id;
2948+ Next;
2949+ if tok = sLparen then begin
2950+ generic := true;
2951+ SaveScan(argsAt);
2952+ SkipArgs;
2953+ end;
2954+ end;
2955+ iargs.at := SpanFrom(start);
2956+ o := NewObj(oModule, alias, nil);
2957+ o^.pos := start;
2958+ Declare(o);
2959+ if not generic then begin
2960+ o^.module := ImportModule(mname, iargs);
2961+ AddImport(m, o^.module);
2962+ end else begin
2963+ o^.module := nil; { until the instance is made, at its first use }
2964+ if numDeferred > High(deferred) then Mark('more than ' + IntStr(High(deferred) + 1) + ' generic imports');
2965+ deferred[numDeferred].o := o;
2966+ deferred[numDeferred].m := m;
2967+ deferred[numDeferred].mname := mname;
2968+ deferred[numDeferred].args := argsAt;
2969+ deferred[numDeferred].at := iargs.at;
2970+ inc(numDeferred);
2971+ end;
2972+ if tok <> sComma then break;
2973+ Next;
2974+ until false;
2975+ Expect(sSemicolon);
2976+ end;
2977+ while tok = sLink do begin
2978+ Next;
2979+ if (tok = sIdent) and (id = nameStatic) then m^.linkStatic := true
2980+ else if tok = sString then begin
2981+ New(lib);
2982+ lib^.name := Intern(@sbuf, slen);
2983+ lib^.next := m^.libs;
2984+ m^.libs := lib;
2985+ m^.usesC := true;
2986+ end else Expected('a library or "static"');
2987+ Next;
2988+ Expect(sSemicolon);
2989+ end;
2990+ { check off;: the module's index and slice checks left out; neither
2991+ word is reserved }
2992+ if (tok = sIdent) and (id = nameCheck) then begin
2993+ Next;
2994+ if (tok <> sIdent) or (id <> nameOff) then Expected('"off"');
2995+ Next;
2996+ Expect(sSemicolon);
2997+ checks := false;
2998+ end;
2999+ Declarations(true);
3000+ if tok = sBegin then begin
3001+ if checkMode then SkipBody
3002+ else begin
3003+ InstancesFor(true);
3004+ line := CurLine;
3005+ Next;
3006+ body := NewChunk(secText, m^.sname, nameBody);
3007+ m^.body := body;
3008+ BeginProc(tBodySig, nil);
3009+ deferSlot := 0;
3010+ curResult := nil;
3011+ EnterBody(body, line);
3012+ stray := false; elseIf := false;
3013+ Statements;
3014+ NoteLine(CurLine, CurCol);
3015+ Expect(sEnd);
3016+ EndProc(body, false);
3017+ end;
3018+ end else Expect(sEnd);
3019+ if (tok <> sIdent) or (id <> n) then EndMissing(MissingPos, 'expected ' + NameOf(n) + ', found ' + Found);
3020+ Next;
3021+ if tok <> sPeriod then Expected('"."');
3022+ o := m^.first;
3023+ while o <> nil do begin
3024+ if (o^.cls = oProc) and o^.fwd then Error(TokPos, NameOf(o^.name) + ' is declared forward but never defined');
3025+ o := o^.link;
3026+ end;
3027+ if (errors = 0) and not checkOnly then Warnings(m, firstDrop);
3028+ numDrops := firstDrop;
3029+ if errors > 0 then Finish; { a module with errors stops the compiler after it }
3030+ CloseScope;
3031+ m^.done := true;
3032+ if not checkOnly then begin
3033+ dec(numPending);
3034+ if lastModule = nil then firstModule := m else lastModule^.next := m;
3035+ lastModule := m;
3036+ end;
3037+ curModule := oldMod; checkMode := oldCheck; curFile := oldPath; checks := oldChecks;
3038+ RestoreScopes(d, saved);
3039+ RestoreScan(st);
3040+ CompileFile := m;
3041+end;
3042+
3043+{ The interface check: b must export just what a does. }
3044+procedure CompareIface(a, b: PModule);
3045+var o, q: PObj;
3046+begin
3047+ o := a^.first;
3048+ while o <> nil do begin
3049+ if o^.exported then begin
3050+ q := Find(b^.scope, o^.name);
3051+ if (q = nil) or not q^.exported or (Fingerprint(o) <> Fingerprint(q)) then
3052+ Fatal(b^.path + ': ' + NameOf(o^.name) + ' isn''t exported as in ' + a^.path);
3053+ end;
3054+ o := o^.link;
3055+ end;
3056+ q := b^.first;
3057+ while q <> nil do begin
3058+ o := Find(a^.scope, q^.name);
3059+ if q^.exported and ((o = nil) or not o^.exported) then
3060+ Fatal(b^.path + ': ' + NameOf(q^.name) + ' isn''t exported by ' + a^.path);
3061+ q := q^.link;
3062+ end;
3063+end;
3064+
3065+{ Reads every other file of module n in dir, and checks its interface
3066+ against m, compiled from the file named chosen. }
3067+procedure CheckSiblings(const dir, chosen: shortstring; n: longint; m: PModule; const args: TArgs);
3068+var
3069+ dp: pDir; e: pDirent; f, prefix: shortstring; i: longint;
3070+ others: array[0..31] of shortstring; numOthers: longint;
3071+begin
3072+ prefix := NameOf(n) + '.';
3073+ numOthers := 0;
3074+ dp := FpOpenDir(dir);
3075+ if dp = nil then exit;
3076+ repeat
3077+ e := FpReadDir(dp^);
3078+ if e = nil then break;
3079+ f := '';
3080+ i := 0;
3081+ while (e^.d_name[i] <> #0) and (i < 255) do begin
3082+ f := f + e^.d_name[i];
3083+ inc(i);
3084+ end;
3085+ if (copy(f, 1, length(prefix)) = prefix) and (length(f) > 4)
3086+ and (copy(f, length(f) - 3, 4) = '.raz') and (f <> chosen)
3087+ and (numOthers <= High(others)) then begin
3088+ others[numOthers] := f;
3089+ inc(numOthers);
3090+ end;
3091+ until false;
3092+ FpCloseDir(dp^);
3093+ for i := 0 to numOthers - 1 do
3094+ CompareIface(m, CompileFile(dir + '/' + others[i], n, args, true));
3095+end;
3096+
3097+const Suffixes: array[0..3] of string[16] = ('.' + Target, '.' + TargetOS, '.' + TargetArch, '');
3098+
3099+{ The directories searched for modules, in order, from -1 to numInc }
3100+function SearchDir(i: longint): shortstring;
3101+begin
3102+ if i = -1 then SearchDir := mainDir
3103+ else if i = numInc then SearchDir := libDir
3104+ else SearchDir := incDirs[i];
3105+end;
3106+
3107+function ModuleFile(n: longint; var dir, f: shortstring): boolean;
3108+var i, j: longint;
3109+begin
3110+ for i := -1 to numInc do begin
3111+ dir := SearchDir(i);
3112+ for j := 0 to 3 do begin
3113+ f := NameOf(n) + Suffixes[j] + '.raz';
3114+ if Exists(dir + '/' + f) then exit(true);
3115+ end;
3116+ end;
3117+ ModuleFile := false;
3118+end;
3119+
3120+{ A program has one module of each name: module n, found as dir/f,
3121+ must have no files in a later directory, unless dir/f is a link to
3122+ one of them, which chooses it (report, section 3) }
3123+procedure CheckOneModule(n: longint; const dir, f: shortstring; const at: TPos);
3124+var i, j: longint; past, chosen: boolean; g, files, others: shortstring;
3125+ st, mine: Stat;
3126+begin
3127+ g := dir + '/' + f + #0;
3128+ FpStat(@g[1], mine);
3129+ others := '';
3130+ past := false;
3131+ for i := -1 to numInc do begin
3132+ if past then begin
3133+ files := '';
3134+ chosen := false;
3135+ for j := 0 to 3 do begin
3136+ g := SearchDir(i) + '/' + NameOf(n) + Suffixes[j] + '.raz';
3137+ if Exists(g) then begin
3138+ files := files + ' and ' + ShownPath(g);
3139+ g := g + #0;
3140+ FpStat(@g[1], st);
3141+ chosen := chosen or ((st.st_dev = mine.st_dev) and (st.st_ino = mine.st_ino));
3142+ end;
3143+ end;
3144+ if not chosen then others := others + files;
3145+ end;
3146+ past := past or (SearchDir(i) = dir);
3147+ end;
3148+ if others = '' then exit;
3149+ Error(at, 'module ' + NameOf(n) + ' is in ' + ShownPath(dir + '/' + f) + others);
3150+ Help('a program has one module of each name; a symbolic link to one of these files chooses it');
3151+ Fail;
3152+end;
3153+
3154+function ImportModule(name: longint; const args: TArgs): PModule;
3155+var m: PModule; i: longint; dir, f: shortstring;
3156+begin
3157+ m := FindModule(name, args);
3158+ if m <> nil then exit(m);
3159+ for i := 0 to numPending - 1 do
3160+ if IsModule(pending[i], name, args) then MarkAt(args.at, NameOf(name) + ' imports itself');
3161+ if not ModuleFile(name, dir, f) then begin
3162+ Error(args.at, 'can''t find module ' + NameOf(name));
3163+ dir := ShownPath(SearchDir(-1));
3164+ for i := 0 to numInc do dir := dir + ', ' + ShownPath(SearchDir(i));
3165+ Help('looked for ' + NameOf(name) + '.raz in ' + dir);
3166+ Fail;
3167+ end;
3168+ CheckOneModule(name, dir, f, args.at);
3169+ m := CompileFile(dir + '/' + f, name, args, false);
3170+ CheckSiblings(dir, f, name, m, args);
3171+ ImportModule := m;
3172+end;
3173+
3174+procedure AddImport(m, im: PModule);
3175+var imp: PImport;
3176+begin
3177+ New(imp);
3178+ imp^.module := im;
3179+ imp^.next := m^.imports;
3180+ m^.imports := imp;
3181+end;
3182+
3183+{ Makes the instance that deferred[i] imports: its arguments are read
3184+ where the import wrote them, and must be declared by now. Compiling
3185+ the instance comes in the middle of a declaration, so what that
3186+ declaration has under way is kept aside meanwhile. }
3187+procedure MakeInstance(i: longint; const at: TPos);
3188+var
3189+ d: TDeferred; st: TScanState; args: TArgs; types, exported, ext, wasQuiet: boolean; nf, nd: longint;
3190+ ft: array[0..255] of PType; fp: array[0..255] of TPos; decl: array[0..63] of longint;
3191+begin
3192+ d := deferred[i];
3193+ dec(numDeferred);
3194+ deferred[i] := deferred[numDeferred];
3195+ SaveScan(st);
3196+ RestoreScan(d.args);
3197+ args.n := 0;
3198+ making := true; useAt := at;
3199+ ParseArgs(args, NameOf(d.mname));
3200+ making := false;
3201+ RestoreScan(st);
3202+ args.at := d.at;
3203+ types := inTypes; exported := declExported; ext := inExtern; wasQuiet := quiet;
3204+ nf := numFwd; ft := fwdTypes; fp := fwdPos; nd := numDeclaring; decl := declaring;
3205+ d.o^.module := ImportModule(d.mname, args);
3206+ inTypes := types; declExported := exported; inExtern := ext; quiet := wasQuiet;
3207+ numFwd := nf; fwdTypes := ft; fwdPos := fp; numDeclaring := nd; declaring := decl;
3208+ AddImport(curModule, d.o^.module);
3209+end;
3210+
3211+procedure FirstUse(o: PObj; const at: TPos);
3212+var i: longint;
3213+begin
3214+ for i := 0 to numDeferred - 1 do
3215+ if deferred[i].o = o then begin MakeInstance(i, at); exit end;
3216+ Fail; { its arguments had an error, already reported }
3217+end;
3218+
3219+{ An instance can't be compiled in the middle of another procedure's
3220+ code, so before a procedure's code begins, from its "proc" on, or
3221+ the module body's, from its "begin" to the end of the file, this
3222+ reads ahead for the names of imports not yet made, and makes those. }
3223+procedure InstancesFor(wholeRest: boolean);
3224+var st: TScanState; d, i: longint; begun: boolean;
3225+begin
3226+ if checkMode then exit;
3227+ i := numDeferred - 1;
3228+ while (i >= 0) and (deferred[i].m <> curModule) do dec(i);
3229+ if i < 0 then exit;
3230+ { The procedure ends at the "end" that closes its first "begin": d
3231+ counts the words still open that "end" or "until" closes, and begun
3232+ says that begin was met, so that a record's end in its declarations
3233+ doesn't stop it. A forward or code procedure has no raz body to
3234+ read, so it stops at that word. The body reads to the end of the
3235+ file, as wholeRest says. }
3236+ SaveScan(st);
3237+ d := 0; begun := false;
3238+ repeat
3239+ case tok of
3240+ sIdent: for i := numDeferred - 1 downto 0 do
3241+ if (deferred[i].m = curModule) and (deferred[i].o^.name = id) then MakeInstance(i, TokPos);
3242+ sBegin: begin begun := begun or (d = 0); inc(d) end;
3243+ sIf, sWhile, sFor, sMatch, sRepeat, sRecord, sVariant: inc(d);
3244+ sEnd, sUntil: dec(d);
3245+ end;
3246+ if not wholeRest and (d = 0) and (begun or (tok in [sForward, sCode])) then break;
3247+ Next;
3248+ until tok = sEof;
3249+ RestoreScan(st);
3250+end;
3251+
3252+function CompileMain(const path: shortstring): PModule;
3253+var base: shortstring; i, n: longint; none: TArgs;
3254+begin
3255+ none.n := 0;
3256+ i := length(path);
3257+ while (i > 0) and (path[i] <> '/') do dec(i);
3258+ if i = 0 then mainDir := '.' else mainDir := copy(path, 1, i - 1);
3259+ base := copy(path, i + 1, 255);
3260+ i := pos('.', base);
3261+ if i > 0 then base := copy(base, 1, i - 1);
3262+ if base = '' then Fatal('no module in ' + path);
3263+ n := Name(base);
3264+ none.at := TokPos;
3265+ if n <> nameRt then ImportModule(nameRt, none);
3266+ if FindModule(n, none) <> nil then CompileMain := FindModule(n, none)
3267+ else CompileMain := CompileFile(path, n, none, false);
3268+end;
3269+
3270+initialization
3271+ nameRt := Name('Rt');
3272+ nameFail := Name('fail');
3273+ nameMain := Name('main');
3274+ nameAdr := Name('ADR');
3275+ nameBody := Name('body');
3276+ nameStatic := Name('static');
3277+ nameCheck := Name('check');
3278+ nameOff := Name('off');
3279+ tArgv := NewPtr(NewPtr(tU8, false), false);
3280+ tBodySig := NewType(fProc, 8, 8);
3281+ curLoop := nil;
3282+ numPending := 0;
3283+ firstModule := nil;
3284+ lastModule := nil;
3285+end.

seed/raz.pas added +245 -0

@@ -0,0 +1,245 @@
1+{ raz.pas: the command line.
2+
3+ raz [-I dir]... [-o file] [-Werror] [-S] Main.raz
4+ raz run [-I dir]... Main.raz [arg]...
5+ raz --version
6+
7+ Compiles the main module and every module it imports, writes the
8+ entry point, links what it reaches, and writes the executable: by
9+ default the main module's file without its .raz; with -S, it lists
10+ the main module's code instead. raz run writes it to a memfd
11+ instead, a file that lives only in memory, and executes it in raz's
12+ place with the arguments after Main.raz, so its status is the
13+ program's; its argv[0] is Main.raz.
14+
15+ The program starts by saving argc and argv, runs every module's body
16+ (those of the modules the program imports, imported modules first),
17+ then the main module's main, and ends with Rt.exit and main's
18+ status. A static program does this from its entry point. One that
19+ uses C starts through the C library, __libc_start_main, which sets
20+ C up and calls this as C's main; first it gives Rt C's exit, which
21+ Rt.exit then ends the program with.
22+
23+ Depends on: everything else.
24+ Leaves out: the work itself; the other units compile, link and
25+ write, and this only reads the command line and runs them in order. }
26+
27+program raz;
28+
29+{$mode objfpc}{$H-}
30+
31+uses math, BaseUnix, syscall, scan, diag, sym, chunk, x64, gen, parse, link, elf;
32+
33+const
34+ { what git describe says, made by make: 0.3.0 at the tag v0.3.0,
35+ 0.3.0-5-g38d29a8 five commits past it }
36+ Version = {$I version.inc};
37+ Report = '2026-10.21'; { the version of doc/raz.md it follows }
38+ MemfdCreate = 319; { the system call; FPC 3.2.2 has no name for it }
39+ MfdCloexec = 1; { an ELF still executes: the kernel opens it first }
40+
41+{ The modules the program uses: the main module, Rt, and every module
42+ they import. A module read only for the interface check is not. }
43+procedure Use(m: PModule);
44+var i: PImport;
45+begin
46+ if m^.used then exit;
47+ m^.used := true;
48+ i := m^.imports;
49+ while i <> nil do begin
50+ Use(i^.module);
51+ i := i^.next;
52+ end;
53+end;
54+
55+{ Whether the program uses C: if so, the libraries it needs go to
56+ elf.pas, the C library first. }
57+function UsesC: boolean;
58+var m, st, c: PModule; l: PLib; i: longint; seen: boolean;
59+begin
60+ st := nil; c := nil;
61+ numNeeded := 1;
62+ needed[0] := Intern(PChar('libc.so.6'), 9);
63+ m := firstModule;
64+ while m <> nil do begin
65+ if m^.used and m^.linkStatic then st := m;
66+ if m^.used and m^.usesC then c := m;
67+ l := m^.libs;
68+ while m^.used and (l <> nil) do begin
69+ seen := false;
70+ for i := 0 to numNeeded - 1 do seen := seen or (needed[i] = l^.name);
71+ if not seen then begin
72+ if numNeeded > High(needed) then Fatal('more than ' + IntStr(High(needed) + 1) + ' libraries');
73+ needed[numNeeded] := l^.name;
74+ inc(numNeeded);
75+ end;
76+ l := l^.next;
77+ end;
78+ m := m^.next;
79+ end;
80+ if (st <> nil) and (c <> nil) then
81+ Fatal(NameOf(st^.name) + ' says link static, but ' + NameOf(c^.name) + ' uses C');
82+ if c = nil then numNeeded := 0;
83+ UsesC := c <> nil;
84+end;
85+
86+{ What raz -h says }
87+procedure Usage;
88+begin
89+ writeln('usage: raz [option]... Main.raz compiles Main.raz and the modules it imports');
90+ writeln(' raz run [option]... Main.raz [arg]... compiles it and runs it, with the args');
91+ writeln('options:');
92+ writeln(' -o file the program''s file, Main without .raz if left out');
93+ writeln(' -I dir looks for imported modules in dir too, after Main.raz''s own');
94+ writeln(' -Werror a warning counts as an error');
95+ writeln(' -S lists the main module''s code, under each line of source');
96+ writeln(' -s strips symbols, line numbers, the places a failure is told');
97+ writeln(' by and the profiler: a failure says only its address');
98+ writeln(' -noprofile leaves out the profiler, which RAZ_PROFILE turns on');
99+ writeln(' -h, --help says this');
100+ writeln(' --version says the version, and the report it follows');
101+ writeln('see raz(1), and the report, doc/raz.md');
102+end;
103+
104+function RtObj(rt: PModule; const n: shortstring): PObj;
105+var o: PObj;
106+begin
107+ o := Find(rt^.scope, Intern(@n[1], length(n)));
108+ if o = nil then Fatal('Rt has no ' + n);
109+ RtObj := o;
110+end;
111+
112+var
113+ path, outPath, dir, s: shortstring;
114+ i, first, entry, fd: longint;
115+ m, rt: PModule;
116+ main: PObj;
117+ run, noProfile: boolean;
118+ links: array[0..3] of TLink;
119+ numLinks: longint;
120+
121+
122+{ Rt is given the address of chunk, in its variable v }
123+procedure AddLink(chunk: longint; v: PObj);
124+begin
125+ links[numLinks].chunk := chunk;
126+ links[numLinks].into := v^.chunk;
127+ inc(numLinks);
128+end;
129+
130+begin
131+ { constants fold as the machine computes: NaN and infinities, no traps }
132+ SetExceptionMask([exInvalidOp, exDenormalized, exZeroDivide, exOverflow, exUnderflow, exPrecision]);
133+ path := '';
134+ outPath := '';
135+ numInc := 0;
136+ noProfile := false;
137+ run := (ParamCount >= 1) and (ParamStr(1) = 'run');
138+ i := 1 + ord(run);
139+ while i <= ParamCount do begin
140+ s := ParamStr(i);
141+ if s = '-I' then begin
142+ inc(i);
143+ if numInc > High(incDirs) then Fatal('more than ' + IntStr(High(incDirs) + 1) + ' -I directories');
144+ incDirs[numInc] := ParamStr(i);
145+ inc(numInc);
146+ end else if s = '-o' then begin
147+ inc(i);
148+ outPath := ParamStr(i);
149+ end else if s = '-Werror' then
150+ werror := true
151+ else if s = '-S' then
152+ listing := true
153+ else if s = '-s' then
154+ stripped := true
155+ else if s = '-noprofile' then
156+ noProfile := true
157+ else if (s = '-h') or (s = '--help') then begin
158+ Usage;
159+ Halt(0);
160+ end else if s = '--version' then begin
161+ writeln('raz ', Version, ', report ', Report);
162+ Halt(0);
163+ end else if (s <> '') and (s[1] = '-') then
164+ Fatal('unknown option ' + s)
165+ else begin
166+ path := s;
167+ first := i;
168+ if run then break; { the rest are the program's }
169+ end;
170+ inc(i);
171+ end;
172+ if path = '' then begin
173+ Usage;
174+ Halt(1);
175+ end;
176+ if run and (outPath <> '') then Fatal('raz run takes no -o');
177+ dir := ParamStr(0);
178+ i := length(dir);
179+ while (i > 0) and (dir[i] <> '/') do dec(i);
180+ if i = 0 then libDir := 'lib' else libDir := copy(dir, 1, i) + 'lib';
181+ if outPath = '' then begin
182+ outPath := path;
183+ if copy(outPath, length(outPath) - 3, 4) = '.raz' then
184+ outPath := copy(outPath, 1, length(outPath) - 4)
185+ else outPath := outPath + '.out';
186+ end;
187+
188+ m := CompileMain(path);
189+ if errors > 0 then Finish;
190+
191+ Use(m);
192+ rt := firstModule;
193+ while (rt <> nil) and (NameOf(rt^.name) <> 'Rt') do rt := rt^.next;
194+ if rt <> nil then Use(rt);
195+
196+ main := Find(m^.scope, Intern('main', 4));
197+ if main <> nil then begin
198+ if (main^.cls <> oProc) or not main^.exported then Error(main^.pos, 'main must be an exported procedure')
199+ else if (main^.typ^.len <> 0) or ((main^.typ^.base <> nil) and (main^.typ^.base <> tInt)) then
200+ Error(main^.pos, 'main must be proc main* or proc main*: INT');
201+ if errors > 0 then Finish;
202+ end;
203+ Finish;
204+
205+ if rt = nil then Fatal('can''t find module Rt');
206+ { what Rt is given: the places, which the linker makes, for Rt to say
207+ where a failed check or a signal was (place), and the calls under
208+ way then (calls); and the profiler, which needs them too. raz -s
209+ gives none, -noprofile no profiler. }
210+ numLinks := 0;
211+ if not stripped then begin
212+ placesChunk := NewChunk(secRodata, -1, -1);
213+ SetData(placesChunk, nil, 0, 8);
214+ AddLink(placesChunk, RtObj(rt, 'places'));
215+ AddLink(RtObj(rt, 'calls')^.chunk, RtObj(rt, 'teller'));
216+ AddLink(RtObj(rt, 'place')^.chunk, RtObj(rt, 'placer'));
217+ if not noProfile then AddLink(RtObj(rt, 'startProfile')^.chunk, RtObj(rt, 'profiler'));
218+ end;
219+ entry := EntryPoint(UsesC, firstModule, main, RtObj(rt, 'cExit')^.chunk,
220+ RtObj(rt, 'exit')^.chunk, links, numLinks);
221+
222+ MarkLive(entry);
223+ if not HasReals then
224+ for i := 0 to numChunks - 1 do
225+ if chunks^[i].live and chunks^[i].reals then
226+ Error(chunks^[i].realsAt, 'this target has no reals');
227+ if errors > 0 then Finish;
228+ if listing then begin
229+ List(m^.sname);
230+ exit;
231+ end;
232+
233+ mainPath := path;
234+ if run then begin
235+ { argv from Main.raz on is the program's, ending in nil as it must }
236+ fd := Do_SysCall(MemfdCreate, TSysParam(PChar('raz')), MfdCloexec);
237+ if fd < 0 then Fatal('can''t create a memfd');
238+ Str(fd, s);
239+ outPath := '/proc/self/fd/' + s + #0;
240+ WriteElf(outPath, entry);
241+ FpExecve(@outPath[1], @argv[first], envp);
242+ Fatal('can''t run ' + path);
243+ end;
244+ WriteElf(outPath, entry);
245+end.

seed/scan.pas added +886 -0

@@ -0,0 +1,886 @@
1+{ scan.pas: the scanner.
2+
3+ Reads a raz source file and hands the parser one symbol at a time:
4+ reserved words, identifiers, numbers, characters, strings and
5+ operators. Identifiers are interned, so that the rest of the compiler
6+ compares names as small integers. The scanner also says where the
7+ current symbol is, for messages.
8+
9+ Depends on: BaseUnix, to read files; diag, to report errors.
10+ Leaves out: recovery from errors in the text itself, such as a string
11+ not closed: the first such error stops the compiler. The parser goes
12+ on after its own errors, through recovery below. }
13+
14+unit scan;
15+
16+{$mode objfpc}{$H-}
17+
18+interface
19+
20+uses diag;
21+
22+type
23+ TSym = (sNull, sIdent, sInt, sReal, sChar, sString,
24+ sPlus, sMinus, sTimes, sSlash, sEql, sNeq, sLss, sLeq, sGtr, sGeq,
25+ sBecomes, sColon, sSemicolon, sComma, sPeriod, sUpto, sEllipsis,
26+ sLparen, sRparen, sLbrak, sRbrak, sLbrace, sRbrace, sArrow, sAmp, sTilde, sBar,
27+ sBlank,
28+ { the reserved words, in the order of Words below }
29+ sAnd, sBegin, sBreak, sBy, sCode, sConst, sDefer, sDiv, sDo, sElse,
30+ sElsif, sEnd, sExtern, sFor, sForward, sIf, sImport, sIn, sLink,
31+ sMatch, sMod, sModule, sNot, sOf, sOr, sPacked, sProc, sRecord,
32+ sRepeat, sReturn, sSet, sShl, sShr, sThen, sTo, sTry, sType, sUntil, sVar,
33+ sVariant, sVolatile, sWhile, sXor,
34+ sEof);
35+
36+ PBytes = ^TBytes;
37+ TBytes = array[0..MaxInt - 1] of byte;
38+ PLongs = ^TLongs;
39+ TLongs = array[0..MaxInt div 4 - 1] of longint;
40+
41+ { Where the scanner is. Importing a module compiles it in the middle
42+ of another, so the parser saves this and restores it afterwards. }
43+ TScanState = record
44+ buf: PChar;
45+ len, pos, line, lineStart: longint;
46+ tokPos, tokLine, tokLineStart: longint;
47+ prevEnd: longint; { where the symbol before this one ends }
48+ tok: TSym;
49+ ival: int64;
50+ rval: double;
51+ id: longint;
52+ f: longint; { the file, as diag knows it }
53+ end;
54+
55+const
56+ MaxIdent = 63;
57+ MaxStr = 65536;
58+
59+var
60+ tok: TSym; { the current symbol }
61+ ival: int64; { sInt, sChar: its value }
62+ rval: double; { sReal: its value }
63+ id: longint; { sIdent: its name }
64+ sbuf: array[0..MaxStr] of byte; { sString: its bytes, then a zero }
65+ slen: longint; { sString: how many bytes }
66+
67+function Intern(p: PChar; n: longint): longint;
68+function NameOf(n: longint): shortstring;
69+function Reserved(n: longint): boolean;
70+function Open(const path: shortstring): shortstring;
71+procedure Next;
72+procedure Mark(const msg: shortstring);
73+procedure MarkAt(const p: TPos; const msg: shortstring);
74+procedure MarkHelp(const p: TPos; const msg, hint: shortstring);
75+procedure Fail;
76+function AtLineStart: boolean;
77+function Indent: longint;
78+function SymText(s: TSym): shortstring;
79+function Found: shortstring;
80+
81+var
82+ { Where the parser goes on after an error: the innermost statement or
83+ declaration being read. nil stops the compiler at the first error. }
84+ recovery: ^jmp_buf;
85+ { The parser is skipping what it has read once already, after an
86+ error, so slips in it aren't reported again. }
87+ skipping: boolean;
88+procedure SaveScan(var st: TScanState);
89+procedure RestoreScan(const st: TScanState);
90+function TokPos: TPos;
91+function AfterPrev: TPos;
92+function MissingPos: TPos;
93+function SpanFrom(const p: TPos): TPos;
94+function CurLine: longint;
95+function CurCol: longint;
96+procedure LineCol(a: longint; out line, col: longint);
97+
98+implementation
99+
100+uses BaseUnix;
101+
102+const
103+ NumWords = ord(sXor) - ord(sAnd) + 1;
104+ Words: array[0..NumWords - 1] of string[8] = (
105+ 'and', 'begin', 'break', 'by', 'code', 'const', 'defer', 'div', 'do',
106+ 'else', 'elsif', 'end', 'extern', 'for', 'forward', 'if', 'import',
107+ 'in', 'link', 'match', 'mod', 'module', 'not', 'of', 'or', 'packed',
108+ 'proc', 'record', 'repeat', 'return', 'set', 'shl', 'shr', 'then',
109+ 'to', 'try', 'type', 'until', 'var', 'variant', 'VOLATILE', 'while', 'xor');
110+ Ops: array[sPlus..sBlank] of string[3] = (
111+ '+', '-', '*', '/', '=', '#', '<', '<=', '>', '>=',
112+ ':=', ':', ';', ',', '.', '..', '...',
113+ '(', ')', '[', ']', '{', '}', '^', '&', '~', '|', '_');
114+
115+var
116+ cur: TScanState; { buf .. path; tok, ival, rval and id live above }
117+
118+ { The name table: every distinct identifier once, in a pool of
119+ characters, found through an open-addressed hash table. }
120+ pool: PChar;
121+ poolLen, poolCap: longint;
122+ nameOff, nameLen, nameHash: PLongs;
123+ numNames, nameCap: longint;
124+ table: PLongs; { name + 1, or 0 for an empty slot }
125+ tableMask: longint;
126+
127+{ Names }
128+
129+function Hash(p: PChar; n: longint): longint;
130+var h: longword; i: longint;
131+begin
132+ h := 2166136261;
133+ for i := 0 to n - 1 do h := (h xor byte(p[i])) * 16777619;
134+ Hash := longint(h and $7FFFFFFF);
135+end;
136+
137+procedure Grow;
138+var i, j, n: longint;
139+begin
140+ FreeMem(table);
141+ tableMask := tableMask * 2 + 1;
142+ table := GetMem((tableMask + 1) * 4);
143+ FillChar(table^, (tableMask + 1) * 4, 0);
144+ for n := 0 to numNames - 1 do begin
145+ i := nameHash^[n] and tableMask;
146+ while table^[i] <> 0 do i := (i + 1) and tableMask;
147+ table^[i] := n + 1;
148+ end;
149+ j := nameCap * 2;
150+ nameOff := ReAllocMem(nameOff, j * 4);
151+ nameLen := ReAllocMem(nameLen, j * 4);
152+ nameHash := ReAllocMem(nameHash, j * 4);
153+ nameCap := j;
154+end;
155+
156+function Intern(p: PChar; n: longint): longint;
157+var h, i, k: longint;
158+begin
159+ h := Hash(p, n);
160+ i := h and tableMask;
161+ while table^[i] <> 0 do begin
162+ k := table^[i] - 1;
163+ if (nameHash^[k] = h) and (nameLen^[k] = n)
164+ and (CompareByte(pool[nameOff^[k]], p^, n) = 0) then exit(k);
165+ i := (i + 1) and tableMask;
166+ end;
167+ if poolLen + n > poolCap then begin
168+ poolCap := poolCap * 2 + n;
169+ pool := ReAllocMem(pool, poolCap);
170+ end;
171+ Move(p^, pool[poolLen], n);
172+ k := numNames;
173+ nameOff^[k] := poolLen;
174+ nameLen^[k] := n;
175+ nameHash^[k] := h;
176+ inc(poolLen, n);
177+ inc(numNames);
178+ table^[i] := k + 1;
179+ if numNames * 2 > tableMask then Grow;
180+ Intern := k;
181+end;
182+
183+function NameOf(n: longint): shortstring;
184+var s: shortstring;
185+begin
186+ SetLength(s, nameLen^[n]);
187+ Move(pool[nameOff^[n]], s[1], nameLen^[n]);
188+ NameOf := s;
189+end;
190+
191+{ Errors }
192+
193+{ The current symbol }
194+function TokPos: TPos;
195+begin
196+ TokPos.f := cur.f;
197+ TokPos.a := cur.tokPos;
198+ TokPos.b := cur.pos;
199+end;
200+
201+{ The place just after the symbol before the current one, where a
202+ missing symbol belongs }
203+function AfterPrev: TPos;
204+begin
205+ AfterPrev.f := cur.f;
206+ AfterPrev.a := cur.prevEnd;
207+ AfterPrev.b := cur.prevEnd;
208+end;
209+
210+{ Where to say a symbol is missing: at the current symbol, unless it
211+ starts a later line than the symbol before it, which is more likely
212+ where the missing one belongs }
213+function MissingPos: TPos;
214+var i: longint;
215+begin
216+ MissingPos := TokPos;
217+ for i := cur.prevEnd to cur.tokPos - 1 do
218+ if cur.buf[i] = #10 then MissingPos := AfterPrev;
219+end;
220+
221+{ From the start of p to the end of the symbol before the current one:
222+ the whole of a construct that has just been read }
223+function SpanFrom(const p: TPos): TPos;
224+begin
225+ SpanFrom := p;
226+ SpanFrom.b := cur.prevEnd;
227+end;
228+
229+function CurLine: longint;
230+begin
231+ CurLine := cur.tokLine;
232+end;
233+
234+{ The line and column of byte a of the file, at or before the current
235+ symbol: counted back from the symbol's line, so that it costs only
236+ the distance. A column counts characters, as diag's do. }
237+procedure LineCol(a: longint; out line, col: longint);
238+var i, start: longint;
239+begin
240+ line := cur.tokLine;
241+ start := cur.tokLineStart;
242+ while a < start do begin
243+ dec(line);
244+ dec(start);
245+ while (start > 0) and (cur.buf[start - 1] <> #10) do dec(start);
246+ end;
247+ col := 1;
248+ for i := start to a - 1 do
249+ if (byte(cur.buf[i]) and $C0) <> $80 then inc(col);
250+end;
251+
252+function CurCol: longint;
253+var line: longint;
254+begin
255+ LineCol(cur.tokPos, line, CurCol);
256+end;
257+
258+procedure Mark(const msg: shortstring);
259+begin
260+ MarkAt(TokPos, msg);
261+end;
262+
263+{ After an error in the parser's construct, reported with its notes
264+ and help: the parser goes on from the recovery point. }
265+procedure Fail;
266+begin
267+ if recovery = nil then Finish;
268+ longjmp(recovery^, 1);
269+end;
270+
271+procedure MarkAt(const p: TPos; const msg: shortstring);
272+begin
273+ Error(p, msg);
274+ Fail;
275+end;
276+
277+{ MarkAt, with a line of help after the message. }
278+procedure MarkHelp(const p: TPos; const msg, hint: shortstring);
279+begin
280+ Error(p, msg);
281+ Help(hint);
282+ Fail;
283+end;
284+
285+{ An error in the text at bytes a to b of the file being read, which
286+ stops the compiler: past it, the symbols can't be trusted. }
287+procedure MarkBytes(a, b: longint; const msg: shortstring);
288+var p: TPos;
289+begin
290+ p.f := cur.f; p.a := a; p.b := b;
291+ quiet := false;
292+ Error(p, msg);
293+ Finish;
294+end;
295+
296+procedure LexError(const msg: shortstring);
297+begin
298+ MarkBytes(cur.tokPos, cur.pos, msg);
299+end;
300+
301+{ The n characters at the scanner are how another language writes t:
302+ an error, but reading goes on as if t were written. }
303+procedure Slip(n: longint; t: TSym; const msg: shortstring);
304+var p: TPos;
305+begin
306+ p.f := cur.f; p.a := cur.pos; p.b := cur.pos + n;
307+ if not skipping then Error(p, msg);
308+ inc(cur.pos, n);
309+ tok := t;
310+end;
311+
312+{ How an operator or reserved word is written, quoted, for messages. }
313+function SymText(s: TSym): shortstring;
314+begin
315+ if s in [sPlus..sBlank] then SymText := '"' + Ops[s] + '"'
316+ else SymText := '"' + Words[ord(s) - ord(sAnd)] + '"';
317+end;
318+
319+{ The current symbol, for "expected ..., found ...": a name as it is,
320+ a literal by its kind, an operator or reserved word quoted. }
321+function Found: shortstring;
322+begin
323+ case tok of
324+ sIdent: Found := NameOf(id);
325+ sInt, sReal: Found := 'a number';
326+ sChar: Found := 'a character';
327+ sString: Found := 'a string';
328+ sEof: Found := 'the end of the file';
329+ else Found := SymText(tok);
330+ end;
331+end;
332+
333+{ The current symbol is the first on its line: at the top level of a
334+ module, by the usual layout, so where reading can start again. }
335+function AtLineStart: boolean;
336+begin
337+ AtLineStart := cur.tokPos = cur.tokLineStart;
338+end;
339+
340+{ The column the current symbol's line is indented to }
341+function Indent: longint;
342+var i: longint;
343+begin
344+ i := cur.tokLineStart;
345+ while cur.buf[i] in [' ', #9] do inc(i);
346+ Indent := i - cur.tokLineStart + 1;
347+end;
348+
349+{ Files }
350+
351+{ Name n is a reserved word }
352+function Reserved(n: longint): boolean;
353+begin
354+ Reserved := n < NumWords;
355+end;
356+
357+{ Reads the file at path to scan it; '' if it can, else why not }
358+function Open(const path: shortstring): shortstring;
359+var fd: cint; st: Stat; n, got, r: longint; p: shortstring;
360+begin
361+ p := path + #0;
362+ fd := FpOpen(@p[1], O_RDONLY);
363+ if fd < 0 then
364+ case FpGetErrno of
365+ ESysENOENT: exit('there is no such file');
366+ ESysEACCES: exit('permission denied');
367+ else exit('it can''t be opened');
368+ end;
369+ if FpFStat(fd, st) <> 0 then begin FpClose(fd); exit('it can''t be opened') end;
370+ if (st.st_mode and S_IFMT) <> S_IFREG then begin FpClose(fd); exit('it isn''t a file') end;
371+ n := st.st_size;
372+ cur.buf := GetMem(n + 1);
373+ got := 0;
374+ while got < n do begin
375+ r := FpRead(fd, cur.buf[got], n - got);
376+ if r <= 0 then Fatal('can''t read ' + path);
377+ got := got + r;
378+ end;
379+ FpClose(fd);
380+ cur.buf[n] := #0; { the sentinel that ends every scan }
381+ cur.len := n;
382+ cur.pos := 0;
383+ cur.line := 1;
384+ cur.lineStart := 0;
385+ cur.tokPos := 0;
386+ cur.tokLine := 1;
387+ cur.tokLineStart := 0;
388+ cur.f := AddFile(path, cur.buf, n);
389+ Open := '';
390+end;
391+
392+procedure SaveScan(var st: TScanState);
393+begin
394+ st := cur;
395+ st.tok := tok; st.ival := ival; st.rval := rval; st.id := id;
396+end;
397+
398+procedure RestoreScan(const st: TScanState);
399+begin
400+ cur := st;
401+ tok := st.tok; ival := st.ival; rval := st.rval; id := st.id;
402+end;
403+
404+{ UTF-8 }
405+
406+{ Decodes the character at buf[pos], which is not ASCII, checking that
407+ it is well formed; returns its code point and moves pos past it. }
408+function Utf8(var pos: longint): longint;
409+var b0, b1, n, i, cp: longint; lo, hi: byte;
410+begin
411+ b0 := byte(cur.buf[pos]);
412+ lo := $80; hi := $BF;
413+ case b0 of
414+ $C2..$DF: begin n := 1; cp := b0 and $1F end;
415+ $E0: begin n := 2; cp := 0; lo := $A0 end;
416+ $E1..$EC, $EE, $EF: begin n := 2; cp := b0 and $0F end;
417+ $ED: begin n := 2; cp := $0D; hi := $9F end; { no surrogates }
418+ $F0: begin n := 3; cp := 0; lo := $90 end;
419+ $F1..$F3: begin n := 3; cp := b0 and $07 end;
420+ $F4: begin n := 3; cp := 4; hi := $8F end; { up to 10FFFFH }
421+ else
422+ cur.tokPos := pos;
423+ LexError('invalid UTF-8');
424+ end;
425+ for i := 1 to n do begin
426+ b1 := byte(cur.buf[pos + i]);
427+ if (b1 < lo) or (b1 > hi) or (pos + i >= cur.len) then begin
428+ cur.tokPos := pos;
429+ LexError('bad UTF-8');
430+ end;
431+ cp := cp shl 6 or (b1 and $3F);
432+ lo := $80; hi := $BF;
433+ end;
434+ pos := pos + n + 1;
435+ Utf8 := cp;
436+end;
437+
438+procedure Put(b: longint);
439+begin
440+ if slen >= MaxStr then LexError('a string holds at most ' + IntStr(MaxStr) + ' bytes');
441+ sbuf[slen] := b;
442+ inc(slen);
443+end;
444+
445+procedure PutUtf8(cp: longint);
446+begin
447+ if cp < $80 then Put(cp)
448+ else if cp < $800 then begin
449+ Put($C0 or cp shr 6); Put($80 or cp and $3F)
450+ end else if cp < $10000 then begin
451+ Put($E0 or cp shr 12); Put($80 or cp shr 6 and $3F); Put($80 or cp and $3F)
452+ end else begin
453+ Put($F0 or cp shr 18); Put($80 or cp shr 12 and $3F);
454+ Put($80 or cp shr 6 and $3F); Put($80 or cp and $3F)
455+ end;
456+end;
457+
458+function HexVal(c: char): longint;
459+begin
460+ case c of
461+ '0'..'9': HexVal := ord(c) - ord('0');
462+ 'A'..'F': HexVal := ord(c) - ord('A') + 10;
463+ 'a'..'f': HexVal := ord(c) - ord('a') + 10;
464+ else HexVal := -1;
465+ end;
466+end;
467+
468+{ The text of the file from byte a up to but not including b }
469+function Text(a, b: longint): shortstring;
470+var p: TPos;
471+begin
472+ p.f := cur.f; p.a := a; p.b := b;
473+ Text := Source(p);
474+end;
475+
476+{ One character of a character or string literal, at buf[pos]: its code
477+ point, or for \xHH, minus one minus the byte. }
478+function LitChar(inString: boolean): longint;
479+var c: char; v, d, n, esc, digits: longint;
480+begin
481+ c := cur.buf[cur.pos];
482+ esc := cur.pos;
483+ if c = '\' then begin
484+ inc(cur.pos);
485+ c := cur.buf[cur.pos];
486+ inc(cur.pos);
487+ case c of
488+ 'n': v := 10;
489+ 't': v := 9;
490+ 'r': v := 13;
491+ '0': v := 0;
492+ '\', '''', '"': v := ord(c);
493+ 'x': begin
494+ if not inString then MarkBytes(esc, cur.pos, '\x is only for strings');
495+ d := HexVal(cur.buf[cur.pos]);
496+ n := HexVal(cur.buf[cur.pos + 1]);
497+ if (d < 0) or (n < 0) then MarkBytes(esc, cur.pos + 2, '\x needs two hex digits');
498+ inc(cur.pos, 2);
499+ v := -1 - (d * 16 + n);
500+ end;
501+ 'u': begin
502+ if cur.buf[cur.pos] <> '{' then MarkBytes(esc, cur.pos, 'expected "{" after \u');
503+ inc(cur.pos);
504+ digits := cur.pos;
505+ v := 0; n := 0;
506+ while HexVal(cur.buf[cur.pos]) >= 0 do begin
507+ v := v * 16 + HexVal(cur.buf[cur.pos]);
508+ inc(n); inc(cur.pos);
509+ if n > 6 then MarkBytes(esc, cur.pos, 'a code point has at most 6 hex digits');
510+ end;
511+ if (n = 0) or (cur.buf[cur.pos] <> '}') then MarkBytes(esc, cur.pos, 'expected hex digits and "}" after \u{');
512+ inc(cur.pos);
513+ if (v > $10FFFF) or ((v >= $D800) and (v <= $DFFF)) then
514+ MarkBytes(esc, cur.pos, Text(digits, cur.pos - 1) + ' isn''t a code point');
515+ end;
516+ else MarkBytes(esc, cur.pos, 'unknown escape \' + c);
517+ end;
518+ end else if byte(c) >= $80 then
519+ v := Utf8(cur.pos)
520+ else if (c < ' ') or (c = #127) then
521+ if inString then LexError('string not closed')
522+ else LexError('character not closed')
523+ else begin
524+ v := ord(c);
525+ inc(cur.pos);
526+ end;
527+ LitChar := v;
528+end;
529+
530+{ Symbols }
531+
532+procedure Comment;
533+var depth, open: longint; c: char;
534+begin
535+ depth := 1;
536+ open := cur.pos;
537+ inc(cur.pos, 2);
538+ repeat
539+ c := cur.buf[cur.pos];
540+ if c = #0 then begin
541+ if cur.pos >= cur.len then MarkBytes(open, open + 2, 'comment not closed');
542+ inc(cur.pos);
543+ end else if (c = '(') and (cur.buf[cur.pos + 1] = '*') then begin
544+ inc(depth); inc(cur.pos, 2)
545+ end else if (c = '*') and (cur.buf[cur.pos + 1] = ')') then begin
546+ dec(depth); inc(cur.pos, 2)
547+ end else if c = #10 then begin
548+ inc(cur.pos); inc(cur.line); cur.lineStart := cur.pos
549+ end else if byte(c) >= $80 then
550+ Utf8(cur.pos)
551+ else
552+ inc(cur.pos);
553+ until depth = 0;
554+end;
555+
556+{ Reading a decimal real exactly: the F64 nearest to digits times 10 to
557+ an exponent, ties to the even one, which a library's Val doesn't
558+ promise. The number is a fraction of two big integers, num / den,
559+ scaled by 2^e until its whole part has 53 or 54 bits; that part and
560+ the remainder give the bits and the rounding. }
561+type
562+ TBig = record
563+ n: longint; { words in use; 0 is zero }
564+ w: array[0..95] of longword; { least significant first }
565+ end;
566+ { 96 words, 3072 bits, are plenty: a shortstring holds at most 255
567+ digits, so ReadReal's den is at most 10^(330 + 255), about 2^1944,
568+ and num below 10^310; the shift that follows makes the larger one at
569+ most 54 bits longer than den, about 2000 bits in all. }
570+
571+{ a := a * m + add }
572+procedure BigMul(var a: TBig; m, add: longword);
573+var i: longint; c: qword;
574+begin
575+ c := add;
576+ for i := 0 to a.n - 1 do begin
577+ c := qword(a.w[i]) * m + c;
578+ a.w[i] := longword(c);
579+ c := c shr 32;
580+ end;
581+ if c <> 0 then begin a.w[a.n] := longword(c); inc(a.n) end;
582+end;
583+
584+procedure BigShl(var a: TBig; k: longint);
585+var i, words, bits: longint;
586+begin
587+ if a.n = 0 then exit;
588+ words := k div 32; bits := k mod 32;
589+ a.w[a.n + words] := 0;
590+ for i := a.n - 1 downto 0 do begin
591+ if bits > 0 then a.w[i + words + 1] := a.w[i + words + 1] or (a.w[i] shr (32 - bits));
592+ a.w[i + words] := a.w[i] shl bits;
593+ end;
594+ for i := 0 to words - 1 do a.w[i] := 0;
595+ inc(a.n, words + 1);
596+ while (a.n > 0) and (a.w[a.n - 1] = 0) do dec(a.n);
597+end;
598+
599+procedure BigShr1(var a: TBig);
600+var i: longint;
601+begin
602+ for i := 0 to a.n - 1 do begin
603+ a.w[i] := a.w[i] shr 1;
604+ if i + 1 < a.n then a.w[i] := a.w[i] or (a.w[i + 1] shl 31);
605+ end;
606+ while (a.n > 0) and (a.w[a.n - 1] = 0) do dec(a.n);
607+end;
608+
609+function BigCmp(const a, b: TBig): longint;
610+var i: longint;
611+begin
612+ if a.n <> b.n then exit(ord(a.n > b.n) * 2 - 1);
613+ for i := a.n - 1 downto 0 do
614+ if a.w[i] <> b.w[i] then exit(ord(a.w[i] > b.w[i]) * 2 - 1);
615+ BigCmp := 0;
616+end;
617+
618+{ a := a - b, b not above a }
619+procedure BigSub(var a: TBig; const b: TBig);
620+var i: longint; d: int64;
621+begin
622+ d := 0;
623+ for i := 0 to a.n - 1 do begin
624+ d := d + a.w[i];
625+ if i < b.n then d := d - b.w[i];
626+ a.w[i] := longword(d);
627+ d := -ord(d < 0); { a borrow }
628+ end;
629+ while (a.n > 0) and (a.w[a.n - 1] = 0) do dec(a.n);
630+end;
631+
632+function BigBits(const a: TBig): longint;
633+var t: longword;
634+begin
635+ if a.n = 0 then exit(0);
636+ BigBits := (a.n - 1) * 32;
637+ t := a.w[a.n - 1];
638+ while t <> 0 do begin inc(BigBits); t := t shr 1 end;
639+end;
640+
641+{ s is digits, a point, digits, and maybe E, a sign and digits. False if
642+ the value is past the largest F64; one below the smallest is 0. }
643+function ReadReal(const s: shortstring; out x: double): boolean;
644+var
645+ num, den, d: TBig; i, digits, e, ex: longint; neg, half, sticky: boolean;
646+ q, b: qword;
647+begin
648+ num.n := 0; den.n := 1; den.w[0] := 1;
649+ digits := 0; e := 0; i := 1;
650+ while (i <= length(s)) and (s[i] <> 'E') do begin
651+ if s[i] = '.' then e := 1
652+ else begin
653+ BigMul(num, 10, ord(s[i]) - ord('0'));
654+ if num.n > 0 then inc(digits); { counted from the first that isn't 0 }
655+ if e > 0 then inc(e);
656+ end;
657+ inc(i);
658+ end;
659+ if e > 0 then e := 1 - e; { minus the digits after the point }
660+ ex := 0; neg := false;
661+ if i <= length(s) then begin
662+ inc(i);
663+ neg := s[i] = '-';
664+ if s[i] in ['+', '-'] then inc(i);
665+ for i := i to length(s) do
666+ if ex < 100000 then ex := ex * 10 + ord(s[i]) - ord('0');
667+ end;
668+ if neg then ex := -ex;
669+ inc(e, ex);
670+ x := 0.0;
671+ if num.n = 0 then exit(true);
672+ if digits + e > 310 then exit(false); { 10^310 is past every F64 }
673+ if digits + e < -330 then exit(true); { and 10^-330 below half the least }
674+ for i := 1 to e do BigMul(num, 10, 0);
675+ for i := 1 to -e do BigMul(den, 10, 0);
676+ { num / den 2^-e from 2^52 to 2^54, but not past the least exponent }
677+ e := BigBits(num) - BigBits(den) - 53;
678+ if e < -1074 then e := -1074;
679+ if e < 0 then BigShl(num, -e) else BigShl(den, e);
680+ { q, its whole part, by long division; num is left the remainder }
681+ d := den; BigShl(d, 53);
682+ q := 0;
683+ for i := 53 downto 0 do begin
684+ if BigCmp(num, d) >= 0 then begin BigSub(num, d); q := q or (qword(1) shl i) end;
685+ BigShr1(d);
686+ end;
687+ if q >= qword(1) shl 53 then begin { a bit too many: it rounds }
688+ half := odd(q); sticky := num.n > 0;
689+ q := q shr 1; inc(e);
690+ end else begin { the remainder against half of den }
691+ BigShl(num, 1);
692+ i := BigCmp(num, den);
693+ half := i >= 0; sticky := i > 0;
694+ end;
695+ if half and (sticky or odd(q)) then begin
696+ inc(q);
697+ if q = qword(1) shl 53 then begin q := q shr 1; inc(e) end;
698+ end;
699+ if e > 971 then exit(false);
700+ if q >= qword(1) shl 52 then b := qword(e + 1075) shl 52 or (q and (qword(1) shl 52 - 1))
701+ else b := q; { below the least normal, e is -1074 }
702+ Move(b, x, 8);
703+ ReadReal := true;
704+end;
705+
706+procedure Number;
707+var start, i, d: longint; allDec: boolean; v: qword; s: shortstring;
708+begin
709+ start := cur.pos;
710+ allDec := true;
711+ while cur.buf[cur.pos] in ['0'..'9', 'A'..'F'] do begin
712+ if cur.buf[cur.pos] > '9' then allDec := false;
713+ inc(cur.pos);
714+ end;
715+ if cur.buf[cur.pos] = 'H' then begin
716+ v := 0;
717+ for i := start to cur.pos - 1 do begin
718+ if v shr 60 <> 0 then LexError(Text(start, cur.pos) + ' is too big for U64');
719+ v := v * 16 + qword(HexVal(cur.buf[i]));
720+ end;
721+ inc(cur.pos);
722+ tok := sInt;
723+ ival := int64(v); { 16 digits are the bits of a 64-bit word }
724+ end else if (cur.buf[cur.pos] = '.') and (cur.buf[cur.pos + 1] in ['0'..'9']) then begin
725+ if not allDec then LexError('a decimal number has only the digits 0 to 9');
726+ inc(cur.pos);
727+ while cur.buf[cur.pos] in ['0'..'9'] do inc(cur.pos);
728+ if cur.buf[cur.pos] = 'E' then begin
729+ inc(cur.pos);
730+ if cur.buf[cur.pos] in ['+', '-'] then inc(cur.pos);
731+ if not (cur.buf[cur.pos] in ['0'..'9']) then LexError('expected a digit in the exponent');
732+ while cur.buf[cur.pos] in ['0'..'9'] do inc(cur.pos);
733+ end;
734+ if cur.pos - start > 255 then LexError('a number has at most 255 characters');
735+ SetLength(s, cur.pos - start);
736+ Move(cur.buf[start], s[1], cur.pos - start);
737+ if not ReadReal(s, rval) then LexError(Text(start, cur.pos) + ' is out of the range of F64');
738+ tok := sReal;
739+ end else begin
740+ if not allDec then LexError('a hex number ends with H');
741+ v := 0;
742+ for i := start to cur.pos - 1 do begin
743+ d := ord(cur.buf[i]) - ord('0');
744+ if v > (qword(high(int64)) - qword(d)) div 10 then LexError(Text(start, cur.pos) + ' is too big for I64');
745+ v := v * 10 + qword(d);
746+ end;
747+ tok := sInt;
748+ ival := int64(v);
749+ end;
750+ if cur.buf[cur.pos] in ['A'..'Z', 'a'..'z', '_', '0'..'9'] then
751+ LexError('a name can''t start with a digit');
752+end;
753+
754+procedure Next;
755+var c: char; start, h, v, i: longint;
756+begin
757+ cur.prevEnd := cur.pos;
758+ repeat
759+ c := cur.buf[cur.pos];
760+ while c in [' ', #9, #13, #10] do begin
761+ if c = #10 then begin
762+ inc(cur.line); cur.lineStart := cur.pos + 1
763+ end;
764+ inc(cur.pos);
765+ c := cur.buf[cur.pos];
766+ end;
767+ if (c = '(') and (cur.buf[cur.pos + 1] = '*') then begin
768+ Comment; c := ' '
769+ end;
770+ until c <> ' ';
771+ cur.tokPos := cur.pos;
772+ cur.tokLine := cur.line;
773+ cur.tokLineStart := cur.lineStart;
774+ case c of
775+ 'A'..'Z', 'a'..'z', '_': begin
776+ start := cur.pos;
777+ repeat inc(cur.pos)
778+ until not (cur.buf[cur.pos] in ['A'..'Z', 'a'..'z', '0'..'9', '_']);
779+ if cur.pos - start > MaxIdent then LexError('a name has at most ' + IntStr(MaxIdent) + ' characters');
780+ h := Intern(@cur.buf[start], cur.pos - start);
781+ if (cur.pos - start = 1) and (c = '_') then tok := sBlank
782+ else if h < NumWords then tok := TSym(ord(sAnd) + h)
783+ else begin tok := sIdent; id := h end;
784+ end;
785+ '0'..'9': Number;
786+ '''': begin
787+ inc(cur.pos);
788+ if cur.buf[cur.pos] = '''' then LexError('empty character');
789+ v := LitChar(false);
790+ if cur.buf[cur.pos] <> '''' then begin
791+ { 'ab': several characters, as some languages write a string }
792+ i := cur.pos;
793+ while not (cur.buf[i] in ['''', #10, #0]) do inc(i);
794+ if cur.buf[i] = '''' then MarkBytes(cur.tokPos, i + 1, 'a character is one character: the string is "' + Text(cur.tokPos + 1, i) + '"')
795+ else LexError('character not closed');
796+ end;
797+ inc(cur.pos);
798+ tok := sChar;
799+ ival := v;
800+ end;
801+ '"': begin
802+ inc(cur.pos);
803+ slen := 0;
804+ while cur.buf[cur.pos] <> '"' do begin
805+ v := LitChar(true);
806+ if v < 0 then Put(-1 - v) else PutUtf8(v);
807+ end;
808+ inc(cur.pos);
809+ sbuf[slen] := 0;
810+ tok := sString;
811+ end;
812+ '+': begin inc(cur.pos); tok := sPlus end;
813+ '-': begin inc(cur.pos); tok := sMinus end;
814+ '*': begin inc(cur.pos); tok := sTimes end;
815+ '/': begin inc(cur.pos); tok := sSlash end;
816+ '=':
817+ if cur.buf[cur.pos + 1] = '=' then Slip(2, sEql, 'comparing is written =, not ==')
818+ else begin inc(cur.pos); tok := sEql end;
819+ '&':
820+ if cur.buf[cur.pos + 1] = '&' then Slip(2, sAnd, '"and" is written and, not &&')
821+ else begin inc(cur.pos); tok := sAmp end;
822+ '#': begin inc(cur.pos); tok := sNeq end;
823+ '<': begin
824+ inc(cur.pos);
825+ if cur.buf[cur.pos] = '=' then begin inc(cur.pos); tok := sLeq end
826+ else tok := sLss;
827+ end;
828+ '>': begin
829+ inc(cur.pos);
830+ if cur.buf[cur.pos] = '=' then begin inc(cur.pos); tok := sGeq end
831+ else tok := sGtr;
832+ end;
833+ ':': begin
834+ inc(cur.pos);
835+ if cur.buf[cur.pos] = '=' then begin inc(cur.pos); tok := sBecomes end
836+ else tok := sColon;
837+ end;
838+ ';': begin inc(cur.pos); tok := sSemicolon end;
839+ ',': begin inc(cur.pos); tok := sComma end;
840+ '.': begin
841+ inc(cur.pos);
842+ if cur.buf[cur.pos] = '.' then begin
843+ inc(cur.pos);
844+ if cur.buf[cur.pos] = '.' then begin inc(cur.pos); tok := sEllipsis end
845+ else tok := sUpto;
846+ end else tok := sPeriod;
847+ end;
848+ '(': begin inc(cur.pos); tok := sLparen end;
849+ ')': begin inc(cur.pos); tok := sRparen end;
850+ '[': begin inc(cur.pos); tok := sLbrak end;
851+ ']': begin inc(cur.pos); tok := sRbrak end;
852+ '{': begin inc(cur.pos); tok := sLbrace end;
853+ '}': begin inc(cur.pos); tok := sRbrace end;
854+ '^': begin inc(cur.pos); tok := sArrow end;
855+ '|':
856+ if cur.buf[cur.pos + 1] = '|' then Slip(2, sOr, '"or" is written or, not ||')
857+ else begin inc(cur.pos); tok := sBar end;
858+ '~': begin inc(cur.pos); tok := sTilde end;
859+ '!':
860+ if cur.buf[cur.pos + 1] = '=' then Slip(2, sNeq, '"not equal" is written #, not !=')
861+ else Slip(1, sNot, '"not" is written not, not !');
862+ #0: begin
863+ if cur.pos < cur.len then MarkBytes(cur.pos, cur.pos + 1, 'NUL byte in the text');
864+ tok := sEof;
865+ end;
866+ else
867+ if byte(c) >= $80 then
868+ LexError('only ASCII outside strings, characters and comments');
869+ MarkBytes(cur.pos, cur.pos + 1, 'unexpected character "' + c + '"');
870+ end;
871+end;
872+
873+var i: longint;
874+
875+initialization
876+ poolCap := 1 shl 16;
877+ pool := GetMem(poolCap);
878+ nameCap := 1 shl 12;
879+ nameOff := GetMem(nameCap * 4);
880+ nameLen := GetMem(nameCap * 4);
881+ nameHash := GetMem(nameCap * 4);
882+ tableMask := 2 * nameCap - 1;
883+ table := GetMem((tableMask + 1) * 4);
884+ FillChar(table^, (tableMask + 1) * 4, 0);
885+ for i := 0 to NumWords - 1 do Intern(@Words[i][1], length(Words[i]));
886+end.

seed/sym.pas added +646 -0

@@ -0,0 +1,646 @@
1+{ sym.pas: types, objects and scopes.
2+
3+ Every name the program declares becomes an object (TObj): a constant,
4+ type, variable, procedure, module, record field, variant case or
5+ built-in. Every type is a TType. Objects are found through one hash
6+ table keyed by scope and name, so a lookup costs the same however
7+ big a module grows. A scope is just a number: the universe is 0,
8+ and each module, procedure, record and match arm gets a fresh one.
9+
10+ Depends on: scan, for names and errors.
11+ Leaves out: code. Where a variable lives is decided here (frame
12+ offsets, chunk numbers), but nothing is emitted. }
13+
14+unit sym;
15+
16+{$mode objfpc}{$H-}
17+
18+interface
19+
20+uses scan, diag;
21+
22+type
23+ TForm = (fNone, fBool, fInt, fReal, fConst, fNil, fStr, fPtr, fArray,
24+ fSlice, fRecord, fVariant, fProc, fEnum, fSet, fError);
25+ { fConst is the type of an untyped integer constant; fStr of a string
26+ literal, whose length the literal carries. F32 and F64 are fReal,
27+ told apart by size, and so is tRConst, an untyped real constant. }
28+
29+ TClass = (oConst, oType, oVar, oProc, oModule, oField, oCase, oBuiltin);
30+
31+ PType = ^TType;
32+ PObj = ^TObj;
33+ PModule = ^TModule;
34+ PImport = ^TImport;
35+ PLib = ^TLib;
36+
37+ TType = record
38+ form: TForm;
39+ size, align: int64;
40+ signed: boolean; { fInt }
41+ vol: boolean; { fPtr: ^VOLATILE }
42+ packd: boolean; { fRecord }
43+ variadic: boolean; { fProc: ends in ... }
44+ tuple: boolean; { fRecord: the results of a procedure that has several }
45+ base: PType; { fPtr, fArray, fSlice: what it holds; fProc: result }
46+ len: int64; { fArray: elements; fProc: parameters; fVariant: cases; a tuple: results }
47+ fields: PObj; { fRecord: fields; fVariant: cases; fProc: parameters }
48+ scope: longint; { fRecord: the scope of its fields }
49+ fwd: longint; { fPtr whose base isn't declared yet: its name, else -1 }
50+ obj: PObj; { the declaration that names it, or nil }
51+ module: PModule; { the module that built it }
52+ end;
53+
54+ TObj = record
55+ cls: TClass;
56+ name: longint;
57+ exported: boolean;
58+ typ: PType;
59+ next: PObj; { the next in its list: scope, fields, parameters }
60+ scope: longint; { where it is declared }
61+ pos: TPos; { where its name is declared, for messages }
62+ val: int64; { oConst: value; oBuiltin: which; oCase: tag;
63+ oField: offset; oVar: frame offset }
64+ chunk: longint; { global oVar, oProc, string oConst: its chunk }
65+ lev: integer; { oVar: 0 for a module variable, 1 for a local }
66+ ind: boolean; { oVar: the frame slot holds the variable's address }
67+ off: int64; { oVar with ind: added to that address }
68+ isVar: boolean; { a var parameter }
69+ param: boolean; { oVar: a parameter }
70+ used: boolean; { named somewhere but in its own body }
71+ read: boolean; { oVar: named other than as what := assigns }
72+ fwd: boolean; { oProc: declared forward, no body yet }
73+ isCode: boolean; { oProc: a code procedure }
74+ openEnd: boolean; { oProc: has results, and may reach its end }
75+ reg: longint; { oVar: the register it lives in, or 0 if in memory;
76+ for a slice, the one its pointer is in }
77+ reg2: longint; { oVar: a slice in registers: the one its length is in }
78+ ext: boolean; { oProc, oVar: C's, reached through its chunk, which
79+ holds its address }
80+ fields: PObj; { oCase: its fields }
81+ module: PModule; { oModule: the module; others: where declared }
82+ link: PObj; { the next declaration of its module, top-level or
83+ local }
84+ end;
85+
86+ { The arguments of a generic module's instance: a type, or a
87+ procedure (o) and its type. }
88+ TArgs = record
89+ n: longint;
90+ t: array[0..7] of PType;
91+ o: array[0..7] of PObj;
92+ pos: array[0..7] of TPos; { where each argument is, for messages }
93+ at: TPos; { where the import is }
94+ end;
95+
96+ TImport = record
97+ module: PModule;
98+ next: PImport;
99+ end;
100+
101+ { A library a module links, by its name, as interned }
102+ TLib = record
103+ name: longint;
104+ next: PLib;
105+ end;
106+
107+ TModule = record
108+ name: longint;
109+ sname: longint; { the name of its symbols: List(I64) for an instance }
110+ args: TArgs;
111+ scope: longint;
112+ path: shortstring;
113+ first, last: PObj; { its top-level declarations, in order }
114+ locals, lastLocal: PObj; { its procedures' declarations, in order }
115+ imports: PImport;
116+ body: longint; { the chunk of its body, or -1 }
117+ done: boolean; { compiled to the end }
118+ checkOnly: boolean; { read only to check another file's interface }
119+ used: boolean; { imported, through others, by the main module }
120+ usesC: boolean; { has an extern, or links a library }
121+ linkStatic: boolean; { says link static }
122+ libs: PLib; { the libraries it links }
123+ next: PModule; { modules in the order they were finished }
124+ end;
125+
126+const
127+ { built-in procedures }
128+ bSize = 0; bAdr = 1; bLen = 2; bNew = 3; bMsg = 4; bSyscall = 5;
129+ bFence = 6; bCas = 7; bXchg = 8; bXadd = 9; bArgc = 10; bArgv = 11;
130+ bInc = 12; bDec = 13; bCopy = 14;
131+
132+ MaxDepth = 64; { scopes open at once }
133+
134+var
135+ tI8, tI16, tI32, tI64, tU8, tU16, tU32, tU64: PType;
136+ tInt, tUInt: PType; { INT and UINT, as big as an address: 8 bytes here }
137+ tBool, tF32, tReal, tRConst, tError, tConst, tNil, tStr, tNone, tPtrU8, tBytes: PType;
138+ tPoison: PType; { of a name reported as not declared }
139+ curModule: PModule;
140+
141+function NewType(form: TForm; size, align: int64): PType;
142+function NewObj(cls: TClass; name: longint; typ: PType): PObj;
143+function NewScope: longint;
144+procedure OpenScope(s: longint);
145+procedure CloseScope;
146+function ScopeDepth: longint;
147+procedure CutScopes(d: longint);
148+function TopScope: longint;
149+procedure SaveScopes(var d: longint; var saved: array of longint);
150+procedure RestoreScopes(d: longint; const saved: array of longint);
151+procedure Insert(obj: PObj; s: longint);
152+function Find(s, name: longint): PObj;
153+function Lookup(name: longint): PObj;
154+function Closest(name, s: longint): PObj;
155+
156+function AlignUp(x, a: int64): int64;
157+function Same(a, b: PType): boolean;
158+function IsInt(t: PType): boolean;
159+function IsScalar(t: PType): boolean;
160+function IsAggregate(t: PType): boolean;
161+function InTwoRegs(t: PType): boolean;
162+function BehindPointer(t: PType): boolean;
163+function Fits(v: int64; t: PType): boolean;
164+function TypeName(t: PType): shortstring;
165+function Fingerprint(o: PObj): qword;
166+
167+implementation
168+
169+uses math;
170+
171+type
172+ PObjTab = ^TObjTab;
173+ TObjTab = array[0..MaxInt div 16] of PObj;
174+
175+var
176+ scopes: array[0..MaxDepth - 1] of longint;
177+ depth: longint;
178+ nextScope: longint;
179+ hashTab: PObjTab;
180+ hashMask, hashCount: longint;
181+
182+function NewType(form: TForm; size, align: int64): PType;
183+var t: PType;
184+begin
185+ New(t);
186+ FillChar(t^, SizeOf(TType), 0);
187+ t^.form := form;
188+ t^.size := size;
189+ t^.align := align;
190+ t^.fwd := -1;
191+ t^.module := curModule;
192+ NewType := t;
193+end;
194+
195+function NewObj(cls: TClass; name: longint; typ: PType): PObj;
196+var o: PObj;
197+begin
198+ New(o);
199+ FillChar(o^, SizeOf(TObj), 0);
200+ o^.cls := cls;
201+ o^.name := name;
202+ o^.typ := typ;
203+ o^.chunk := -1;
204+ o^.module := curModule;
205+ o^.pos := TokPos;
206+ NewObj := o;
207+end;
208+
209+{ Scopes }
210+
211+function NewScope: longint;
212+begin
213+ inc(nextScope);
214+ NewScope := nextScope;
215+end;
216+
217+procedure OpenScope(s: longint);
218+begin
219+ if depth = MaxDepth then Mark('scopes nested more than ' + IntStr(MaxDepth) + ' deep');
220+ scopes[depth] := s;
221+ inc(depth);
222+end;
223+
224+procedure CloseScope;
225+begin
226+ dec(depth);
227+end;
228+
229+{ An imported module is compiled in the middle of another, and must
230+ see only the universe and itself. }
231+procedure SaveScopes(var d: longint; var saved: array of longint);
232+var i: longint;
233+begin
234+ d := depth;
235+ for i := 0 to depth - 1 do saved[i] := scopes[i];
236+ depth := 1;
237+end;
238+
239+procedure RestoreScopes(d: longint; const saved: array of longint);
240+var i: longint;
241+begin
242+ depth := d;
243+ for i := 0 to depth - 1 do scopes[i] := saved[i];
244+end;
245+
246+function ScopeDepth: longint;
247+begin
248+ ScopeDepth := depth;
249+end;
250+
251+{ Closes the scopes opened since there were d, after an error }
252+procedure CutScopes(d: longint);
253+begin
254+ depth := d;
255+end;
256+
257+function TopScope: longint;
258+begin
259+ TopScope := scopes[depth - 1];
260+end;
261+
262+{ Where the search for name in scope s starts in the hash table: each
263+ number is multiplied by an odd constant near 2^32 or 2^16 over the
264+ golden ratio (Knuth's multiplicative hashing), which spreads the low
265+ bits the mask keeps. }
266+function Slot(s, name: longint): longint;
267+begin
268+ Slot := longint((longword(s) * 2654435761 xor longword(name) * 40503) and longword(hashMask));
269+end;
270+
271+{ Doubles the table, which Insert keeps at most half full so that the
272+ linear probing stays short, and puts every entry in its new slot. }
273+procedure Rehash;
274+var old: PObjTab; n, i, j: longint;
275+begin
276+ old := hashTab;
277+ n := hashMask + 1;
278+ hashMask := n * 2 - 1;
279+ hashTab := GetMem(n * 2 * SizeOf(PObj));
280+ FillChar(hashTab^, n * 2 * SizeOf(PObj), 0);
281+ for i := 0 to n - 1 do
282+ if old^[i] <> nil then begin
283+ j := Slot(old^[i]^.scope, old^[i]^.name);
284+ while hashTab^[j] <> nil do j := (j + 1) and hashMask;
285+ hashTab^[j] := old^[i];
286+ end;
287+ FreeMem(old);
288+end;
289+
290+procedure Insert(obj: PObj; s: longint);
291+var i: longint; o: PObj;
292+begin
293+ i := Slot(s, obj^.name);
294+ o := hashTab^[i];
295+ while o <> nil do begin
296+ if (o^.scope = s) and (o^.name = obj^.name) then begin
297+ Error(obj^.pos, NameOf(obj^.name) + ' is declared twice');
298+ Note(o^.pos, 'the first one is here');
299+ Fail;
300+ end;
301+ i := (i + 1) and hashMask;
302+ o := hashTab^[i];
303+ end;
304+ obj^.scope := s;
305+ hashTab^[i] := obj;
306+ inc(hashCount);
307+ if hashCount * 2 > hashMask then Rehash;
308+end;
309+
310+function Find(s, name: longint): PObj;
311+var i: longint; o: PObj;
312+begin
313+ i := Slot(s, name);
314+ o := hashTab^[i];
315+ while o <> nil do begin
316+ if (o^.scope = s) and (o^.name = name) then exit(o);
317+ i := (i + 1) and hashMask;
318+ o := hashTab^[i];
319+ end;
320+ Find := nil;
321+end;
322+
323+function Lookup(name: longint): PObj;
324+var i: longint; o: PObj;
325+begin
326+ for i := depth - 1 downto 0 do begin
327+ o := Find(scopes[i], name);
328+ if o <> nil then exit(o);
329+ end;
330+ Lookup := nil;
331+end;
332+
333+{ How far apart two names are: the edits, a character put in, taken out,
334+ changed or swapped with the next, that make one the other, ignoring
335+ case. }
336+function Distance(const a, b: shortstring): longint;
337+var d: array[0..MaxIdent + 1, 0..MaxIdent + 1] of longint; i, j, c: longint;
338+begin
339+ for i := 0 to length(a) do d[i, 0] := i;
340+ for j := 0 to length(b) do d[0, j] := j;
341+ for i := 1 to length(a) do
342+ for j := 1 to length(b) do begin
343+ c := ord(UpCase(a[i]) <> UpCase(b[j]));
344+ d[i, j] := Min(Min(d[i - 1, j] + 1, d[i, j - 1] + 1), d[i - 1, j - 1] + c);
345+ if (i > 1) and (j > 1) and (UpCase(a[i]) = UpCase(b[j - 1]))
346+ and (UpCase(a[i - 1]) = UpCase(b[j])) then
347+ d[i, j] := Min(d[i, j], d[i - 2, j - 2] + 1);
348+ end;
349+ Distance := d[length(a), length(b)];
350+end;
351+
352+{ The name spelled most like name, for "did you mean": in scope s, if
353+ it can be reached from here, or in the scopes in reach if s < 0; nil
354+ if none is within an edit for every three characters. Only after an
355+ error, so it looks at every object. }
356+function Closest(name, s: longint): PObj;
357+var i, j, d, best: longint; o: PObj; n: shortstring; reach: boolean;
358+begin
359+ n := NameOf(name);
360+ best := length(n) div 3 + 1;
361+ Closest := nil;
362+ for i := 0 to hashMask do begin
363+ o := hashTab^[i];
364+ if (o = nil) or (o^.name = name) or (o^.name < 0) or (o^.typ = tPoison) then continue;
365+ if s >= 0 then reach := (o^.scope = s) and (o^.exported or (o^.module = curModule))
366+ else begin
367+ reach := false;
368+ for j := 0 to depth - 1 do reach := reach or (o^.scope = scopes[j]);
369+ end;
370+ if reach then begin
371+ d := Distance(n, NameOf(o^.name));
372+ if d < best then begin best := d; Closest := o end;
373+ end;
374+ end;
375+end;
376+
377+{ Types }
378+
379+function AlignUp(x, a: int64): int64;
380+begin
381+ AlignUp := (x + a - 1) div a * a;
382+end;
383+
384+function IsInt(t: PType): boolean;
385+begin
386+ IsInt := t^.form in [fInt, fConst];
387+end;
388+
389+function IsScalar(t: PType): boolean;
390+begin
391+ IsScalar := t^.form in [fBool, fInt, fReal, fConst, fNil, fPtr, fProc,
392+ fEnum, fSet, fError];
393+end;
394+
395+function IsAggregate(t: PType): boolean;
396+begin
397+ IsAggregate := t^.form in [fArray, fSlice, fRecord, fVariant];
398+end;
399+
400+{ Whether a procedure's result t is two words, which come back in rax
401+ and rdx, as System V returns a struct of two integers: a slice (its
402+ pointer, then its length), or two results that are each a single
403+ value of 8 bytes at most and not a real. }
404+function InTwoRegs(t: PType): boolean;
405+
406+ function OneWord(f: PObj): boolean;
407+ begin
408+ OneWord := IsScalar(f^.typ) and (f^.typ^.form <> fReal) and (f^.typ^.size <= 8);
409+ end;
410+
411+begin
412+ if t^.form = fSlice then exit(true);
413+ InTwoRegs := t^.tuple and (t^.len = 2) and OneWord(t^.fields) and OneWord(t^.fields^.next);
414+end;
415+
416+{ Whether a procedure's result t comes back in memory the caller
417+ provides, whose address the caller passes as a hidden first argument,
418+ in rdi: any result that is neither one value, in rax or xmm0, nor two
419+ words, in rax and rdx. }
420+function BehindPointer(t: PType): boolean;
421+begin
422+ BehindPointer := IsAggregate(t) and not InTwoRegs(t);
423+end;
424+
425+function Fits(v: int64; t: PType): boolean;
426+begin
427+ if t^.form <> fInt then exit(t^.form = fConst);
428+ case t^.size of
429+ 1: if t^.signed then Fits := (v >= -128) and (v <= 127)
430+ else Fits := (v >= 0) and (v <= 255);
431+ 2: if t^.signed then Fits := (v >= -32768) and (v <= 32767)
432+ else Fits := (v >= 0) and (v <= 65535);
433+ 4: if t^.signed then Fits := (v >= -2147483648) and (v <= 2147483647)
434+ else Fits := (v >= 0) and (v <= 4294967295);
435+ else Fits := t^.signed or (v >= 0);
436+ end;
437+end;
438+
439+{ Structural sameness of two types. Named types are the same only if
440+ they are one declaration; a type with no name is the same as another
441+ built alike. }
442+function Alike(a, b: PType): boolean;
443+var p, q: PObj;
444+begin
445+ if a = b then exit(true);
446+ if a^.form <> b^.form then exit(false);
447+ case a^.form of
448+ fPtr: Alike := (a^.vol = b^.vol) and Same(a^.base, b^.base);
449+ fArray: Alike := (a^.len = b^.len) and Same(a^.base, b^.base);
450+ fSlice, fSet: Alike := Same(a^.base, b^.base);
451+ fProc, fRecord: begin
452+ { a record is the same only as itself, but for several results }
453+ if (a^.form = fRecord) and not (a^.tuple and b^.tuple) then exit(false);
454+ if (a^.len <> b^.len) or (a^.variadic <> b^.variadic) then exit(false);
455+ if (a^.base = nil) <> (b^.base = nil) then exit(false);
456+ if (a^.base <> nil) and not Same(a^.base, b^.base) then exit(false);
457+ p := a^.fields; q := b^.fields;
458+ while p <> nil do begin
459+ if (p^.isVar <> q^.isVar) or not Same(p^.typ, q^.typ) then exit(false);
460+ p := p^.next; q := q^.next;
461+ end;
462+ Alike := true;
463+ end;
464+ else Alike := false;
465+ end;
466+end;
467+
468+function Same(a, b: PType): boolean;
469+begin
470+ if a = b then exit(true);
471+ if (a = nil) or (b = nil) then exit(false);
472+ if (a^.obj <> nil) and (b^.obj <> nil) then exit(false);
473+ Same := Alike(a, b);
474+end;
475+
476+function TypeName(t: PType): shortstring;
477+var s: shortstring; f: PObj;
478+begin
479+ if t = nil then exit('nothing');
480+ if t^.obj <> nil then begin
481+ if (t^.obj^.module <> nil) and (t^.obj^.module <> curModule) then
482+ exit(NameOf(t^.obj^.module^.sname) + '.' + NameOf(t^.obj^.name));
483+ exit(NameOf(t^.obj^.name));
484+ end;
485+ case t^.form of
486+ fConst: TypeName := 'an integer constant';
487+ fReal: TypeName := 'a real constant';
488+ fNil: TypeName := 'nil';
489+ fStr: TypeName := 'a string';
490+ fPtr: if t^.vol then TypeName := '^VOLATILE ' + TypeName(t^.base)
491+ else TypeName := '^' + TypeName(t^.base);
492+ fArray: begin Str(t^.len, s); TypeName := '[' + s + ']' + TypeName(t^.base) end;
493+ fSlice: TypeName := '[]' + TypeName(t^.base);
494+ fRecord: if not t^.tuple then TypeName := 'record'
495+ else begin
496+ s := '(';
497+ f := t^.fields;
498+ while f <> nil do begin
499+ s := s + TypeName(f^.typ);
500+ f := f^.next;
501+ if f <> nil then s := s + ', ';
502+ end;
503+ TypeName := s + ')';
504+ end;
505+ fVariant: TypeName := 'variant';
506+ fProc: begin
507+ s := 'proc(';
508+ f := t^.fields;
509+ while f <> nil do begin
510+ if f^.isVar then s := s + 'var ';
511+ s := s + TypeName(f^.typ);
512+ f := f^.next;
513+ if f <> nil then s := s + ', ';
514+ end;
515+ s := s + ')';
516+ if t^.base <> nil then s := s + ': ' + TypeName(t^.base);
517+ TypeName := s;
518+ end;
519+ else TypeName := '?';
520+ end;
521+end;
522+
523+{ A fingerprint of what a declaration exports, for the interface
524+ check: two files of one module export the same thing when their
525+ fingerprints agree. A named type counts by its name, so that a type
526+ declared in each file stands for the other's. }
527+procedure Mix(var h: qword; v: int64);
528+begin
529+ h := (h xor qword(v)) * 1099511628211; { FNV-1a's 64-bit prime }
530+end;
531+
532+procedure Shape(var h: qword; t: PType; top: boolean);
533+var f, g: PObj;
534+begin
535+ if t = nil then begin Mix(h, -1); exit end;
536+ if (t^.obj <> nil) and not top then begin
537+ Mix(h, t^.obj^.name);
538+ if t^.obj^.module <> nil then Mix(h, t^.obj^.module^.sname);
539+ exit;
540+ end;
541+ Mix(h, ord(t^.form));
542+ Mix(h, ord(t^.vol) + 2 * ord(t^.variadic));
543+ Mix(h, t^.len);
544+ if t^.form in [fPtr, fArray, fSlice, fProc, fSet] then Shape(h, t^.base, false);
545+ f := t^.fields;
546+ while f <> nil do begin
547+ if (t^.form <> fRecord) or f^.exported then begin
548+ Mix(h, f^.name);
549+ Mix(h, ord(f^.isVar));
550+ Shape(h, f^.typ, false);
551+ g := f^.fields;
552+ while g <> nil do begin Shape(h, g^.typ, false); g := g^.next end;
553+ end;
554+ f := f^.next;
555+ end;
556+end;
557+
558+function Fingerprint(o: PObj): qword;
559+var h: qword; f: PObj;
560+begin
561+ h := 14695981039346656037; { FNV-1a's 64-bit offset basis }
562+ Mix(h, ord(o^.cls));
563+ if o^.cls = oCase then begin
564+ Mix(h, o^.val);
565+ f := o^.fields;
566+ while f <> nil do begin Shape(h, f^.typ, false); f := f^.next end;
567+ end else Shape(h, o^.typ, o^.cls = oType);
568+ Fingerprint := h;
569+end;
570+
571+{ The universe }
572+
573+function Basic(const name: shortstring; form: TForm; size: int64; signed: boolean): PType;
574+var t: PType; o: PObj;
575+begin
576+ t := NewType(form, size, size);
577+ t^.signed := signed;
578+ o := NewObj(oType, Intern(@name[1], length(name)), t);
579+ o^.exported := true;
580+ t^.obj := o;
581+ Insert(o, 0);
582+ Basic := t;
583+end;
584+
585+procedure Enter(const name: shortstring; cls: TClass; t: PType; v: int64);
586+var o: PObj;
587+begin
588+ o := NewObj(cls, Intern(@name[1], length(name)), t);
589+ o^.val := v;
590+ o^.exported := true;
591+ Insert(o, 0);
592+end;
593+
594+initialization
595+ hashMask := (1 shl 14) - 1;
596+ hashTab := GetMem((hashMask + 1) * SizeOf(PObj));
597+ FillChar(hashTab^, (hashMask + 1) * SizeOf(PObj), 0);
598+ depth := 1;
599+ scopes[0] := 0;
600+ nextScope := 0;
601+ curModule := nil;
602+ tI8 := Basic('I8', fInt, 1, true);
603+ tI16 := Basic('I16', fInt, 2, true);
604+ tI32 := Basic('I32', fInt, 4, true);
605+ tI64 := Basic('I64', fInt, 8, true);
606+ tU8 := Basic('U8', fInt, 1, false);
607+ tU16 := Basic('U16', fInt, 2, false);
608+ tU32 := Basic('U32', fInt, 4, false);
609+ tU64 := Basic('U64', fInt, 8, false);
610+ tInt := Basic('INT', fInt, 8, true);
611+ tUInt := Basic('UINT', fInt, 8, false);
612+ tBool := Basic('BOOL', fBool, 1, false);
613+ tF32 := Basic('F32', fReal, 4, false);
614+ tReal := Basic('F64', fReal, 8, false);
615+ tRConst := NewType(fReal, 8, 8);
616+ tError := Basic('ERROR', fError, 8, false);
617+ tConst := NewType(fConst, 8, 8);
618+ tConst^.signed := true;
619+ tNil := NewType(fNil, 8, 8);
620+ tStr := NewType(fStr, 0, 1);
621+ tNone := NewType(fNone, 0, 1);
622+ tPtrU8 := NewType(fPtr, 8, 8);
623+ tPtrU8^.base := tU8;
624+ tBytes := NewType(fSlice, 16, 8);
625+ tBytes^.base := tU8;
626+ tPoison := NewType(fInt, 8, 8);
627+ tPoison^.signed := true;
628+ Enter('true', oConst, tBool, 1);
629+ Enter('false', oConst, tBool, 0);
630+ Enter('nil', oConst, tNil, 0);
631+ Enter('SIZE', oBuiltin, nil, bSize);
632+ Enter('ADR', oBuiltin, nil, bAdr);
633+ Enter('LEN', oBuiltin, nil, bLen);
634+ Enter('NEW', oBuiltin, nil, bNew);
635+ Enter('MSG', oBuiltin, nil, bMsg);
636+ Enter('SYSCALL', oBuiltin, nil, bSyscall);
637+ Enter('FENCE', oBuiltin, nil, bFence);
638+ Enter('CAS', oBuiltin, nil, bCas);
639+ Enter('XCHG', oBuiltin, nil, bXchg);
640+ Enter('XADD', oBuiltin, nil, bXadd);
641+ Enter('ARGC', oBuiltin, nil, bArgc);
642+ Enter('ARGV', oBuiltin, nil, bArgv);
643+ Enter('INC', oBuiltin, nil, bInc);
644+ Enter('DEC', oBuiltin, nil, bDec);
645+ Enter('COPY', oBuiltin, nil, bCopy);
646+end.

seed/x64.pas added +1208 -0

@@ -0,0 +1,1208 @@
1+{ x64.pas: machine code for x86-64.
2+
3+ The encoder writes the instructions the code generator needs, and
4+ no others, into the text of chunk.pas. Registers are numbered as the
5+ hardware numbers them. Jumps within a procedure are patched here, as
6+ soon as their target is known.
7+
8+ Depends on: scan, for errors; chunk, for the code buffer and fixups.
9+ Leaves out: choosing instructions; that is gen.pas. }
10+
11+unit x64;
12+
13+{$mode objfpc}{$H-}
14+
15+interface
16+
17+uses scan, diag, chunk;
18+
19+const
20+ 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; R12 = 12; R13 = 13; R14 = 14; R15 = 15;
22+ RIP = -1; { a base meaning rip-relative, to a chunk }
23+ NoIndex = -1;
24+
25+ { condition codes }
26+ ccB = 2; ccAE = 3; ccE = 4; ccNE = 5; ccBE = 6; ccA = 7; ccS = 8;
27+ ccP = 10; ccNP = 11; ccL = 12; ccGE = 13; ccLE = 14; ccG = 15;
28+
29+ { group 1 operations, the /digit of 81 and 83 }
30+ aluAdd = 0; aluOr = 1; aluAnd = 4; aluSub = 5; aluXor = 6; aluCmp = 7;
31+
32+ { the /digit of D3 and C1 }
33+ shShl = 4; shShr = 5; shSar = 7;
34+
35+ NoLabel = -1;
36+
37+type
38+ TMem = record
39+ base: longint; { a register, or RIP }
40+ index: longint; { a register, or NoIndex }
41+ scale: longint; { 1, 2, 4 or 8 }
42+ disp: longint;
43+ chunk: longint; { with RIP: the chunk addressed }
44+ end;
45+
46+var
47+ listing: boolean; { -S: each instruction's text is kept, for List }
48+
49+function Here: TMem;
50+function Mem(base: longint; disp: int64): TMem;
51+function MemRip(chunk: longint; disp: longint): TMem;
52+function MemIdx(base, index, scale: longint; disp: int64): TMem;
53+
54+procedure MovRR(dst, src: longint);
55+procedure MovRI(r: longint; v: int64);
56+procedure Load(r: longint; const m: TMem; size: longint; signed: boolean);
57+procedure Store(const m: TMem; r: longint; size: longint);
58+procedure Lea(r: longint; const m: TMem);
59+procedure Alu(op, dst, src: longint);
60+procedure AluI(op, r: longint; v: longint);
61+procedure AluM(op, r: longint; const m: TMem);
62+procedure AluMI(op: longint; m: TMem; v, size: longint);
63+procedure StoreI(m: TMem; v, size: longint);
64+procedure Imul(dst, src: longint);
65+procedure ImulI(r: longint; v: longint);
66+procedure Shift(op, r: longint);
67+procedure ShiftI(op, r, n: longint);
68+procedure Unary(ext, r: longint); { F7 /ext: 2 not, 3 neg, 6 div, 7 idiv }
69+procedure Cqo;
70+procedure Extend(r, size: longint; signed: boolean);
71+procedure SetCC(cc, r: longint);
72+procedure TestRR(a, b: longint);
73+procedure Push(r: longint);
74+procedure Pop(r: longint);
75+procedure CallChunk(c: longint);
76+procedure CallBack(target: longint);
77+procedure CallR(r: longint);
78+procedure JmpR(r: longint);
79+procedure CallM(const m: TMem);
80+procedure Ret;
81+procedure Leave;
82+procedure Syscall;
83+procedure Mfence;
84+procedure Ud2;
85+procedure Align(n: longint);
86+procedure RepMovsb;
87+procedure Std;
88+procedure Cld;
89+procedure RepStosb;
90+procedure RepeCmpsb;
91+procedure LockCmpxchg(const m: TMem; r: longint);
92+procedure Xchg(const m: TMem; r: longint);
93+procedure LockXadd(const m: TMem; r: longint);
94+procedure MovqXR(x, r: longint);
95+procedure MovqRX(r, x: longint);
96+procedure MovX(x, y: longint);
97+{ The real instructions take single: F32 (ss) rather than F64 (sd) }
98+procedure MovsXM(x: longint; const m: TMem; single: boolean);
99+procedure MovsMX(const m: TMem; x: longint; single: boolean);
100+procedure Sse(op, x, y: longint; single: boolean); { 58 add, 59 mul, 5C sub, 5E div, 5A convert }
101+procedure SseM(op, x: longint; const m: TMem; single: boolean);
102+procedure Ucomis(x, y: longint; single: boolean);
103+procedure Cvtsi2s(x, r: longint; single: boolean);
104+procedure Cvtts2si(r, x: longint; single: boolean);
105+procedure Btc(r, bit: longint);
106+
107+procedure Jmp(var L: longint);
108+procedure Jcc(cc: longint; var L: longint);
109+procedure JmpBack(target: longint);
110+procedure JccBack(cc, target: longint);
111+procedure FixLink(L: longint);
112+procedure DropJumpTo(var L: longint);
113+procedure FixLinkTo(L, target: longint);
114+function JoinLinks(L1, L2: longint): longint;
115+
116+type
117+ { The parser's reader of an integer constant in a code procedure: a
118+ whole expression, or, when whole is false, a single factor }
119+ TConstFn = function(whole: boolean): int64;
120+
121+const
122+ RegNames: array[0..3, 0..15] of string[5] = (
123+ ('rax', 'rcx', 'rdx', 'rbx', 'rsp', 'rbp', 'rsi', 'rdi',
124+ 'r8', 'r9', 'r10', 'r11', 'r12', 'r13', 'r14', 'r15'),
125+ ('eax', 'ecx', 'edx', 'ebx', 'esp', 'ebp', 'esi', 'edi',
126+ 'r8d', 'r9d', 'r10d', 'r11d', 'r12d', 'r13d', 'r14d', 'r15d'),
127+ ('ax', 'cx', 'dx', 'bx', 'sp', 'bp', 'si', 'di',
128+ 'r8w', 'r9w', 'r10w', 'r11w', 'r12w', 'r13w', 'r14w', 'r15w'),
129+ ('al', 'cl', 'dl', 'bl', 'spl', 'bpl', 'sil', 'dil',
130+ 'r8b', 'r9b', 'r10b', 'r11b', 'r12b', 'r13b', 'r14b', 'r15b'));
131+ CondNames: array[0..15] of string[3] = ('o', 'no', 'b', 'ae', 'e', 'ne',
132+ 'be', 'a', 's', 'ns', 'p', 'np', 'l', 'ge', 'le', 'g');
133+
134+procedure Assemble(constExpr: TConstFn);
135+procedure Say(const s: shortstring);
136+function SaidCount: longint;
137+procedure Unsay(n: longint);
138+procedure Restate(at: longint; const s: shortstring);
139+procedure List(module: longint);
140+
141+implementation
142+
143+{ Operands }
144+
145+function Mem(base: longint; disp: int64): TMem;
146+begin
147+ if (disp < low(longint)) or (disp > high(longint)) then Mark('an offset beyond 32 bits');
148+ Mem.base := base; Mem.index := NoIndex; Mem.scale := 1;
149+ Mem.disp := disp; Mem.chunk := -1;
150+end;
151+
152+function MemRip(chunk: longint; disp: longint): TMem;
153+begin
154+ MemRip.base := RIP; MemRip.index := NoIndex; MemRip.scale := 1;
155+ MemRip.disp := disp; MemRip.chunk := chunk;
156+end;
157+
158+function MemIdx(base, index, scale: longint; disp: int64): TMem;
159+begin
160+ MemIdx := Mem(base, disp);
161+ MemIdx.index := index;
162+ MemIdx.scale := scale;
163+end;
164+
165+{ The address of the code about to be written, as an operand }
166+function Here: TMem;
167+begin
168+ Here := MemRip(curChunk, pc - chunks^[curChunk].start);
169+end;
170+
171+{ Encoding. An instruction is: a legacy prefix, REX, the opcode, ModRM,
172+ SIB and displacement. Opcodes of more than one byte are given with
173+ their first byte in the low eight bits. }
174+
175+procedure Opcode(op: longint);
176+begin
177+ repeat
178+ Put1(op and $FF);
179+ op := op shr 8;
180+ until op = 0;
181+end;
182+
183+{ The legacy prefix pfx, if any, and REX: wide is REX.W; byte4 says
184+ a byte register of 4 to 7 is used, spl to dil, which exist only with
185+ a REX prefix. }
186+procedure Prefix(pfx: longint; w: boolean; reg, index, base: longint; byte4: boolean);
187+var rex: longint;
188+begin
189+ if pfx <> 0 then Put1(pfx);
190+ rex := 0;
191+ if w then rex := rex or 8;
192+ if reg >= 8 then rex := rex or 4;
193+ if index >= 8 then rex := rex or 2;
194+ if base >= 8 then rex := rex or 1;
195+ if (rex <> 0) or byte4 then Put1($40 or rex);
196+end;
197+
198+{ op reg, [mem] }
199+procedure OpM(pfx: longint; w: boolean; op, reg: longint; const m: TMem; byteReg: boolean = false);
200+var md, b, sc: longint;
201+begin
202+ byteReg := byteReg and (reg >= 4) and (reg <= 7);
203+ if m.base = RIP then Prefix(pfx, w, reg, NoIndex, 0, byteReg)
204+ else Prefix(pfx, w, reg, m.index, m.base, byteReg);
205+ Opcode(op);
206+ reg := reg and 7;
207+ if m.base = RIP then begin
208+ Put1(reg shl 3 or 5);
209+ { mod 00 with r/m 101 is rip + disp32. The displacement counts
210+ from the end of the instruction, and the fixup takes it to end
211+ with these four bytes: an instruction with an immediate after
212+ them, AluMI's or StoreI's, takes the immediate's size off disp
213+ first (the assembler can't name a chunk). }
214+ AddFixup(pc, m.chunk, m.disp);
215+ Put4(0);
216+ exit;
217+ end;
218+ b := m.base and 7;
219+ { mod 00 takes no displacement, but with r/m 101 (RBP or R13) it means
220+ rip-relative, or disp32 under a SIB byte, so those bases take a
221+ zero disp8 }
222+ if (m.disp = 0) and (b <> RBP) then md := 0
223+ else if (m.disp >= -128) and (m.disp <= 127) then md := 1
224+ else md := 2;
225+ { r/m 100 (RSP or R12) means a SIB byte follows, so those bases need
226+ one, with index 100 meaning none }
227+ if (m.index <> NoIndex) or (b = RSP) then begin
228+ Put1(md shl 6 or reg shl 3 or 4);
229+ case m.scale of 1: sc := 0; 2: sc := 1; 4: sc := 2; else sc := 3; end;
230+ if m.index = NoIndex then Put1(sc shl 6 or 4 shl 3 or b)
231+ else Put1(sc shl 6 or (m.index and 7) shl 3 or b);
232+ end else
233+ Put1(md shl 6 or reg shl 3 or b);
234+ if md = 1 then Put1(m.disp)
235+ else if md = 2 then Put4(m.disp);
236+end;
237+
238+{ op reg, rm (both registers) }
239+procedure OpR(pfx: longint; w: boolean; op, reg, rm: longint; byteReg: boolean = false);
240+begin
241+ Prefix(pfx, w, reg, NoIndex, rm, byteReg and ((reg in [4..7]) or (rm in [4..7])));
242+ Opcode(op);
243+ Put1($C0 or (reg and 7) shl 3 or (rm and 7));
244+end;
245+
246+{ The listing: the text of each instruction, as it is made }
247+
248+type
249+ TSaid = record
250+ at: longint; { where the instruction starts in code }
251+ text: string[63];
252+ end;
253+
254+var
255+ said: ^TSaid;
256+ numSaid, saidCap: longint;
257+
258+{ How many instructions the listing has, and back to n of them, for
259+ code made again }
260+function SaidCount: longint;
261+begin
262+ SaidCount := numSaid;
263+end;
264+
265+procedure Unsay(n: longint);
266+begin
267+ numSaid := n;
268+end;
269+
270+procedure SayAt(at: longint; const s: shortstring);
271+begin
272+ if not listing then exit;
273+ if numSaid = saidCap then begin
274+ saidCap := saidCap * 2 + 1024;
275+ said := ReAllocMem(said, saidCap * SizeOf(TSaid));
276+ end;
277+ said[numSaid].at := at;
278+ said[numSaid].text := s;
279+ inc(numSaid);
280+end;
281+
282+{ The text of the instruction about to be written }
283+procedure Say(const s: shortstring);
284+begin
285+ SayAt(pc, s);
286+end;
287+
288+{ The text of the instruction at at, said again, as when its operand is
289+ patched }
290+procedure Restate(at: longint; const s: shortstring);
291+var i: longint;
292+begin
293+ i := numSaid - 1;
294+ while (i >= 0) and (said[i].at <> at) do dec(i);
295+ if i >= 0 then said[i].text := s;
296+end;
297+
298+function RN(r: longint; size: longint = 8): shortstring;
299+begin
300+ case size of
301+ 1: RN := RegNames[3, r];
302+ 2: RN := RegNames[2, r];
303+ 4: RN := RegNames[1, r];
304+ else RN := RegNames[0, r];
305+ end;
306+end;
307+
308+function XN(x: longint): shortstring;
309+begin
310+ XN := 'xmm' + IntStr(x);
311+end;
312+
313+{ A memory operand, with the size of what it holds, as the assembler
314+ reads it }
315+function MN(const m: TMem; size: longint = 0): shortstring;
316+var s: shortstring;
317+begin
318+ case size of
319+ 1: s := 'byte ';
320+ 2: s := 'word ';
321+ 4: s := 'dword ';
322+ 8: s := 'qword ';
323+ else s := '';
324+ end;
325+ if m.base = RIP then s := s + '[' + ChunkName(m.chunk)
326+ else s := s + '[' + RN(m.base);
327+ if m.index <> NoIndex then s := s + ' + ' + RN(m.index) + ' * ' + IntStr(m.scale);
328+ if m.disp > 0 then s := s + ' + ' + IntStr(m.disp)
329+ else if m.disp < 0 then s := s + ' - ' + IntStr(-m.disp);
330+ MN := s + ']';
331+end;
332+
333+const
334+ AluNames: array[0..7] of string[3] = ('add', 'or', 'adc', 'sbb', 'and', 'sub', 'xor', 'cmp');
335+ ShiftNames: array[0..7] of string[3] = ('rol', 'ror', 'rcl', 'rcr', 'shl', 'shr', 'sal', 'sar');
336+ UnaryNames: array[2..7] of string[4] = ('not', 'neg', 'mul', 'imul', 'div', 'idiv');
337+
338+procedure MovRR(dst, src: longint);
339+begin
340+ if listing then Say('mov ' + RN(dst) + ', ' + RN(src));
341+ OpR(0, true, $89, src, dst);
342+end;
343+
344+{ The immediate of n bytes that ends an instruction }
345+procedure PutImm(v, n: longint);
346+begin
347+ if n = 4 then Put4(v)
348+ else begin
349+ Put1(v and $FF);
350+ if n = 2 then Put1((v shr 8) and $FF);
351+ end;
352+end;
353+
354+{ op [m], v, on size bytes; v fits in them, or in 32 bits for 8 }
355+procedure AluMI(op: longint; m: TMem; v, size: longint);
356+var n: longint;
357+begin
358+ if listing then Say(AluNames[op] + ' ' + MN(m, size) + ', ' + IntStr(v));
359+ if (size = 1) or (v >= -128) and (v <= 127) then n := 1
360+ else if size = 2 then n := 2
361+ else n := 4;
362+ if m.base = RIP then dec(m.disp, n);
363+ if size = 1 then OpM(0, false, $80, op, m)
364+ else if n = 1 then OpM(ord(size = 2) * $66, size = 8, $83, op, m)
365+ else OpM(ord(size = 2) * $66, size = 8, $81, op, m);
366+ PutImm(v, n);
367+end;
368+
369+{ mov [m], v, of size bytes; v fits in them, or in 32 bits for 8 }
370+procedure StoreI(m: TMem; v, size: longint);
371+var n: longint;
372+begin
373+ if listing then Say('mov ' + MN(m, size) + ', ' + IntStr(v));
374+ n := size;
375+ if n > 4 then n := 4;
376+ if m.base = RIP then dec(m.disp, n);
377+ if size = 1 then OpM(0, false, $C6, 0, m)
378+ else OpM(ord(size = 2) * $66, size = 8, $C7, 0, m);
379+ PutImm(v, n);
380+end;
381+
382+procedure MovRI(r: longint; v: int64);
383+begin
384+ if not listing then
385+ else if v = 0 then Say('xor ' + RN(r, 4) + ', ' + RN(r, 4))
386+ else Say('mov ' + RN(r) + ', ' + IntStr(v));
387+ if (v >= low(longint)) and (v <= high(longint)) then begin
388+ if v = 0 then OpR(0, false, $31, r, r) { xor r32, r32 }
389+ else if v > 0 then begin { mov r32, imm32 }
390+ Prefix(0, false, 0, NoIndex, r, false); Put1($B8 + r and 7); Put4(v)
391+ end else begin
392+ OpR(0, true, $C7, 0, r); Put4(v) { sign-extended imm32 }
393+ end;
394+ end else if (v > 0) and (v <= $FFFFFFFF) then begin
395+ Prefix(0, false, 0, NoIndex, r, false); Put1($B8 + r and 7); Put4(longint(v))
396+ end else begin
397+ Prefix(0, true, 0, NoIndex, r, false); Put1($B8 + r and 7); Put8(v)
398+ end;
399+end;
400+
401+procedure Load(r: longint; const m: TMem; size: longint; signed: boolean);
402+begin
403+ if not listing then
404+ else if size = 8 then Say('mov ' + RN(r) + ', ' + MN(m))
405+ else if (size = 4) and not signed then Say('mov ' + RN(r, 4) + ', ' + MN(m))
406+ else if size = 4 then Say('movsxd ' + RN(r) + ', ' + MN(m, 4))
407+ else if signed then Say('movsx ' + RN(r) + ', ' + MN(m, size))
408+ else Say('movzx ' + RN(r, 4) + ', ' + MN(m, size));
409+ case size of
410+ 1: if signed then OpM(0, true, $BE0F, r, m) else OpM(0, false, $B60F, r, m);
411+ 2: if signed then OpM(0, true, $BF0F, r, m) else OpM(0, false, $B70F, r, m);
412+ 4: if signed then OpM(0, true, $63, r, m) else OpM(0, false, $8B, r, m);
413+ else OpM(0, true, $8B, r, m);
414+ end;
415+end;
416+
417+procedure Store(const m: TMem; r: longint; size: longint);
418+begin
419+ if listing then Say('mov ' + MN(m) + ', ' + RN(r, size));
420+ case size of
421+ 1: OpM(0, false, $88, r, m, true);
422+ 2: OpM($66, false, $89, r, m);
423+ 4: OpM(0, false, $89, r, m);
424+ else OpM(0, true, $89, r, m);
425+ end;
426+end;
427+
428+procedure Lea(r: longint; const m: TMem);
429+begin
430+ if listing then Say('lea ' + RN(r) + ', ' + MN(m));
431+ OpM(0, true, $8D, r, m);
432+end;
433+
434+procedure Alu(op, dst, src: longint);
435+begin
436+ if listing then Say(AluNames[op] + ' ' + RN(dst) + ', ' + RN(src));
437+ OpR(0, true, op shl 3 or 1, src, dst);
438+end;
439+
440+procedure AluI(op, r: longint; v: longint);
441+begin
442+ if listing then Say(AluNames[op] + ' ' + RN(r) + ', ' + IntStr(v));
443+ if (v >= -128) and (v <= 127) then begin
444+ OpR(0, true, $83, op, r); Put1(v)
445+ end else begin
446+ OpR(0, true, $81, op, r); Put4(v)
447+ end;
448+end;
449+
450+{ op r, [m] }
451+procedure AluM(op, r: longint; const m: TMem);
452+begin
453+ if listing then Say(AluNames[op] + ' ' + RN(r) + ', ' + MN(m));
454+ OpM(0, true, op shl 3 or 3, r, m);
455+end;
456+
457+procedure Imul(dst, src: longint);
458+begin
459+ if listing then Say('imul ' + RN(dst) + ', ' + RN(src));
460+ OpR(0, true, $AF0F, dst, src);
461+end;
462+
463+procedure ImulI(r: longint; v: longint);
464+begin
465+ if listing then Say('imul ' + RN(r) + ', ' + RN(r) + ', ' + IntStr(v));
466+ OpR(0, true, $69, r, r);
467+ Put4(v);
468+end;
469+
470+procedure Shift(op, r: longint);
471+begin
472+ if listing then Say(ShiftNames[op] + ' ' + RN(r) + ', cl');
473+ OpR(0, true, $D3, op, r);
474+end;
475+
476+procedure ShiftI(op, r, n: longint);
477+begin
478+ if listing then Say(ShiftNames[op] + ' ' + RN(r) + ', ' + IntStr(n));
479+ OpR(0, true, $C1, op, r);
480+ Put1(n);
481+end;
482+
483+procedure Unary(ext, r: longint);
484+begin
485+ if listing then Say(UnaryNames[ext] + ' ' + RN(r));
486+ OpR(0, true, $F7, ext, r);
487+end;
488+
489+procedure Cqo;
490+begin
491+ if listing then Say('cqo');
492+ Put1($48); Put1($99);
493+end;
494+
495+{ Brings a value of size bytes in r to 64 bits, by its sign or zeros. }
496+procedure Extend(r, size: longint; signed: boolean);
497+begin
498+ if not listing then
499+ else if size = 4 then begin
500+ if signed then Say('movsxd ' + RN(r) + ', ' + RN(r, 4)) else Say('mov ' + RN(r, 4) + ', ' + RN(r, 4))
501+ end else if signed then Say('movsx ' + RN(r) + ', ' + RN(r, size))
502+ else Say('movzx ' + RN(r, 4) + ', ' + RN(r, size));
503+ case size of
504+ 1: if signed then OpR(0, true, $BE0F, r, r, true) else OpR(0, false, $B60F, r, r, true);
505+ 2: if signed then OpR(0, true, $BF0F, r, r) else OpR(0, false, $B70F, r, r);
506+ 4: if signed then OpR(0, true, $63, r, r) else OpR(0, false, $89, r, r);
507+ end;
508+end;
509+
510+{ r := 1 if the condition holds, else 0 }
511+procedure SetCC(cc, r: longint);
512+begin
513+ if listing then Say('set' + CondNames[cc] + ' ' + RN(r, 1));
514+ OpR(0, false, $900F + cc shl 8, 0, r, true);
515+ if listing then Say('movzx ' + RN(r, 4) + ', ' + RN(r, 1));
516+ OpR(0, false, $B60F, r, r, true);
517+end;
518+
519+procedure TestRR(a, b: longint);
520+begin
521+ if listing then Say('test ' + RN(a) + ', ' + RN(b));
522+ OpR(0, true, $85, b, a);
523+end;
524+
525+procedure Push(r: longint);
526+begin
527+ if listing then Say('push ' + RN(r));
528+ if r >= 8 then Put1($41);
529+ Put1($50 + r and 7);
530+end;
531+
532+procedure Pop(r: longint);
533+begin
534+ if listing then Say('pop ' + RN(r));
535+ if r >= 8 then Put1($41);
536+ Put1($58 + r and 7);
537+end;
538+
539+procedure CallChunk(c: longint);
540+begin
541+ if listing then Say('call ' + ChunkName(c));
542+ Put1($E8);
543+ AddFixup(pc, c, 0);
544+ Put4(0);
545+end;
546+
547+procedure CallBack(target: longint);
548+begin
549+ if listing then Say('call');
550+ Put1($E8);
551+ Put4(target - (pc + 4));
552+end;
553+
554+procedure CallR(r: longint);
555+begin
556+ if listing then Say('call ' + RN(r));
557+ OpR(0, false, $FF, 2, r);
558+end;
559+
560+procedure JmpR(r: longint);
561+begin
562+ if listing then Say('jmp ' + RN(r));
563+ OpR(0, false, $FF, 4, r);
564+end;
565+
566+procedure CallM(const m: TMem);
567+begin
568+ if listing then Say('call ' + MN(m));
569+ OpM(0, false, $FF, 2, m);
570+end;
571+
572+procedure Ret; begin if listing then Say('ret'); Put1($C3) end;
573+procedure Leave; begin Say('leave'); Put1($C9) end;
574+procedure Syscall; begin Say('syscall'); Put1($0F); Put1($05) end;
575+procedure Mfence; begin Say('mfence'); Put1($0F); Put1($AE); Put1($F0) end;
576+procedure Ud2; begin Say('ud2'); Put1($0F); Put1($0B) end;
577+
578+{ Code made up to a multiple of n bytes with no-ops, the fewest: the
579+ long forms of nop, of up to 8 bytes, that x86 decodes as one }
580+procedure Align(n: longint);
581+const
582+ Nops: array[1..8] of string[8] = (#$90, #$66#$90, #$0F#$1F#$00, #$0F#$1F#$40#$00,
583+ #$0F#$1F#$44#$00#$00, #$66#$0F#$1F#$44#$00#$00, #$0F#$1F#$80#$00#$00#$00#$00,
584+ #$0F#$1F#$84#$00#$00#$00#$00#$00);
585+var k, i: longint;
586+begin
587+ while pc mod n <> 0 do begin
588+ k := n - pc mod n;
589+ if k > 8 then k := 8;
590+ Say('nop');
591+ for i := 1 to k do Put1(ord(Nops[k][i]));
592+ end;
593+end;
594+procedure RepMovsb; begin Say('rep movsb'); Put1($F3); Put1($A4) end;
595+{ the direction flag, which has rep movsb go down, and back up }
596+procedure Std; begin Say('std'); Put1($FD) end;
597+procedure Cld; begin Say('cld'); Put1($FC) end;
598+procedure RepStosb; begin Say('rep stosb'); Put1($F3); Put1($AA) end;
599+procedure RepeCmpsb; begin Say('repe cmpsb'); Put1($F3); Put1($A6) end;
600+
601+procedure LockCmpxchg(const m: TMem; r: longint);
602+begin
603+ if listing then Say('lock cmpxchg ' + MN(m) + ', ' + RN(r));
604+ Put1($F0);
605+ OpM(0, true, $B10F, r, m);
606+end;
607+
608+procedure Xchg(const m: TMem; r: longint);
609+begin
610+ if listing then Say('xchg ' + MN(m) + ', ' + RN(r));
611+ OpM(0, true, $87, r, m);
612+end;
613+
614+procedure LockXadd(const m: TMem; r: longint);
615+begin
616+ if listing then Say('lock xadd ' + MN(m) + ', ' + RN(r));
617+ Put1($F0);
618+ OpM(0, true, $C10F, r, m);
619+end;
620+
621+procedure MovqXR(x, r: longint);
622+begin
623+ if listing then Say('movq ' + XN(x) + ', ' + RN(r));
624+ OpR($66, true, $6E0F, x, r);
625+end;
626+
627+procedure MovqRX(r, x: longint);
628+begin
629+ if listing then Say('movq ' + RN(r) + ', ' + XN(x));
630+ OpR($66, true, $7E0F, x, r);
631+end;
632+
633+{ movaps: all of xmm y to xmm x, the shortest move between two }
634+procedure MovX(x, y: longint);
635+begin
636+ if listing then Say('movaps ' + XN(x) + ', ' + XN(y));
637+ OpR(0, false, $280F, x, y);
638+end;
639+
640+const
641+ RealPfx: array[boolean] of longint = ($F2, $F3);
642+ RealEnd: array[boolean] of string[2] = ('sd', 'ss');
643+
644+procedure MovsXM(x: longint; const m: TMem; single: boolean);
645+begin
646+ if listing then Say('movs' + RealEnd[single][2] + ' ' + XN(x) + ', ' + MN(m));
647+ OpM(RealPfx[single], false, $100F, x, m);
648+end;
649+
650+procedure MovsMX(const m: TMem; x: longint; single: boolean);
651+begin
652+ if listing then Say('movs' + RealEnd[single][2] + ' ' + MN(m) + ', ' + XN(x));
653+ OpM(RealPfx[single], false, $110F, x, m);
654+end;
655+
656+function SseName(op: longint; single: boolean): shortstring;
657+begin
658+ case op of
659+ $58: SseName := 'add' + RealEnd[single];
660+ $59: SseName := 'mul' + RealEnd[single];
661+ $5C: SseName := 'sub' + RealEnd[single];
662+ $5E: SseName := 'div' + RealEnd[single];
663+ else SseName := 'cvt' + RealEnd[single] + '2' + RealEnd[not single];
664+ end;
665+end;
666+
667+procedure Sse(op, x, y: longint; single: boolean);
668+begin
669+ if listing then Say(SseName(op, single) + ' ' + XN(x) + ', ' + XN(y));
670+ OpR(RealPfx[single], false, $0F or op shl 8, x, y);
671+end;
672+
673+{ The same, its right operand in memory: addsd x, [m] }
674+procedure SseM(op, x: longint; const m: TMem; single: boolean);
675+begin
676+ if listing then Say(SseName(op, single) + ' ' + XN(x) + ', ' + MN(m));
677+ OpM(RealPfx[single], false, $0F or op shl 8, x, m);
678+end;
679+
680+procedure Ucomis(x, y: longint; single: boolean);
681+begin
682+ if listing then Say('ucomi' + RealEnd[single] + ' ' + XN(x) + ', ' + XN(y));
683+ if single then OpR(0, false, $2E0F, x, y) else OpR($66, false, $2E0F, x, y);
684+end;
685+
686+procedure Cvtsi2s(x, r: longint; single: boolean);
687+begin
688+ if listing then Say('cvtsi2' + RealEnd[single] + ' ' + XN(x) + ', ' + RN(r));
689+ OpR(RealPfx[single], true, $2A0F, x, r);
690+end;
691+
692+procedure Cvtts2si(r, x: longint; single: boolean);
693+begin
694+ if listing then Say('cvtt' + RealEnd[single] + '2si ' + RN(r) + ', ' + XN(x));
695+ OpR(RealPfx[single], true, $2C0F, r, x);
696+end;
697+
698+procedure Btc(r, bit: longint);
699+begin
700+ if listing then Say('btc ' + RN(r) + ', ' + IntStr(bit));
701+ OpR(0, true, $BA0F, 7, r);
702+ Put1(bit);
703+end;
704+
705+{ Jumps. A label not yet placed is the chain of the jumps to it, each
706+ rel32 field holding the position of the one before, NoLabel ending
707+ it. Placing the label walks the chain and patches each. }
708+
709+procedure Jmp(var L: longint);
710+begin
711+ if listing then Say('jmp');
712+ Put1($E9);
713+ Put4(L);
714+ L := pc - 4;
715+end;
716+
717+procedure Jcc(cc: longint; var L: longint);
718+begin
719+ if listing then Say('j' + CondNames[cc]);
720+ Put1($0F); Put1($80 + cc);
721+ Put4(L);
722+ L := pc - 4;
723+end;
724+
725+procedure JmpBack(target: longint);
726+begin
727+ if listing then Say('jmp');
728+ Put1($E9);
729+ Put4(target - (pc + 4));
730+end;
731+
732+procedure JccBack(cc, target: longint);
733+begin
734+ if listing then Say('j' + CondNames[cc]);
735+ Put1($0F); Put1($80 + cc);
736+ Put4(target - (pc + 4));
737+end;
738+
739+procedure FixLinkTo(L, target: longint);
740+var next: longint;
741+begin
742+ while L <> NoLabel do begin
743+ next := Get4At(L);
744+ Put4At(L, target - (L + 4));
745+ L := next;
746+ end;
747+end;
748+
749+procedure FixLink(L: longint);
750+begin
751+ FixLinkTo(L, pc);
752+end;
753+
754+{ If the last instruction made is a jmp to L, it is taken back, since L
755+ is to be placed just after it: a return at the end of a procedure
756+ needn't jump to the code that returns. L is the place of the latest
757+ jump's 4-byte field, so the last instruction is that jump when L is
758+ 4 bytes back and an E9 byte (jmp) is before it; a jcc's field follows
759+ the bytes 0F 8x, never E9. L then becomes the next jump on the chain,
760+ which the field held. The caller must place L next, before anything
761+ can have noted where the jmp ended. }
762+procedure DropJumpTo(var L: longint);
763+begin
764+ if (L = NoLabel) or (L <> pc - 4) or (code^[L - 1] <> $E9) then exit;
765+ L := Get4At(L);
766+ TakeBack(5);
767+ if listing and (numSaid > 0) and (said[numSaid - 1].at = pc) then dec(numSaid);
768+end;
769+
770+{ The jumps of chains L1 and L2, as one chain: each jump's field holds
771+ the next one's place until it is fixed, the last NoLabel }
772+function JoinLinks(L1, L2: longint): longint;
773+var L: longint;
774+begin
775+ if L2 = NoLabel then exit(L1);
776+ if L1 <> NoLabel then begin
777+ L := L2;
778+ while Get4At(L) <> NoLabel do L := Get4At(L);
779+ Put4At(L, L1);
780+ end;
781+ JoinLinks := L2;
782+end;
783+
784+
785+{ The assembler, for code procedures: x86-64 in Intel's syntax as NASM
786+ writes it (report, appendix A). It reads instructions with the
787+ scanner up to end, and encodes them with OpM and OpR; constants are
788+ read by the parser's constExpr. }
789+
790+const
791+ NoBase = -3; { a memory operand's base, not yet read }
792+
793+type
794+ TOpKind = (oReg, oXmm, oMem, oImm);
795+ TOpd = record
796+ kind: TOpKind;
797+ r, size: longint; { oReg, oXmm: the register and its size; oMem: its size, or 0 }
798+ m: TMem;
799+ v: int64; { oImm }
800+ end;
801+
802+{ The current symbol as a word: an identifier, or a reserved word that
803+ is also an instruction }
804+function AsmWord: shortstring;
805+begin
806+ case tok of
807+ sIdent: AsmWord := NameOf(id);
808+ sAnd: AsmWord := 'and';
809+ sOr: AsmWord := 'or';
810+ sXor: AsmWord := 'xor';
811+ sNot: AsmWord := 'not';
812+ sDiv: AsmWord := 'div';
813+ sShl: AsmWord := 'shl';
814+ sShr: AsmWord := 'shr';
815+ else AsmWord := '';
816+ end;
817+end;
818+
819+{ Whether w names a register: rax, eax, ax, al and so on, or xmm0 to
820+ xmm15 (size 16) }
821+function IsReg(const w: shortstring; var r, size: longint): boolean;
822+const Sizes: array[0..3] of longint = (8, 4, 2, 1);
823+var i, j, e: longint;
824+begin
825+ IsReg := true;
826+ for i := 0 to 3 do
827+ for j := 0 to 15 do
828+ if RegNames[i, j] = w then begin r := j; size := Sizes[i]; exit end;
829+ size := 16;
830+ Val(copy(w, 4, 2), r, e);
831+ IsReg := (copy(w, 1, 3) = 'xmm') and (length(w) > 3) and (e = 0) and (r in [0..15]);
832+end;
833+
834+{ Which word of list, a list of words each with a space either side,
835+ w is, from 0; -1 if none }
836+function WordIndex(const w, list: shortstring): longint;
837+var i, k: longint;
838+begin
839+ k := pos(' ' + w + ' ', list);
840+ WordIndex := -1;
841+ if k = 0 then exit;
842+ WordIndex := 0;
843+ for i := 2 to k do if list[i] = ' ' then inc(WordIndex);
844+end;
845+
846+{ The condition a name ends in: e of je, nz of jnz }
847+function Cond(const w: shortstring): longint;
848+const
849+ Alias: array[0..11] of string[3] = ('c', 'nae', 'nc', 'nb', 'z', 'nz', 'na', 'nbe', 'nge', 'nl', 'ng', 'nle');
850+ AliasCc: array[0..11] of longint = (2, 2, 3, 3, 4, 5, 6, 7, 12, 13, 14, 15);
851+var i: longint;
852+begin
853+ for i := 0 to 15 do if CondNames[i] = w then exit(i);
854+ for i := 0 to 11 do if Alias[i] = w then exit(AliasCc[i]);
855+ Cond := -1;
856+end;
857+
858+procedure Operand(var o: TOpd; constExpr: TConstFn);
859+var w: shortstring; r, size, sz: longint; st: TScanState;
860+begin
861+ FillChar(o, SizeOf(o), 0);
862+ w := AsmWord;
863+ sz := 0;
864+ if w = 'byte' then sz := 1 else if w = 'word' then sz := 2
865+ else if w = 'dword' then sz := 4 else if w = 'qword' then sz := 8;
866+ if sz <> 0 then begin Next; w := AsmWord end;
867+ if tok = sLbrak then begin
868+ { [base + index * scale + disp], the displacement last }
869+ Next;
870+ o.kind := oMem; o.size := sz;
871+ o.m := Mem(NoBase, 0);
872+ repeat
873+ if IsReg(AsmWord, r, size) and (size = 8) then begin
874+ Next;
875+ { the scale is a single number or constant: a whole expression
876+ would take in the displacement after it, as 4 + 16 in
877+ [rdi + rsi * 4 + 16] }
878+ if tok = sTimes then begin
879+ Next;
880+ o.m.index := r;
881+ o.m.scale := constExpr(false);
882+ end
883+ else if o.m.base = NoBase then o.m.base := r
884+ else begin o.m.index := r; o.m.scale := 1 end;
885+ end else o.m.disp := o.m.disp + constExpr(true);
886+ if not (tok in [sPlus, sMinus]) then break;
887+ SaveScan(st);
888+ Next;
889+ if not IsReg(AsmWord, r, size) and (st.tok = sMinus) then RestoreScan(st);
890+ until false;
891+ if (tok <> sRbrak) or (o.m.base = NoBase) or not (o.m.scale in [1, 2, 4, 8]) then
892+ Mark('expected a memory operand, [base + index * scale + disp]');
893+ Next;
894+ end else if IsReg(w, o.r, o.size) then begin
895+ if o.size = 16 then o.kind := oXmm else o.kind := oReg;
896+ Next;
897+ end else begin
898+ o.kind := oImm;
899+ o.v := constExpr(true);
900+ end;
901+end;
902+
903+{ op with register reg and the register or memory operand o }
904+procedure RM(pfx: longint; w: boolean; op, reg: longint; const o: TOpd; byteReg: boolean = false);
905+begin
906+ if o.kind = oMem then OpM(pfx, w, op, reg, o.m, byteReg)
907+ else OpR(pfx, w, op, reg, o.r, byteReg);
908+end;
909+
910+procedure PutImm(v: int64; size: longint);
911+begin
912+ case size of
913+ 1: Put1(v);
914+ 2: begin Put1(v); Put1(v shr 8) end;
915+ else Put4(v);
916+ end;
917+end;
918+
919+procedure Assemble(constExpr: TConstFn);
920+const
921+ Alus = ' add or adc sbb and sub xor cmp ';
922+ Unaries = ' not neg mul imul div idiv ';
923+ Shifts = ' rol ror rcl rcr shl shr sal sar ';
924+ SseOps = ' sqrt add mul sub min div max ';
925+ SseCodes: array[0..6] of longint = ($51, $58, $59, $5C, $5D, $5E, $5F);
926+ { SSE2 integer instructions that work on 16 bytes at a time: 66 0F code,
927+ xmm and xmm or memory (pshufd also takes a byte) }
928+ PackedOps = ' punpcklbw punpcklwd pcmpeqb pshufd pand pandn por pxor paddb psubb ';
929+ PackedCodes: array[0..9] of longint = ($60, $61, $74, $70, $DB, $DF, $EB, $EF, $FC, $F8);
930+ { bit scans and counts: reg, reg or memory, with the prefix and code that tell them }
931+ BitOps = ' bsf bsr tzcnt lzcnt popcnt ';
932+ BitPfx: array[0..4] of longint = (0, 0, $F3, $F3, $F3);
933+ BitCodes: array[0..4] of longint = ($BC0F, $BD0F, $BC0F, $BD0F, $B80F);
934+ Plain: array[0..14] of string[7] = ('ret', 'leave', 'syscall', 'cpuid', 'rdtsc',
935+ 'pause', 'nop', 'ud2', 'int3', 'hlt', 'cqo', 'cdq', 'mfence', 'lfence', 'sfence');
936+ PlainOp: array[0..14] of longint = ($C3, $C9, $050F, $A20F, $310F,
937+ $90F3, $90, $0B0F, $CC, $F4, $9948, $99, $F0AE0F, $E8AE0F, $F8AE0F);
938+var
939+ w: shortstring; o: array[0..2] of TOpd; n, i, k, size, pfx, cc: longint;
940+ wide, byteOp, wasListing: boolean; at, start: TPos; v: int64; first: longint;
941+ names, places, chains: array[0..63] of longint; numLabels: longint;
942+ usedAt: array[0..63] of TPos;
943+
944+ { the label called n, entered if new }
945+ function Lab(n: longint): longint;
946+ var i: longint;
947+ begin
948+ for i := 0 to numLabels - 1 do if names[i] = n then exit(i);
949+ if numLabels > High(names) then Mark('more than 64 labels');
950+ names[numLabels] := n; places[numLabels] := -1; chains[numLabels] := NoLabel;
951+ usedAt[numLabels] := TokPos;
952+ Lab := numLabels;
953+ inc(numLabels);
954+ end;
955+
956+ procedure Bad;
957+ begin
958+ MarkAt(at, 'can''t assemble ' + w + ' with these operands');
959+ end;
960+
961+ { an instruction of two operands: a register or memory, and a
962+ register (opcode toRM), the other way (fromRM), or an immediate
963+ (opImm /digit, or none if opImm < 0) }
964+ procedure Two(toRM, fromRM, opImm, digit: longint);
965+ begin
966+ if n <> 2 then Bad;
967+ if o[1].kind = oImm then begin
968+ if (o[0].kind = oImm) or (opImm < 0) then Bad;
969+ if (opImm = $81) and not byteOp and (o[1].v >= -128) and (o[1].v <= 127) then begin
970+ RM(pfx, wide, $83, digit, o[0]); { a byte, sign-extended }
971+ Put1(o[1].v);
972+ end else begin
973+ RM(pfx, wide, opImm - ord(byteOp), digit, o[0]);
974+ PutImm(o[1].v, size);
975+ end;
976+ end else if (o[1].kind = oReg) and (o[0].kind in [oReg, oMem]) then
977+ RM(pfx, wide, toRM - ord(byteOp), o[1].r, o[0], byteOp)
978+ else if (o[0].kind = oReg) and (o[1].kind = oMem) then
979+ RM(pfx, wide, fromRM - ord(byteOp), o[0].r, o[1], byteOp)
980+ else Bad;
981+ end;
982+
983+begin
984+ numLabels := 0;
985+ while not (tok in [sEnd, sEof]) do begin
986+ at := TokPos;
987+ w := AsmWord;
988+ if tok = sSemicolon then begin Next; continue end;
989+ if w = '' then Mark('expected an instruction');
990+ Next;
991+ if tok = sColon then begin
992+ SayAt(pc, w + ':');
993+ k := Lab(Intern(@w[1], length(w)));
994+ if places[k] >= 0 then MarkAt(at, 'label ' + w + ' is defined twice');
995+ places[k] := pc;
996+ FixLink(chains[k]);
997+ Next;
998+ continue;
999+ end;
1000+ first := pc;
1001+ wasListing := listing;
1002+ listing := false; { the instruction is said as it is written }
1003+ if w = 'lock' then begin
1004+ Put1($F0);
1005+ w := AsmWord;
1006+ Next;
1007+ end;
1008+ cc := -1;
1009+ if w = 'db' then
1010+ repeat
1011+ start := TokPos;
1012+ v := constExpr(true);
1013+ if (v < -128) or (v > 255) then MarkAt(SpanFrom(start), 'expected a byte from 0 to 255, found ' + IntStr(v));
1014+ Put1(v);
1015+ if tok <> sComma then break;
1016+ Next;
1017+ until false
1018+ else if (w[1] = 'j') and ((w = 'jmp') or (Cond(copy(w, 2, 3)) >= 0)) and (tok = sIdent) then begin
1019+ { a jump to a label }
1020+ k := Lab(id);
1021+ Next;
1022+ if w <> 'jmp' then cc := Cond(copy(w, 2, 3));
1023+ if places[k] >= 0 then begin
1024+ if cc < 0 then JmpBack(places[k]) else JccBack(cc, places[k])
1025+ end else if cc < 0 then Jmp(chains[k]) else Jcc(cc, chains[k]);
1026+ end else begin
1027+ n := 0;
1028+ if tok <> sSemicolon then
1029+ repeat
1030+ if n > High(o) then Mark('too many operands');
1031+ Operand(o[n], constExpr);
1032+ inc(n);
1033+ if tok <> sComma then break;
1034+ Next;
1035+ until false;
1036+ { the size: a register's, or what the memory operand says }
1037+ size := 8;
1038+ for i := n - 1 downto 0 do
1039+ if (o[i].kind = oReg) or (o[i].kind = oMem) and (o[i].size <> 0) then size := o[i].size;
1040+ if n > 0 then
1041+ if (o[0].kind = oReg) or (o[0].kind = oMem) and (o[0].size <> 0) then size := o[0].size;
1042+ wide := size = 8;
1043+ byteOp := size = 1;
1044+ if size = 2 then pfx := $66 else pfx := 0;
1045+ if WordIndex(w, Alus) >= 0 then begin
1046+ k := WordIndex(w, Alus);
1047+ Two(k * 8 + 1, k * 8 + 3, $81, k)
1048+ end
1049+ else if w = 'mov' then begin
1050+ if (n = 2) and (o[0].kind = oReg) and (o[1].kind = oImm) and (size >= 4) then begin
1051+ if wide then MovRI(o[0].r, o[1].v)
1052+ else begin Prefix(0, false, 0, NoIndex, o[0].r, false); Put1($B8 + o[0].r and 7); Put4(o[1].v) end;
1053+ end else Two($89, $8B, $C7, 0);
1054+ end else if w = 'test' then Two($85, $85, $F7, 0)
1055+ else if w = 'xchg' then Two($87, $87, -1, 0)
1056+ else if (w = 'cmpxchg') or (w = 'xadd') then begin
1057+ if (n <> 2) or (o[1].kind <> oReg) then Bad;
1058+ if w = 'xadd' then k := $C10F else k := $B10F;
1059+ RM(pfx, wide, k - ord(byteOp) shl 8, o[1].r, o[0], byteOp);
1060+ end else if w = 'lea' then begin
1061+ if (n <> 2) or (o[0].kind <> oReg) or (o[1].kind <> oMem) then Bad;
1062+ RM(pfx, wide, $8D, o[0].r, o[1]);
1063+ end else if (w = 'movzx') or (w = 'movsx') or (w = 'movsxd') then begin
1064+ if (n <> 2) or (o[0].kind <> oReg) or (o[1].kind = oImm) then Bad;
1065+ if w = 'movsxd' then k := $63
1066+ else if o[1].size = 1 then k := $B60F
1067+ else if o[1].size = 2 then k := $B70F
1068+ else Bad;
1069+ if w = 'movsx' then k := k + $0800;
1070+ RM(pfx, wide, k, o[0].r, o[1], o[1].size = 1);
1071+ end else if ((WordIndex(w, Unaries) >= 0) and (n = 1)) or (w = 'inc') or (w = 'dec') then begin
1072+ if o[0].kind = oImm then Bad;
1073+ if w = 'inc' then RM(pfx, wide, $FF - ord(byteOp), 0, o[0], byteOp)
1074+ else if w = 'dec' then RM(pfx, wide, $FF - ord(byteOp), 1, o[0], byteOp)
1075+ else RM(pfx, wide, $F7 - ord(byteOp), WordIndex(w, Unaries) + 2, o[0], byteOp);
1076+ end else if w = 'imul' then begin
1077+ if (n < 2) or (o[0].kind <> oReg) or (o[1].kind = oImm) then Bad;
1078+ if n = 2 then RM(pfx, wide, $AF0F, o[0].r, o[1])
1079+ else begin RM(pfx, wide, $69, o[0].r, o[1]); PutImm(o[2].v, size) end;
1080+ end else if WordIndex(w, Shifts) >= 0 then begin
1081+ k := WordIndex(w, Shifts);
1082+ if k = 6 then k := 4; { sal is shl }
1083+ if (n <> 2) or (o[0].kind = oImm) then Bad;
1084+ if o[1].kind = oImm then begin RM(pfx, wide, $C1 - ord(byteOp), k, o[0], byteOp); Put1(o[1].v) end
1085+ else if (o[1].kind = oReg) and (o[1].r = RCX) and (o[1].size = 1) then RM(pfx, wide, $D3 - ord(byteOp), k, o[0], byteOp)
1086+ else Bad;
1087+ end else if (w = 'push') or (w = 'pop') then begin
1088+ if (n <> 1) or (o[0].kind <> oReg) or not wide then Bad;
1089+ if w = 'push' then Push(o[0].r) else Pop(o[0].r);
1090+ end else if (w = 'call') or (w = 'jmp') then begin
1091+ if (n <> 1) or (o[0].kind = oImm) then Bad;
1092+ if w = 'call' then RM(0, false, $FF, 2, o[0]) else RM(0, false, $FF, 4, o[0]);
1093+ end else if (copy(w, 1, 3) = 'set') and (Cond(copy(w, 4, 3)) >= 0) then begin
1094+ if (n <> 1) or (o[0].kind = oImm) or (size <> 1) then Bad;
1095+ RM(0, false, $900F + Cond(copy(w, 4, 3)) shl 8, 0, o[0], true);
1096+ end else if (copy(w, 1, 4) = 'cmov') and (Cond(copy(w, 5, 3)) >= 0) then begin
1097+ if (n <> 2) or (o[0].kind <> oReg) or (o[1].kind = oImm) then Bad;
1098+ RM(pfx, wide, $400F + Cond(copy(w, 5, 3)) shl 8, o[0].r, o[1]);
1099+ end else if (length(w) > 2) and (WordIndex(copy(w, 1, length(w) - 2), SseOps) >= 0)
1100+ and ((copy(w, length(w) - 1, 2) = 'sd') or (copy(w, length(w) - 1, 2) = 'ss')) then begin
1101+ { sqrtsd, addss and the like: xmm, xmm or memory }
1102+ if (n <> 2) or (o[0].kind <> oXmm) or not (o[1].kind in [oXmm, oMem]) then Bad;
1103+ k := $0F or SseCodes[WordIndex(copy(w, 1, length(w) - 2), SseOps)] shl 8;
1104+ RM(RealPfx[w[length(w)] = 's'], false, k, o[0].r, o[1]);
1105+ end else if WordIndex(w, PackedOps) >= 0 then begin
1106+ if (n < 2) or (o[0].kind <> oXmm) or not (o[1].kind in [oXmm, oMem]) then Bad;
1107+ k := WordIndex(w, PackedOps);
1108+ RM($66, false, $0F or PackedCodes[k] shl 8, o[0].r, o[1]);
1109+ if w = 'pshufd' then begin
1110+ if (n <> 3) or (o[2].kind <> oImm) then Bad;
1111+ Put1(o[2].v);
1112+ end else if n <> 2 then Bad;
1113+ end else if (w = 'movdqu') or (w = 'movdqa') then begin
1114+ { the load is 6F and the store 7F; movdqu is F3, movdqa 66 }
1115+ if w = 'movdqu' then k := $F3 else k := $66;
1116+ if (n = 2) and (o[0].kind = oXmm) and (o[1].kind in [oXmm, oMem]) then RM(k, false, $6F0F, o[0].r, o[1])
1117+ else if (n = 2) and (o[0].kind = oMem) and (o[1].kind = oXmm) then RM(k, false, $7F0F, o[1].r, o[0])
1118+ else Bad;
1119+ end else if w = 'pmovmskb' then begin
1120+ if (n <> 2) or (o[0].kind <> oReg) or (o[1].kind <> oXmm) then Bad;
1121+ RM($66, false, $D70F, o[0].r, o[1]);
1122+ end else if WordIndex(w, BitOps) >= 0 then begin
1123+ if (n <> 2) or (o[0].kind <> oReg) or (o[1].kind = oImm) or (size < 4) then Bad;
1124+ k := WordIndex(w, BitOps);
1125+ RM(BitPfx[k], wide, BitCodes[k], o[0].r, o[1]);
1126+ end else if (w = 'movsd') or (w = 'movss') then begin
1127+ if w = 'movsd' then k := $F2 else k := $F3;
1128+ if (n = 2) and (o[0].kind = oXmm) and (o[1].kind in [oXmm, oMem]) then RM(k, false, $100F, o[0].r, o[1])
1129+ else if (n = 2) and (o[0].kind = oMem) and (o[1].kind = oXmm) then RM(k, false, $110F, o[1].r, o[0])
1130+ else Bad;
1131+ end else if (w = 'movq') or (w = 'movd') then begin
1132+ if (n = 2) and (o[0].kind = oXmm) and (o[1].kind in [oReg, oMem]) then RM($66, w = 'movq', $6E0F, o[0].r, o[1])
1133+ else if (n = 2) and (o[1].kind = oXmm) and (o[0].kind in [oReg, oMem]) then RM($66, w = 'movq', $7E0F, o[1].r, o[0])
1134+ else Bad;
1135+ end else if (w = 'ucomisd') or (w = 'ucomiss') then begin
1136+ if (n <> 2) or (o[0].kind <> oXmm) or not (o[1].kind in [oXmm, oMem]) then Bad;
1137+ if w = 'ucomisd' then RM($66, false, $2E0F, o[0].r, o[1]) else RM(0, false, $2E0F, o[0].r, o[1]);
1138+ end else if (w = 'cvtsi2sd') or (w = 'cvtsi2ss') then begin
1139+ if (n <> 2) or (o[0].kind <> oXmm) or not (o[1].kind in [oReg, oMem]) then Bad;
1140+ RM(RealPfx[w = 'cvtsi2ss'], o[1].size <> 4, $2A0F, o[0].r, o[1]);
1141+ end else if (w = 'cvttsd2si') or (w = 'cvttss2si') then begin
1142+ if (n <> 2) or (o[0].kind <> oReg) or not (o[1].kind in [oXmm, oMem]) then Bad;
1143+ RM(RealPfx[w = 'cvttss2si'], wide, $2C0F, o[0].r, o[1]);
1144+ end else if (w = 'cvtsd2ss') or (w = 'cvtss2sd') then begin
1145+ if (n <> 2) or (o[0].kind <> oXmm) or not (o[1].kind in [oXmm, oMem]) then Bad;
1146+ RM(RealPfx[w = 'cvtss2sd'], false, $5A0F, o[0].r, o[1]);
1147+ end else begin
1148+ k := 0;
1149+ while (k <= High(Plain)) and (Plain[k] <> w) do inc(k);
1150+ if (k > High(Plain)) or (n <> 0) then MarkAt(at, 'unknown instruction ' + w);
1151+ Opcode(PlainOp[k]);
1152+ end;
1153+ end;
1154+ if tok <> sSemicolon then Mark('expected ";"');
1155+ listing := wasListing;
1156+ SayAt(first, Source(SpanFrom(at)));
1157+ Next;
1158+ end;
1159+ for k := 0 to numLabels - 1 do
1160+ if places[k] < 0 then MarkAt(usedAt[k], 'label ' + NameOf(names[k]) + ' isn''t defined');
1161+end;
1162+
1163+{ The listing, raz -S: each live procedure of the module in the order
1164+ it was made, each line of source it comes from, and under it the
1165+ instructions made for it, at their offsets in the procedure; a jump
1166+ within it says where to by its offset too. }
1167+procedure List(module: longint);
1168+var order: ^longint; n, i, j, k, c, t, line: longint; text: shortstring;
1169+begin
1170+ order := GetMem(numChunks * SizeOf(longint));
1171+ n := 0;
1172+ for c := 0 to numChunks - 1 do
1173+ if chunks^[c].live and (chunks^[c].sec = secText) and (chunks^[c].module = module) then begin
1174+ i := n;
1175+ while (i > 0) and (chunks^[order[i - 1]].start > chunks^[c].start) do begin
1176+ order[i] := order[i - 1];
1177+ dec(i);
1178+ end;
1179+ order[i] := c;
1180+ inc(n);
1181+ end;
1182+ i := 0; j := 0;
1183+ for k := 0 to n - 1 do begin
1184+ c := order[k];
1185+ writeln;
1186+ writeln(ChunkName(c), ':');
1187+ line := -1;
1188+ while (i < numSaid) and (said[i].at < chunks^[c].start) do inc(i);
1189+ while (i < numSaid) and (said[i].at < chunks^[c].start + chunks^[c].size) do begin
1190+ while (j < numLines) and (lines^[j].at <= said[i].at) do begin
1191+ if (lines^[j].chunk = c) and (lines^[j].line <> line) then begin
1192+ line := lines^[j].line;
1193+ writeln(line: 6, ' ', LineText(NameOf(lines^[j].path), line));
1194+ end;
1195+ inc(j);
1196+ end;
1197+ text := said[i].text;
1198+ t := said[i].at;
1199+ if (text = 'jmp') or (text = 'call') then text := text + ' ' + IntStr(t + 5 + Get4At(t + 1) - chunks^[c].start)
1200+ else if (text[1] = 'j') and (pos(' ', text) = 0) then text := text + ' ' + IntStr(t + 6 + Get4At(t + 2) - chunks^[c].start);
1201+ writeln(t - chunks^[c].start: 14, ' ', text);
1202+ inc(i);
1203+ end;
1204+ end;
1205+ FreeMem(order);
1206+end;
1207+
1208+end.

self/Chunk.raz deleted +0 -354

@@ -1,354 +0,0 @@
1-(* Chunk: the compiled program, before it is linked.
2-
3- The code of a program is a set of chunks: one per procedure, module
4- variable and string. A chunk's bytes go in one of three sections:
5- text (code), rodata (strings and other constants), bss (variables,
6- which are all zero). A reference from code to another chunk (a call,
7- or an address) is a fixup, patched once the linker has placed every
8- chunk. Line notes say which place in the source the code from each
9- point on is for.
10-
11- Nothing here depends on the machine: text is bytes, written by the
12- encoder for the target (X64).
13-
14- Depends on: Scan, for names and memory; Diag, for positions.
15- Leaves out: the instructions; that is X64.
16-
17- Exported variables can't be set from outside, so the setters at the
18- end do what the seed's other units do to these. *)
19-module Chunk;
20-import Fmt, Diag, Scan;
21-
22-type
23- Section* = (secText, secRodata, secBss);
24-
25- Chunk* = record
26- sec*: Section;
27- start*, size*, align*: INT; (* in its section's buffer *)
28- firstFix*, numFix*: INT; (* its fixups: text's in fixups, rodata's in dataFixups *)
29- home*, name*: INT; (* its module and its name, for the symbol table; -1 if none *)
30- adr*: INT; (* its address, set by the linker *)
31- live*: BOOL; (* reached from the entry point *)
32- ext*: BOOL; (* bss: the address of a C symbol, its name *)
33- reals*: BOOL; (* code: computes with reals, first at realsAt *)
34- realsAt*: Diag.Pos;
35- saveMask*: INT; (* code: the registers of variables it saves, as bits of Gen's VarRegs *)
36- saveAt*: INT; (* ... at this offset from the frame, one quadword each *)
37- end;
38-
39- (* A place in the source whose code starts at a place in text: for
40- gdb, and for Rt to say where a failed check or a signal was *)
41- Line* = record
42- at*, chunk*: INT; (* the place in text, and its chunk *)
43- path*, line*, col*: INT; (* the file's path, interned, the line and column *)
44- end;
45-
46- (* A variable of a procedure, for the trap report: Rt shows it, by
47- kind, from its place in the frame *)
48- VarNote* = record
49- chunk*, name*: INT;
50- off*: INT; (* from the frame pointer *)
51- kind*: INT; (* how Rt shows it: see Link *)
52- end;
53-
54- Fixup* = record
55- at*: INT; (* the 32-bit field, as an offset in text; in
56- dataFixups, the 64-bit one, from its chunk's start *)
57- chunk*: INT; (* the chunk it refers to *)
58- addend*: INT; (* added to the chunk's address *)
59- end;
60-
61-var
62- text*: ^U8; (* text *)
63- pc*: INT; (* its length *)
64- rodata*: ^U8;
65- rolen*: INT;
66- chunks*: ^Chunk;
67- numChunks*: INT;
68- fixups*: ^Fixup;
69- numFixups*: INT;
70- (* Addresses in read-only data, as in an array constant of strings:
71- each 8 bytes, the chunk's absolute address, since the executable
72- is loaded where the linker placed it *)
73- dataFixups*: ^Fixup;
74- numDataFixups*: INT;
75- lines*: ^Line;
76- numLines*: INT;
77- curFile: INT; (* the file being compiled, for noteLine *)
78- curChunk*: INT; (* the chunk of code being written *)
79- varNotes*: ^VarNote;
80- numVarNotes*: INT;
81-
82- codeCap, roCap, chunkCap, fixCap, dataFixCap, lineCap, noteCap: INT;
83-
84-(* Room for n more bytes of code *)
85-proc room(n: INT);
86-begin
87- if pc + n > codeCap then
88- text := Scan.regrab(text, pc, codeCap * 2 + n);
89- codeCap := codeCap * 2 + n;
90- end;
91-end;
92-
93-proc put1*(b: INT);
94-begin
95- if pc + 16 > codeCap then room(16); end;
96- text[pc] := U8(b & 0FFH);
97- INC(pc);
98-end;
99-
100-(* The low 32 bits of v, least significant byte first *)
101-proc put4*(v: INT);
102-var i: INT;
103-begin
104- if pc + 16 > codeCap then room(16); end;
105- for i := 0 to 3 do text[pc + i] := U8((v shr (8 * i)) & 0FFH); end;
106- INC(pc, 4);
107-end;
108-
109-proc put4At*(at, v: INT);
110-var i: INT;
111-begin
112- for i := 0 to 3 do text[at + i] := U8((v shr (8 * i)) & 0FFH); end;
113-end;
114-
115-(* The 32 bits at at, as a signed number *)
116-proc get4At*(at: INT): INT;
117-var u, i: INT;
118-begin
119- u := 0;
120- for i := 0 to 3 do u := u * 256 + INT(text[at + 3 - i]); end;
121- if u >= 80000000H then u := u - 100000000H; end;
122- return u;
123-end;
124-
125-(* The last n bytes of code taken back. A line noted past the new end
126- now starts there, in place of one noted there before, as noteLine
127- would have it. *)
128-proc takeBack*(n: INT);
129-begin
130- DEC(pc, n);
131- if (numLines > 0) and (lines[numLines - 1].at > pc) then
132- lines[numLines - 1].at := pc;
133- if (numLines > 1) and (lines[numLines - 2].at = pc) then
134- lines[numLines - 2] := lines[numLines - 1];
135- DEC(numLines);
136- end;
137- end;
138-end;
139-
140-proc put8*(v: I64);
141-begin
142- put4(INT(v & 0FFFFFFFFH));
143- put4(INT((v shr 32) & 0FFFFFFFFH));
144-end;
145-
146-proc newChunk*(sec: Section; home, name: INT): INT;
147-var c: ^Chunk;
148-begin
149- if numChunks = chunkCap then
150- chunks := ^Chunk(Scan.regrab(^U8(chunks), numChunks * SIZE(Chunk), chunkCap * 2 * SIZE(Chunk)));
151- chunkCap := chunkCap * 2;
152- end;
153- c := ADR(chunks[numChunks]);
154- c^ := {};
155- c^.sec := sec;
156- c^.home := home;
157- c^.name := name;
158- c^.align := 1;
159- c^.size := -1; (* not yet defined *)
160- INC(numChunks);
161- return numChunks - 1;
162-end;
163-
164-proc beginChunk*(c: INT);
165-begin
166- (* code is aligned to 32 bytes, the windows in which x86 fetches and
167- caches it, so that a procedure's loops sit in them the same way
168- whatever comes before: rat ran 5% slower at 16, by where its loops
169- fell. Padded with CC, x86's int3: a trap if it were ever run *)
170- while pc & 31 # 0 do put1(0CCH); end;
171- curChunk := c;
172- chunks[c].start := pc;
173- chunks[c].align := 32;
174- chunks[c].firstFix := numFixups;
175-end;
176-
177-proc endChunk*(c: INT);
178-begin
179- chunks[c].size := pc - chunks[c].start;
180- chunks[c].numFix := numFixups - chunks[c].firstFix;
181-end;
182-
183-(* The n bytes at p are the data of rodata chunk c *)
184-proc setData*(c: INT; p: ^U8; n, align: INT);
185-begin
186- if rolen + n > roCap then
187- rodata := Scan.regrab(rodata, rolen, roCap * 2 + n);
188- roCap := roCap * 2 + n;
189- end;
190- COPY(rodata[rolen..rolen + n], p[0..n]);
191- chunks[c].firstFix := numDataFixups;
192- chunks[c].numFix := 0;
193- chunks[c].start := rolen;
194- chunks[c].size := n;
195- chunks[c].align := align;
196- INC(rolen, n);
197-end;
198-
199-proc setBss*(c: INT; size, align: INT);
200-begin
201- chunks[c].size := size;
202- chunks[c].align := align;
203-end;
204-
205-(* The code from here on is for line and column of the current file. A
206- place with no code of its own gives way to the next. *)
207-proc noteLine*(line, col: INT);
208-begin
209- if (numLines > 0) and (lines[numLines - 1].at = pc) then DEC(numLines); end;
210- if (numLines > 0) and (lines[numLines - 1].chunk = curChunk) and (lines[numLines - 1].line = line)
211- and (lines[numLines - 1].col = col) and (lines[numLines - 1].path = curFile) then
212- return;
213- end;
214- if numLines = lineCap then
215- lines := ^Line(Scan.regrab(^U8(lines), numLines * SIZE(Line), lineCap * 2 * SIZE(Line)));
216- lineCap := lineCap * 2;
217- end;
218- lines[numLines].at := pc;
219- lines[numLines].chunk := curChunk;
220- lines[numLines].path := curFile;
221- lines[numLines].line := line;
222- lines[numLines].col := col;
223- INC(numLines);
224-end;
225-
226-(* The quadword that holds the address of C's symbol name, filled in
227- when the program starts; one for each name. *)
228-proc externChunk*(name: INT): INT;
229-var c: INT;
230-begin
231- for c := 0 to numChunks - 1 do
232- if chunks[c].ext and (chunks[c].name = name) then return c; end;
233- end;
234- c := newChunk(secBss, -1, name);
235- setBss(c, 8, 8);
236- chunks[c].ext := true;
237- return c;
238-end;
239-
240-proc addFixup*(at, chunk, addend: INT);
241-begin
242- if numFixups = fixCap then
243- fixups := ^Fixup(Scan.regrab(^U8(fixups), numFixups * SIZE(Fixup), fixCap * 2 * SIZE(Fixup)));
244- fixCap := fixCap * 2;
245- end;
246- fixups[numFixups].at := at;
247- fixups[numFixups].chunk := chunk;
248- fixups[numFixups].addend := addend;
249- INC(numFixups);
250-end;
251-
252-(* The address of chunk, plus addend, at offset at of rodata chunk c,
253- whose data is set: its fixups follow one another. *)
254-proc addDataFixup*(c, at, chunk, addend: INT);
255-begin
256- if numDataFixups = dataFixCap then
257- dataFixups := ^Fixup(Scan.regrab(^U8(dataFixups), numDataFixups * SIZE(Fixup), dataFixCap * 2 * SIZE(Fixup)));
258- dataFixCap := dataFixCap * 2;
259- end;
260- dataFixups[numDataFixups].at := at;
261- dataFixups[numDataFixups].chunk := chunk;
262- dataFixups[numDataFixups].addend := addend;
263- INC(numDataFixups);
264- INC(chunks[c].numFix);
265-end;
266-
267-proc noteVar*(chunk, name, off, kind: INT);
268-begin
269- if numVarNotes = noteCap then
270- varNotes := ^VarNote(Scan.regrab(^U8(varNotes), numVarNotes * SIZE(VarNote), noteCap * 2 * SIZE(VarNote)));
271- noteCap := noteCap * 2;
272- end;
273- varNotes[numVarNotes].chunk := chunk;
274- varNotes[numVarNotes].name := name;
275- varNotes[numVarNotes].off := off;
276- varNotes[numVarNotes].kind := kind;
277- INC(numVarNotes);
278-end;
279-
280-(* The name of chunk c: its module's and its own, or literal and its
281- number for a literal *)
282-proc chunkName*(c: INT): []U8;
283-begin
284- if chunks[c].name < 0 then return Diag.say("literal{}", [Fmt.int(c)]); end;
285- if chunks[c].home < 0 then return Scan.nameOf(chunks[c].name); end;
286- return Diag.say("{}.{}", [Fmt.str(Scan.nameOf(chunks[c].home)), Fmt.str(Scan.nameOf(chunks[c].name))]);
287-end;
288-
289-(* What Gen's Redo and Rewind put back: the code, fixups and lines made
290- since are forgotten *)
291-proc rewindTo*(atPc, atFixups, atLines: INT);
292-begin
293- pc := atPc;
294- numFixups := atFixups;
295- numLines := atLines;
296-end;
297-
298-(* The file the code is being made from, as its path interned *)
299-proc setCurFile*(path: INT);
300-begin
301- curFile := path;
302-end;
303-
304-proc curFilePath*: INT;
305-begin
306- return curFile;
307-end;
308-
309-proc setLive*(c: INT);
310-begin
311- chunks[c].live := true;
312-end;
313-
314-proc setAdr*(c: INT; a: INT);
315-begin
316- chunks[c].adr := a;
317-end;
318-
319-(* Chunk c computes with reals, the first of them at p *)
320-proc setReals*(c: INT; p: Diag.Pos);
321-begin
322- chunks[c].reals := true;
323- chunks[c].realsAt := p;
324-end;
325-
326-proc setSaves*(c, mask, at: INT);
327-begin
328- chunks[c].saveMask := mask;
329- chunks[c].saveAt := at;
330-end;
331-
332-begin
333- codeCap := 1 shl 20;
334- text := Scan.grab(codeCap);
335- pc := 0;
336- roCap := 1 shl 16;
337- rodata := Scan.grab(roCap);
338- rolen := 0;
339- chunkCap := 1 shl 10;
340- chunks := ^Chunk(Scan.grab(chunkCap * SIZE(Chunk)));
341- numChunks := 0;
342- fixCap := 1 shl 12;
343- fixups := ^Fixup(Scan.grab(fixCap * SIZE(Fixup)));
344- numFixups := 0;
345- dataFixCap := 1 shl 8;
346- dataFixups := ^Fixup(Scan.grab(dataFixCap * SIZE(Fixup)));
347- numDataFixups := 0;
348- lineCap := 1 shl 12;
349- lines := ^Line(Scan.grab(lineCap * SIZE(Line)));
350- numLines := 0;
351- noteCap := 1 shl 8;
352- varNotes := ^VarNote(Scan.grab(noteCap * SIZE(VarNote)));
353- numVarNotes := 0;
354-end Chunk.

self/Diag.raz deleted +0 -410

@@ -1,410 +0,0 @@
1-(* Diag: messages.
2-
3- The one place the compiler's messages are made. A message is an
4- error or a warning at a position, which it shows as the file, line
5- and column, then the line of source with the position underlined;
6- notes, each at a position of its own, and help, a line of advice,
7- may follow it. Colour is used when standard error is a terminal and
8- NO_COLOR isn't set. Diag keeps every source file it is given, so
9- that a note can show a line of a module compiled earlier.
10-
11- Depends on: Sys, to write and to ask about the terminal; Buf and Fmt,
12- to build what it writes.
13- Leaves out: wording. The callers say what is wrong, with say; a
14- message is at most 255 characters, which every message so far keeps
15- well within. A message made by say is kept for good, since it is
16- made only where it is about to be shown. *)
17-module Diag;
18-import Sys, Rt, Heap, Mem, Buf, Fmt, Str;
19-
20-type
21- (* A stretch of a source file: bytes a up to but not including b.
22- a = b marks the place between two characters. *)
23- Pos* = record f*, a*, b*: INT; end;
24-
25- File = record
26- path: []U8;
27- buf: ^U8;
28- len: INT;
29- end;
30-
31-const
32- MaxErrors* = 20;
33- Bold = "\x1B[1m"; Red = "\x1B[1;31m"; Yellow = "\x1B[1;33m";
34- Cyan = "\x1B[1;36m"; Green = "\x1B[1;32m"; Blue = "\x1B[1;34m";
35- Plain = "\x1B[0m";
36- (* A long line is shown cut to this many bytes around the place, its
37- cut ends marked ... *)
38- ShownBytes = 100;
39-
40-var
41- errors*, warnings*: INT;
42- werror*: BOOL; (* -Werror: a warning counts as an error *)
43- (* The construct being read uses a name already reported as not
44- declared: its errors follow from that one, and aren't shown. *)
45- quiet*: BOOL;
46-
47- files: ^File; (* numFiles of them, in room for cap *)
48- numFiles, cap: INT;
49- colour, colourKnown, cwdKnown: BOOL;
50- cwd: Buf.Buf; (* the working directory and a /, or empty if unknown *)
51- out: Buf.Buf; (* the message being made *)
52- lastError: Pos; (* where the last error was *)
53- shown: BOOL; (* whether it was shown: its notes and help are only then *)
54-
55-(* Exported variables can't be set from outside, so these do it. *)
56-proc setWerror*(yes: BOOL);
57-begin
58- werror := yes;
59-end;
60-
61-proc setQuiet*(yes: BOOL);
62-begin
63- quiet := yes;
64-end;
65-
66-(* Paths are shown from the working directory where they are under it,
67- so messages read the same wherever the compiler or its library is. *)
68-proc shownPath*(path: []U8): []U8;
69-var d: []U8; err: INT; c: []U8;
70-begin
71- if not cwdKnown then
72- d, err := Sys.workDir();
73- if err = 0 then
74- Buf.str(ADR(cwd), d);
75- Buf.add(ADR(cwd), '/');
76- end;
77- cwdKnown := true;
78- end;
79- c := Buf.bytes(ADR(cwd));
80- if (LEN(c) > 0) and Str.hasPrefix(path, c) then return path[LEN(c)..LEN(path)]; end;
81- return path;
82-end;
83-
84-proc fatal*(msg: []U8); forward;
85-
86-(* Memory, or the end of the compile when there is none *)
87-proc grab(size: INT): ^U8;
88-var p: ^U8;
89-begin
90- p := Mem.alloc(Heap.heap, size, 8);
91- if p = nil then fatal("out of memory"); end;
92- return p;
93-end;
94-
95-(* Keeps buf, len bytes of a file, under a number, which it gives back;
96- buf stays as it is, and its path is copied. *)
97-proc addFile*(path: []U8; buf: ^U8; len: INT): INT;
98-var more: ^File; i: INT; p: []U8; ok: BOOL;
99-begin
100- if numFiles = cap then
101- more := ^File(grab((2 * cap + 8) * SIZE(File)));
102- for i := 0 to numFiles - 1 do more[i] := files[i]; end;
103- if files # nil then Mem.free(Heap.heap, ^U8(files)); end;
104- files := more;
105- cap := 2 * cap + 8;
106- end;
107- p, ok := Str.copy(Heap.heap, shownPath(path));
108- if not ok then fatal("out of memory"); end;
109- files[numFiles] := {path: p, buf: buf, len: len};
110- INC(numFiles);
111- return numFiles - 1;
112-end;
113-
114-proc pathOf*(f: INT): []U8;
115-begin
116- return files[f].path;
117-end;
118-
119-(* Writing *)
120-
121-(* Whether NO_COLOR is set. The library can't tell it set to nothing
122- from not set, so that counts as not set, as no-color.org has it. *)
123-proc noColour: BOOL;
124-begin
125- return LEN(Sys.env("NO_COLOR")) > 0;
126-end;
127-
128-proc put(s: []U8);
129-begin
130- Buf.str(ADR(out), s);
131-end;
132-
133-proc putc(c: U8);
134-begin
135- Buf.add(ADR(out), c);
136-end;
137-
138-proc putNum(n: INT);
139-begin
140- Fmt.write(ADR(out), "{}", [Fmt.int(n)]);
141-end;
142-
143-(* The text of a number *)
144-proc say*(f: []U8; args: []Fmt.Arg): []U8;
145-var b: ^Buf.Buf;
146-begin
147- b := ^Buf.Buf(grab(SIZE(Buf.Buf)));
148- Buf.init(b, Heap.heap);
149- Fmt.write(b, f, args);
150- return Buf.bytes(b);
151-end;
152-
153-(* c, when colour is on *)
154-proc paintOn(c: []U8);
155-begin
156- if not colourKnown then
157- colour := Sys.isTerminal(2) and not noColour();
158- colourKnown := true;
159- end;
160- if colour then put(c); end;
161-end;
162-
163-(* s in colour c, when colour is on *)
164-proc paint(c, s: []U8);
165-begin
166- paintOn(c);
167- put(s);
168- paintOn(Plain);
169-end;
170-
171-(* What has been made, written to standard error *)
172-proc flush;
173-var s: []U8; n: INT;
174-begin
175- s := Buf.bytes(ADR(out));
176- while LEN(s) > 0 do
177- n := Sys.write(Sys.stderr, s);
178- if n <= 0 then break; end;
179- s := s[n..LEN(s)];
180- end;
181- Buf.reset(ADR(out));
182-end;
183-
184-(* Positions *)
185-
186-(* The line of p, and the byte where it starts. Lines are counted from
187- the start of the file, which is slow only next to compiling it. *)
188-proc locate(p: Pos): (INT, INT);
189-var i, line, start: INT; buf: ^U8;
190-begin
191- buf := files[p.f].buf;
192- line := 1;
193- start := 0;
194- for i := 0 to p.a - 1 do
195- if buf[i] = 10 then INC(line); start := i + 1; end;
196- end;
197- return line, start;
198-end;
199-
200-proc lineOf*(p: Pos): INT;
201-var line: INT;
202-begin
203- line, _ := locate(p);
204- return line;
205-end;
206-
207-(* A byte that starts a character: every one but a UTF-8 continuation *)
208-proc starts(c: U8): BOOL;
209-begin
210- return (c & 0C0H) # 80H;
211-end;
212-
213-(* Characters from byte i to byte j of buf *)
214-proc chars(buf: ^U8; i, j: INT): INT;
215-var n: INT;
216-begin
217- n := 0;
218- while i < j do
219- if starts(buf[i]) then INC(n); end;
220- INC(i);
221- end;
222- return n;
223-end;
224-
225-(* "file:line:col: kind: msg", then the line with p underlined. A tab
226- before p is copied into the underline, so that the two line up
227- whatever the terminal makes of tabs. *)
228-proc show(p: Pos; kind, kindColour, msg: []U8);
229-var line, start, stop, lo, hi, i, n: INT; buf: ^U8; f: ^File; digits: []U8;
230-begin
231- if p.f >= numFiles then
232- (* about no place in a file, as for Rt, which the compiler
233- imports before it reads one *)
234- paint(Bold, "raz:");
235- put(" ");
236- paintOn(kindColour); put(kind); put(":"); paintOn(Plain);
237- put(" ");
238- paint(Bold, msg);
239- putc('\n');
240- flush;
241- return;
242- end;
243- line, start := locate(p);
244- f := ADR(files[p.f]);
245- buf := f^.buf;
246- paintOn(Bold);
247- put(f^.path); put(":"); putNum(line); put(":"); putNum(chars(buf, start, p.a) + 1); put(":");
248- paintOn(Plain);
249- put(" ");
250- paintOn(kindColour); put(kind); put(":"); paintOn(Plain);
251- put(" ");
252- paint(Bold, msg);
253- putc('\n');
254- stop := start;
255- while (stop < f^.len) and (buf[stop] # 10) do INC(stop); end;
256- lo := start;
257- hi := stop;
258- if hi - lo > ShownBytes then
259- if p.a - lo > ShownBytes div 2 then lo := p.a - ShownBytes div 2; end;
260- while not starts(buf[lo]) do INC(lo); end;
261- if hi - lo > ShownBytes then hi := lo + ShownBytes; end;
262- while (hi < stop) and not starts(buf[hi]) do INC(hi); end;
263- end;
264- paintOn(Blue);
265- digits := say("{}", [Fmt.int(line)]);
266- for i := LEN(digits) to 4 do put(" "); end;
267- put(digits); put(" |");
268- paintOn(Plain);
269- put(" ");
270- if lo > start then put("..."); end;
271- put(buf[lo..hi]);
272- if hi < stop then put("..."); end;
273- putc('\n');
274- paint(Blue, " |");
275- put(" ");
276- if lo > start then put(" "); end;
277- for i := lo to p.a - 1 do
278- if buf[i] = '\t' then putc('\t'); elsif starts(buf[i]) then putc(' '); end;
279- end;
280- if p.b < hi then n := chars(buf, p.a, p.b); else n := chars(buf, p.a, hi); end;
281- if n < 1 then n := 1; end;
282- paintOn(kindColour);
283- for i := 1 to n do putc('^'); end;
284- paintOn(Plain);
285- putc('\n');
286- flush;
287-end;
288-
289-(* From the start of p to the end of q *)
290-proc join*(p, q: Pos): Pos;
291-begin
292- p.b := q.b;
293- return p;
294-end;
295-
296-(* The text at p, at most the 255 bytes a message can hold *)
297-proc source*(p: Pos): []U8;
298-var n: INT;
299-begin
300- n := p.b - p.a;
301- if n > 255 then n := 255; end;
302- return files[p.f].buf[p.a..p.a + n];
303-end;
304-
305-(* Messages *)
306-
307-(* Line line of the file at path, as written, to at most 255 bytes *)
308-proc lineText*(path: []U8; line: INT): []U8;
309-var i, k, n, j: INT; f: ^File; want: []U8;
310-begin
311- want := shownPath(path);
312- for i := 0 to numFiles - 1 do
313- f := ADR(files[i]);
314- if f^.path = want then
315- k := 0;
316- n := 1;
317- while (n < line) and (k < f^.len) do
318- if f^.buf[k] = 10 then INC(n); end;
319- INC(k);
320- end;
321- j := k;
322- while (j < f^.len) and (f^.buf[j] # 10) and (j - k < 255) do INC(j); end;
323- return f^.buf[k..j];
324- end;
325- end;
326- return "";
327-end;
328-
329-proc error*(p: Pos; msg: []U8);
330-begin
331- (* a second error at one place follows from the first: when a symbol
332- ends a construct with an error, the one around it may stop there too *)
333- shown := not quiet and not ((errors > 0) and (p.f = lastError.f) and (p.a = lastError.a));
334- if not shown then return; end;
335- lastError := p;
336- show(p, "error", Red, msg);
337- INC(errors);
338- if errors >= MaxErrors then
339- put("raz: stopping after ");
340- putNum(MaxErrors);
341- put(" errors\n");
342- flush;
343- Rt.exit(1);
344- end;
345-end;
346-
347-proc warning*(p: Pos; msg: []U8);
348-begin
349- if werror then
350- error(p, msg);
351- else
352- show(p, "warning", Yellow, msg);
353- shown := true;
354- INC(warnings);
355- end;
356-end;
357-
358-(* Notes and help follow an error or a warning, and are shown with it *)
359-proc note*(p: Pos; msg: []U8);
360-begin
361- if shown then show(p, "note", Cyan, msg); end;
362-end;
363-
364-proc help*(msg: []U8);
365-begin
366- if shown then
367- paint(Green, "help:");
368- put(" ");
369- put(msg);
370- putc('\n');
371- flush;
372- end;
373-end;
374-
375-(* An error with no place in the source, such as a file that can't be
376- read: it stops the compiler at once. *)
377-proc fatal*(msg: []U8);
378-begin
379- put("raz: ");
380- put(msg);
381- putc('\n');
382- flush;
383- Rt.exit(1);
384-end;
385-
386-proc count(n: INT; what: []U8): []U8;
387-begin
388- if n = 1 then return say("1 {}", [Fmt.str(what)]); end;
389- return say("{} {}s", [Fmt.int(n), Fmt.str(what)]);
390-end;
391-
392-(* Says how many errors and warnings there were, and stops the compiler
393- if there were errors. *)
394-proc finish*;
395-begin
396- if (errors > 0) and (warnings > 0) then
397- put("raz: "); put(count(errors, "error")); put(", "); put(count(warnings, "warning")); putc('\n');
398- elsif errors > 0 then
399- put("raz: "); put(count(errors, "error")); putc('\n');
400- elsif warnings > 0 then
401- put("raz: "); put(count(warnings, "warning")); putc('\n');
402- end;
403- flush;
404- if errors > 0 then Rt.exit(1); end;
405-end;
406-
407-begin
408- Buf.init(ADR(cwd), Heap.heap);
409- Buf.init(ADR(out), Heap.heap);
410-end Diag.

self/Elf.raz deleted +0 -431

@@ -1,431 +0,0 @@
1-(* Elf: the executable file.
2-
3- Writes an ELF64 executable for x86-64 Linux: the ELF header, the
4- program headers, the linked text and rodata, and section headers
5- with a symbol table, so that objdump and gdb can name each procedure
6- and variable. For gdb's line numbers there is DWARF 4: a line table
7- (.debug_line), and the one compile unit that points to it
8- (.debug_info, .debug_abbrev). There are no types or variables.
9-
10- A program that uses C is linked dynamically, in the least way the
11- loader accepts: it names its loader and libraries, and each C symbol
12- it uses is a quadword the loader fills in with the symbol's address
13- (a GLOB_DAT relocation), which the code calls or reads through.
14- There is no PLT and no lazy binding, and the program exports nothing.
15-
16- Depends on: Link for the images and addresses, Chunk for the chunks,
17- Scan for names and memory, Diag for errors, Sys and Files to write
18- the file.
19- Leaves out: position independent executables, symbol versions, the
20- rest of DWARF.
21-
22- Exported variables can't be set from outside, so needLib, setMainPath
23- and setStripped do it. *)
24-module Elf;
25-import Sys, Files, Fmt, Diag, Scan, Chunk, Link;
26-
27-var
28- needed: [32]INT; (* the libraries to load, names interned *)
29- numNeeded*: INT; (* none: a static program *)
30- mainPath: []U8; (* the main module's file, for gdb *)
31- stripped*: BOOL; (* -s: no symbols and no line numbers; the sections are there, empty *)
32-
33- buf: ^U8;
34- len, cap: INT;
35-
36-(* The library name, to be loaded, unless it is already: false if there
37- are too many *)
38-proc needLib*(name: INT): BOOL;
39-var i: INT;
40-begin
41- for i := 0 to numNeeded - 1 do
42- if needed[i] = name then return true; end;
43- end;
44- if numNeeded = 32 then return false; end;
45- needed[numNeeded] := name;
46- INC(numNeeded);
47- return true;
48-end;
49-
50-(* A static program again *)
51-proc noLibs*;
52-begin
53- numNeeded := 0;
54-end;
55-
56-proc setMainPath*(path: []U8);
57-begin
58- mainPath := path;
59-end;
60-
61-proc setStripped*(yes: BOOL);
62-begin
63- stripped := yes;
64-end;
65-
66-proc room(n: INT);
67-begin
68- if len + n > cap then
69- buf := Scan.regrab(buf, len, cap * 2 + n);
70- cap := cap * 2 + n;
71- end;
72-end;
73-
74-(* The n low bytes of v, least significant first *)
75-proc putN(v: INT; n: INT);
76-var i: INT;
77-begin
78- room(n);
79- for i := 0 to n - 1 do
80- buf[len] := U8(v & 0FFH);
81- v := v shr 8;
82- INC(len);
83- end;
84-end;
85-
86-proc putBytes(p: ^U8; n: INT);
87-begin
88- room(n);
89- if n > 0 then COPY(buf[len..len + n], p[0..n]); end;
90- len := len + n;
91-end;
92-
93-proc padTo(off: INT);
94-begin
95- while len < off do putN(0, 1); end;
96-end;
97-
98-proc patch(at: INT; v: INT; n: INT);
99-var i: INT;
100-begin
101- for i := 0 to n - 1 do
102- buf[at + i] := U8(v & 0FFH);
103- v := v shr 8;
104- end;
105-end;
106-
107-proc phdr(typ, flags: INT; off, adr, filesz, memsz, align: INT);
108-begin
109- putN(typ, 4);
110- putN(flags, 4);
111- putN(off, 8);
112- putN(adr, 8);
113- putN(adr, 8);
114- putN(filesz, 8);
115- putN(memsz, 8);
116- putN(align, 8);
117-end;
118-
119-const
120- (* the section names, in .shstrtab; a section header names its own *)
121- ShNames = "\0.text\0.rodata\0.bss\0.symtab\0.strtab\0.shstrtab\0.dynamic\0.dynstr\0.dynsym\0.debug_line\0.debug_info\0.debug_abbrev\0";
122-
123-(* Where in ShNames the name is: the byte after a zero that starts it and
124- is followed by one; the empty name, found nowhere, is 0 *)
125-proc nameAt(name: []U8): INT;
126-var i, k: INT; same: BOOL;
127-begin
128- for i := 1 to LEN(ShNames) - LEN(name) - 1 do
129- if ShNames[i - 1] = 0 then
130- same := ShNames[i + LEN(name)] = 0;
131- for k := 0 to LEN(name) - 1 do
132- if ShNames[i + k] # name[k] then same := false; end;
133- end;
134- if same and (LEN(name) > 0) then return i; end;
135- end;
136- end;
137- return 0;
138-end;
139-
140-(* A section header. Its name is stored as its offset in ShNames. *)
141-proc shdr(name: []U8; typ: INT; flags, adr, off, size: INT; lnk, info: INT; align, entsize: INT);
142-begin
143- putN(nameAt(name), 4); putN(typ, 4); putN(flags, 8); putN(adr, 8);
144- putN(off, 8); putN(size, 8); putN(lnk, 4); putN(info, 4);
145- putN(align, 8); putN(entsize, 8);
146-end;
147-
148-proc putStr(s: []U8);
149-begin
150- putBytes(ADR(s[0]), LEN(s));
151- putN(0, 1);
152-end;
153-
154-(* LEB128, unsigned *)
155-proc putU(v: INT);
156-begin
157- while v >= 80H do
158- putN(v & 7FH | 80H, 1);
159- v := v shr 7;
160- end;
161- putN(v, 1);
162-end;
163-
164-(* The compile unit, which names the line table, and its abbreviation;
165- the table itself is in the places, in rodata (Link). Section
166- offsets go in off, sizes in size: line, info, abbrev. *)
167-proc putDebug(off, size: []INT);
168-var cwd: []U8; err: INT;
169-begin
170- off[0] := Chunk.chunks[Link.placesChunk].adr - Link.roAdr + Link.roOff + Link.linesOff;
171- size[0] := Link.linesSize;
172- off[1] := len;
173- putN(0, 4); putN(4, 2); putN(0, 4); putN(8, 1); (* length, version, abbrev, address size *)
174- putU(1);
175- putStr(mainPath);
176- cwd, err := Sys.workDir();
177- if err # 0 then cwd := ""; end;
178- putStr(cwd);
179- putStr("raz");
180- putN(0, 4); (* the line table, at 0 *)
181- putN(Link.Base + Link.textOff, 8); putN(Link.textSize, 8); (* the code, all of it *)
182- patch(off[1], len - off[1] - 4, 4);
183- size[1] := len - off[1];
184-
185- off[2] := len;
186- putU(1); putU(11H); putN(0, 1); (* 1: a compile unit, no children *)
187- putU(03H); putU(08H); (* name, a string *)
188- putU(1BH); putU(08H); (* comp_dir, a string *)
189- putU(25H); putU(08H); (* producer, a string *)
190- putU(10H); putU(17H); (* stmt_list, a section offset *)
191- putU(11H); putU(01H); (* low_pc, an address *)
192- putU(12H); putU(07H); (* high_pc, a length in 8 bytes *)
193- putN(0, 2); putN(0, 1);
194- size[2] := len - off[2];
195-end;
196-
197-const
198- Interp = "/lib64/ld-linux-x86-64.so.2";
199- (* program header types *)
200- PtLoad = 1; PtDynamic = 2; PtInterp = 3; PtGnuStack = 6474E551H;
201-
202-var
203- (* in the room at the end of rodata: where each of the loader's
204- tables starts, from extraAdr *)
205- symAt, relaAt, hashAt, strAt: INT;
206- nsym, strLen: INT;
207-
208-(* Whether chunk c is a C symbol the program uses *)
209-proc isExt(c: INT): BOOL;
210-begin
211- return Chunk.chunks[c].live and Chunk.chunks[c].ext;
212-end;
213-
214-(* The sizes of the loader's tables: what linkAll must leave room for. *)
215-proc sizeTables(roExtra, dynSize: ^INT);
216-var c, i: INT;
217-begin
218- nsym := 1;
219- strLen := 1;
220- for i := 0 to numNeeded - 1 do strLen := strLen + LEN(Scan.nameOf(needed[i])) + 1; end;
221- for c := 0 to Chunk.numChunks - 1 do
222- if isExt(c) then
223- INC(nsym);
224- strLen := strLen + LEN(Scan.nameOf(Chunk.chunks[c].name)) + 1;
225- end;
226- end;
227- symAt := (LEN(Interp) + 1 + 7) div 8 * 8;
228- relaAt := symAt + nsym * 24;
229- hashAt := relaAt + (nsym - 1) * 24;
230- strAt := hashAt + 4 * (3 + nsym);
231- roExtra^ := strAt + strLen;
232- dynSize^ := (numNeeded + 10) * 16;
233-end;
234-
235-(* The loader's tables in the room at the end of rodata, which the
236- buffer already holds as zeros: the loader's name; the symbols, one
237- for each C symbol used; a GLOB_DAT relocation for each, at its
238- quadword; a hash table of one bucket; and their names. *)
239-proc putTables;
240-var c, k, i, at, name: INT;
241-begin
242- len := Link.extraAdr - Link.roAdr + Link.roOff;
243- putStr(Interp);
244- padTo(Link.extraAdr - Link.roAdr + Link.roOff + symAt);
245- putN(0, 24);
246- name := strLen;
247- for c := Chunk.numChunks - 1 to 0 by -1 do (* names go last in the string table *)
248- if isExt(c) then name := name - LEN(Scan.nameOf(Chunk.chunks[c].name)) - 1; end;
249- end;
250- for c := 0 to Chunk.numChunks - 1 do
251- if isExt(c) then
252- putN(name, 4); putN(10H, 1); putN(0, 1); putN(0, 2); (* global, undefined *)
253- putN(0, 8); putN(0, 8);
254- name := name + LEN(Scan.nameOf(Chunk.chunks[c].name)) + 1;
255- end;
256- end;
257- k := 1;
258- for c := 0 to Chunk.numChunks - 1 do
259- if isExt(c) then
260- putN(Chunk.chunks[c].adr, 8);
261- putN((k shl 32) | 6, 8); (* R_X86_64_GLOB_DAT *)
262- putN(0, 8);
263- INC(k);
264- end;
265- end;
266- putN(1, 4); putN(nsym, 4); putN(nsym - 1, 4); (* the bucket chains every symbol *)
267- putN(0, 4);
268- for i := 1 to nsym - 1 do putN(i - 1, 4); end;
269- putN(0, 1);
270- for i := 0 to numNeeded - 1 do putStr(Scan.nameOf(needed[i])); end;
271- for c := 0 to Chunk.numChunks - 1 do
272- if isExt(c) then putStr(Scan.nameOf(Chunk.chunks[c].name)); end;
273- end;
274- len := Link.roOff + Link.roSize;
275-
276- (* the dynamic table, at the start of the writable segment *)
277- padTo(Link.bssOff);
278- at := 1;
279- for i := 0 to numNeeded - 1 do
280- putN(1, 8); putN(at, 8); (* DT_NEEDED *)
281- at := at + LEN(Scan.nameOf(needed[i])) + 1;
282- end;
283- putN(4, 8); putN(Link.extraAdr + hashAt, 8); (* DT_HASH *)
284- putN(5, 8); putN(Link.extraAdr + strAt, 8); (* DT_STRTAB *)
285- putN(6, 8); putN(Link.extraAdr + symAt, 8); (* DT_SYMTAB *)
286- putN(10, 8); putN(strLen, 8); (* DT_STRSZ *)
287- putN(11, 8); putN(24, 8); (* DT_SYMENT *)
288- putN(7, 8); putN(Link.extraAdr + relaAt, 8); (* DT_RELA *)
289- putN(8, 8); putN((nsym - 1) * 24, 8); (* DT_RELASZ *)
290- putN(9, 8); putN(24, 8); (* DT_RELAENT *)
291- putN(21, 8); putN(0, 8); (* DT_DEBUG, for gdb *)
292- putN(0, 16); (* DT_NULL *)
293-end;
294-
295-proc writeElf*(path: []U8; entry: INT);
296-var
297- nph, nsh, c, nsyms, sec, strsCap: INT;
298- roExtra, dynSize, symOff, strOff, shstrOff, shOff, strsLen: INT;
299- dbgOff, dbgSize: [3]INT;
300- strs: ^U8;
301- s: []U8;
302- dyn: BOOL;
303-begin
304- cap := 1 shl 16;
305- buf := Scan.grab(cap);
306- len := 0;
307- dyn := numNeeded > 0;
308- roExtra := 0; dynSize := 0;
309- if dyn then sizeTables(ADR(roExtra), ADR(dynSize)); end;
310- (* room for the most program headers either kind of program has *)
311- Link.linkAll(64 + 6 * 56, roExtra, dynSize);
312- if dyn then
313- nph := 6;
314- else
315- nph := 2;
316- if Link.roSize > 0 then INC(nph); end;
317- if Link.bssSize > 0 then INC(nph); end;
318- end;
319-
320- (* ELF header *)
321- putN(464C457FH, 4); (* #127 'ELF' *)
322- putN(2, 1); putN(1, 1); putN(1, 1); putN(0, 9); (* 64-bit, little-endian, version 1 *)
323- putN(2, 2); (* ET_EXEC *)
324- putN(62, 2); (* EM_X86_64 *)
325- putN(1, 4);
326- putN(Chunk.chunks[entry].adr, 8);
327- putN(64, 8); (* program headers follow *)
328- putN(0, 8); (* section headers: patched below *)
329- putN(0, 4);
330- nsh := 10;
331- if dyn then nsh := 13; end;
332- putN(64, 2); putN(56, 2); putN(nph, 2);
333- putN(64, 2); putN(nsh, 2); putN(6, 2); (* .shstrtab is section 6 *)
334-
335- (* flags: 4 read, 5 read and run, 6 read and write *)
336- if dyn then
337- phdr(PtInterp, 4, Link.extraAdr - Link.roAdr + Link.roOff, Link.extraAdr, LEN(Interp) + 1, LEN(Interp) + 1, 1);
338- end;
339- (* the first segment maps the headers too, so text can follow them *)
340- phdr(PtLoad, 5, 0, Link.Base, Link.textOff + Link.textSize, Link.textOff + Link.textSize, Link.Page);
341- if Link.roSize > 0 then phdr(PtLoad, 4, Link.roOff, Link.roAdr, Link.roSize, Link.roSize, Link.Page); end;
342- if dyn then
343- phdr(PtLoad, 6, Link.bssOff, Link.bssAdr, dynSize, Link.bssSize, Link.Page);
344- phdr(PtDynamic, 6, Link.bssOff, Link.bssAdr, dynSize, dynSize, 8);
345- elsif Link.bssSize > 0 then
346- phdr(PtLoad, 6, 0, Link.bssAdr, 0, Link.bssSize, Link.Page);
347- end;
348- phdr(PtGnuStack, 6, 0, 0, 0, 0, 16); (* a stack that can't run code *)
349-
350- padTo(Link.textOff);
351- putBytes(Link.textImg, Link.textSize);
352- padTo(Link.roOff); (* even when empty, so that every section lies in the file *)
353- putBytes(Link.roImg, Link.roSize);
354- if dyn then putTables; end;
355-
356- (* the symbol table: one local symbol for each named live chunk *)
357- padTo((len + 7) div 8 * 8);
358- symOff := len;
359- strsCap := 1 shl 16;
360- strs := Scan.grab(strsCap);
361- strsLen := 1;
362- strs[0] := 0;
363- putN(0, 24);
364- nsyms := 1;
365- for c := 0 to Chunk.numChunks - 1 do
366- if not stripped and Chunk.chunks[c].live and (Chunk.chunks[c].name >= 0) and not Chunk.chunks[c].ext then
367- s := Chunk.chunkName(c);
368- if strsLen + LEN(s) + 1 > strsCap then
369- strs := Scan.regrab(strs, strsLen, strsLen * 2 + 256);
370- strsCap := strsLen * 2 + 256;
371- end;
372- COPY(strs[strsLen..strsLen + LEN(s)], s);
373- strs[strsLen + LEN(s)] := 0;
374- if Chunk.chunks[c].sec = Chunk.secText then (* the section's index in the headers below *)
375- sec := 1;
376- elsif Chunk.chunks[c].sec = Chunk.secRodata then
377- sec := 2;
378- else
379- sec := 3;
380- end;
381- putN(strsLen, 4);
382- if sec = 1 then putN(2, 1); else putN(1, 1); end; (* STT_FUNC, STT_OBJECT *)
383- putN(0, 1);
384- putN(sec, 2);
385- putN(Chunk.chunks[c].adr, 8);
386- putN(Chunk.chunks[c].size, 8);
387- strsLen := strsLen + LEN(s) + 1;
388- INC(nsyms);
389- end;
390- end;
391- strOff := len;
392- putBytes(strs, strsLen);
393- shstrOff := len;
394- putBytes(ADR(ShNames[0]), LEN(ShNames));
395- if stripped or (Link.placesChunk < 0) then
396- for c := 0 to 2 do dbgOff[c] := len; dbgSize[c] := 0; end;
397- else
398- putDebug(dbgOff, dbgSize);
399- end;
400-
401- padTo((len + 7) div 8 * 8);
402- shOff := len;
403- patch(40, shOff, 8);
404- (* types: 1 PROGBITS, 2 SYMTAB, 3 STRTAB, 6 DYNAMIC, 8 NOBITS, 11 DYNSYM;
405- flags: 2 ALLOC, 3 WRITE+ALLOC, 6 ALLOC+EXECINSTR. A symbol table's
406- link is its string table's index: 5 .strtab, 8 .dynstr. The order
407- here is the index the code above relies on. *)
408- shdr("", 0, 0, 0, 0, 0, 0, 0, 0, 0);
409- shdr(".text", 1, 6, Link.Base + Link.textOff, Link.textOff, Link.textSize, 0, 0, 16, 0);
410- shdr(".rodata", 1, 2, Link.roAdr, Link.roOff, Link.roSize, 0, 0, 16, 0);
411- shdr(".bss", 8, 3, Link.bssAdr + dynSize, Link.roOff + Link.roSize, Link.bssSize - dynSize, 0, 0, 16, 0);
412- shdr(".symtab", 2, 0, 0, symOff, nsyms * 24, 5, nsyms, 8, 24);
413- shdr(".strtab", 3, 0, 0, strOff, strsLen, 0, 0, 1, 0);
414- shdr(".shstrtab", 3, 0, 0, shstrOff, LEN(ShNames), 0, 0, 1, 0);
415- if dyn then (* the loader's tables, for readelf and objdump *)
416- shdr(".dynamic", 6, 3, Link.bssAdr, Link.bssOff, dynSize, 8, 0, 8, 16);
417- shdr(".dynstr", 3, 2, Link.extraAdr + strAt, Link.extraAdr + strAt - Link.roAdr + Link.roOff, strLen, 0, 0, 1, 0);
418- shdr(".dynsym", 11, 2, Link.extraAdr + symAt, Link.extraAdr + symAt - Link.roAdr + Link.roOff, nsym * 24, 8, 1, 8, 24);
419- end;
420- shdr(".debug_line", 1, 0, 0, dbgOff[0], dbgSize[0], 0, 0, 1, 0);
421- shdr(".debug_info", 1, 0, 0, dbgOff[1], dbgSize[1], 0, 0, 1, 0);
422- shdr(".debug_abbrev", 1, 0, 0, dbgOff[2], dbgSize[2], 0, 0, 1, 0);
423-
424- if not Files.write(path, buf[0..len]) or (Sys.chmod(path, 1EDH) < 0) then
425- Diag.fatal(Diag.say("can't write {}", [Fmt.str(path)]));
426- end;
427-end;
428-
429-begin
430- mainPath := "";
431-end Elf.

self/Gen.raz deleted +0 -2350

@@ -1,2350 +0,0 @@
1-(* Gen: the code generator, for x86-64.
2-
3- Item and Parse drive a stack machine: they push constants, addresses
4- and the values of variables, operate on the values on top, store
5- them and jump on them. Every value has a kind: a word, which is an
6- integer as big as an address, a pointer, a BOOL, a set or a narrower
7- integer; a long, a 64-bit integer on a machine whose word is smaller
8- (never here); an F32; an F64. This unit makes the machine's code for
9- those calls, and nothing above it knows the machine: a port is a new
10- Gen, with an encoder of its own.
11-
12- The stack is kept in registers, as in Wirth's compilers (Niklaus
13- Wirth's Pascal and Oberon compilers): the value at depth d, depth 0
14- being the bottom, is in r8 to r11, register d mod 4, or in xmm8 to
15- xmm11 if it is a real. A value that needs a register a lower one
16- holds spills that one: stores it in a frame slot, to free the
17- register. A constant, or an address in the frame or of a chunk, is
18- only noted until something needs it in a register, so that it can be
19- an instruction's operand.
20-
21- A slice is two words, a pointer and then a length.
22-
23- Calls use the System V convention, which x86-64 Linux has for C:
24- arguments in rdi, rsi, rdx, rcx, r8, r9 and xmm0 to xmm7, the rest on
25- the machine's stack; rbx, rbp and r12 to r15 are callee-saved, which
26- is to say a called procedure gives them back as it found them. The
27- arguments are computed left to right onto the stack of values, and
28- moved into their registers just before the call: a call in a later
29- argument spills the earlier ones, as any call spills the values under
30- it, so that it can't disturb them. A slice goes as its two words, as
31- System V passes a 16-byte struct of two integers; a record, array or
32- variant passed by value goes as the address of a copy the caller
33- makes. A slice, or two results that are single values, come back in
34- rax and rdx (inTwoRegs); any other record, or several results, comes
35- back in memory the caller provides, through a hidden pointer
36- (behindPointer), where C would send a small struct back in registers.
37-
38- A procedure's frame holds its parameters, its variables, and the
39- temporaries of the statement running. The variables are zeroed on
40- entry.
41-
42- Depends on: Scan and Diag for errors, Sym for types, Chunk for code
43- and data, X64 for instructions.
44- Leaves out: what the program means, its types and their checks; that
45- is Item.
46-
47- The seed's `Mark` in the middle of a push or a check can't give an
48- error back, so it is shown and the call goes on without doing what
49- it could not (see newEntry and check): the compile ends with the
50- message, and the parser's recovery makes the stack right again with
51- resetStack. endProc returns its error, for the parser to pass up.
52-
53- What the parser sets, `inPlace`, has a setter, as the exported
54- variables can't be set from outside. The seed's types lose their T
55- (`TAdr` is `Adr`), and its `Call` record, which the procedure `call`
56- takes, is `CallInfo`. *)
57-module Gen;
58-import Fmt, Diag, Scan, Sym, Chunk, X := X64;
59-
60-const
61- NoLabel* = -1;
62- WordSize* = 8; (* the size of an address, and of INT *)
63- (* What the machine catches by itself, which the code needn't test for
64- (report section 10): on x86-64 Linux, a division by zero, a stack
65- overflow (at the guard page under the stack), a call to nil, and
66- a load or store within NilPage bytes of address 0, which is never
67- mapped. *)
68- NilPage* = 4096;
69-
70- RAX = X.RAX; RCX = X.RCX; RDX = X.RDX; RSP = X.RSP; RBP = X.RBP;
71- RSI = X.RSI; RDI = X.RDI; R8 = X.R8; R9 = X.R9; R10 = X.R10; R11 = X.R11;
72-
73-type
74- Kind* = (kWord, kLong, kF32, kF64);
75-
76- (* Where a variable is: its address is relative to the frame, to a
77- chunk, to an address on the stack, or to one held in a frame slot *)
78- Base* = (bFrame, bGlobal, bStack, bSlot, bReg);
79- Adr* = record
80- base*: Base;
81- chunk*: INT; (* bGlobal: the chunk; bSlot: the frame slot; bReg: the register *)
82- off*: I64; (* added to the address; for bReg, which word, 0 or 8 *)
83- hi*: INT; (* bReg, a slice: the register of its length, the
84- second word; chunk is that of its pointer *)
85- end;
86-
87- (* The code made so far, to go back to for a second try at a body *)
88- CodeMark* = record pc*, fixups*, lines*, said*, fails*: INT; end;
89-
90- (* For entryPoint: the address of chunk, put in the variable whose
91- chunk is into before the program starts *)
92- Link* = record chunk*, into*: INT; end;
93-
94- CallInfo* = record
95- sig*: ^Sym.Type;
96- param*: ^Sym.Obj; (* the parameter the next argument is for *)
97- obj*: ^Sym.Obj; (* the procedure called, if it has a name *)
98- n*: INT; (* the arguments *)
99- isF*: [64]BOOL; (* ... goes in an xmm register *)
100- pair*: [64]BOOL; (* ... is a slice's first word, the next its second *)
101- target*: I64; (* the frame slot of a procedure value, if chunk < 0 *)
102- chunk*: INT; (* else the procedure's chunk *)
103- ext*: BOOL; (* C's: called through the chunk holding its address *)
104- ret*: I64; (* set by call: the temporary a slice or a record result is in *)
105- end;
106-
107-const
108- (* the registers a procedure keeps its busiest variables in: System V's
109- callee-saved ones, so they live through calls (a register variable);
110- a procedure saves those it uses, and Rt finds them there for the
111- trap report *)
112- VarRegs*: [5]INT = [X.RBX, X.R12, X.R13, X.R14, X.R15];
113- (* the registers the trap report can show a variable in: VarRegs, then
114- rdi and rsi, where a procedure that calls nothing keeps the
115- parameters that arrive in them (keptIn) *)
116- ShownRegs*: [7]INT = [X.RBX, X.R12, X.R13, X.R14, X.R15, X.RDI, X.RSI];
117- (* the registers a procedure keeps its busiest reals in, xmm12 to
118- xmm15, numbered from XmmVar up so that they aren't taken for r12 to
119- r15 (regAt). Each has a slot too, written as it is, where the trap
120- report finds it, and from which it is loaded again after a call, as
121- System V has no callee-saved xmm register (xHome). *)
122- XmmVar* = 16;
123- XVarRegs*: [4]INT = [XmmVar + 12, XmmVar + 13, XmmVar + 14, XmmVar + 15];
124- (* a procedure's registers of variables, as bits: bit i is VarRegs[i],
125- bit XBit + i XVarRegs[i] *)
126- XBit* = 5;
127-
128-var
129- rtFail*, argcChunk*, argvChunk*: INT;
130- (* the stubs that check's code calls, one for each kind of failure,
131- made by entryPoint for those used *)
132- failStubs: [6]INT;
133- lost*: BOOL; (* a parameter kept where it arrived was wanted
134- for other work: the procedure is compiled again,
135- the parameter in memory *)
136- inPlace: INT; (* the register of a variable that the statement
137- being compiled assigns, x := x + e, where the
138- value can be worked out in the variable's own
139- register, from its first push on (lInto) *)
140- depth*: INT; (* the values on the stack *)
141- pushed*: INT; (* quadwords pushed on the machine's stack *)
142- codeChunk*: INT; (* the procedure or body being compiled, or -1 *)
143-
144-type
145- (* where a value on the stack is *)
146- Loc = (lConst, (* not loaded: val is the value *)
147- lHeld, (* not loaded: in register val, a register
148- variable's own (see VarRegs), read in place, which
149- nothing in an expression can change *)
150- lAdr, (* not loaded: the address of chunk, or of the frame
151- if chunk is -1, plus val *)
152- lIdx, (* not loaded: the address m, an element of an array
153- or of a slice in registers: the array's or the
154- pointer's register, or rbp, as the base, and the
155- index in a register variable's or the value's
156- own register (indexSlice, indexArray) *)
157- lMem, (* not loaded: the value of size bytes at m, in the
158- frame, a chunk, or at an address lAdr or lIdx
159- noted, read where it is used (pushVar) *)
160- lInto, (* in register val, a register variable's own, which
161- is what the value goes to (inPlace): so it is
162- changed in place *)
163- lReg, (* in its register *)
164- lFrame); (* spilled: in the frame slot val *)
165-
166- Entry = record
167- loc: Loc;
168- val: I64; (* lConst: the value; lHeld: the register; lAdr: the
169- offset; lFrame: the frame slot *)
170- chunk: INT; (* lAdr: the chunk, or -1 for the frame *)
171- m: X.Mem; (* lIdx, lMem *)
172- size: INT; (* lMem *)
173- signed: BOOL; (* lMem *)
174- k: Kind;
175- off: I64; (* lHeld, lReg: a word, its register plus off, the
176- constant of x + 1 not yet added (op), so that an
177- operand that uses it can take it as its
178- displacement: [r13 + r9 * 8 - 8] *)
179- end;
180-
181- (* a check of the procedure, whose failure endFails makes *)
182- Fail = record
183- L, what, ra, name, at: INT;
184- m: X.Mem;
185- n: I64;
186- end;
187-
188-const
189- StubNames: [6][]U8 = ["check0", "check1", "check2", "check3", "check4", "check5"];
190- (* the registers of the stack: the value at depth d is in Regs[d mod
191- NumRegs]. rax, rdx and rcx, which division and shifts need, and rsi
192- and rdi, which copying needs, aren't among them. *)
193- NumRegs = 4;
194- Regs: [NumRegs]INT = [R8, R9, R10, R11];
195- XRegs: [NumRegs]INT = [8, 9, 10, 11]; (* xmm8 to xmm11 *)
196- IntRegs: [6]INT = [RDI, RSI, RDX, RCX, R8, R9];
197-
198-var
199- stack: [256]Entry;
200- owner: [NumRegs]INT; (* the value in each register, or -1 *)
201- frameTop, frameMax, permTop: I64;
202- frameFix: INT; (* where the frame size is patched in *)
203- paramTop: I64; (* the parameters' slots end here *)
204- zeroTop: I64; (* the locals the prologue zeroes end here *)
205- retSlot: I64; (* holds the hidden result pointer *)
206- resType: ^Sym.Type; (* the procedure's result, or nil *)
207- exitL: INT;
208- (* parameters arriving in registers: where each is stored on entry *)
209- inReg: [14]INT;
210- inSlot: [14]I64;
211- inSize: [14]INT;
212- inObj: [14]^Sym.Obj;
213- numIn: INT;
214- procParams: ^Sym.Obj; (* the parameters, for enterBody *)
215- regMask: INT; (* the registers of variables, as bits (XBit) *)
216- kept: INT; (* bit r: register r holds a parameter, as it arrived *)
217- saveAt: I64; (* where they are saved, a quadword each *)
218- homes: [4]I64; (* the slots of the variables in XVarRegs *)
219- frameAt: [3]I64; (* frameTop, frameMax, permTop after the declarations *)
220- fails: [4096]Fail;
221- numFails: INT;
222-
223-proc setInPlace*(r: INT);
224-begin
225- inPlace := r;
226-end;
227-
228-proc kindOf*(t: ^Sym.Type): Kind;
229-begin
230- if t^.form = Sym.fReal then
231- if t^.size = 4 then return kF32; end;
232- return kF64;
233- end;
234- if t^.size > WordSize then return kLong; end;
235- return kWord;
236-end;
237-
238-(* The stack, as in Wirth's compilers: the value at depth d is held in
239- register d mod NumRegs. A value, when a higher one wants its register,
240- and every value in a register when a call would clobber them, is
241- spilled to a frame slot, and loaded again where it is used. A constant
242- is only noted.
243-
244- drop emits no code, and a dropped value's register still holds it
245- until the next push claims it: place (for bStack), operands,
246- indexSlice and jumpCmp read a register after dropping its value.
247-
248- Registers outside the stack, free within one operation: rax, rcx and
249- rdx for arithmetic; rsi and rdi for copying; and, where the stack holds
250- nothing in them, r10 for the prologue's zeroing loop and r11 for a call
251- through a procedure value; xmm0 and xmm1 for reals.
252-
253- A real, an F32 or an F64, is held in xmm8 to xmm11 (XRegs), where the
254- machine computes with reals, the value at depth d in XRegs[d mod
255- NumRegs]: so each depth has two registers, and holds its value in the
256- one of its kind, which owner doesn't tell apart. The xmm registers
257- from xmm8 up carry no arguments, so that call can move a real into
258- xmm0 to xmm7 without overwriting another still to go. *)
259-
260-proc fits32(v: I64): BOOL;
261-begin
262- return (v >= -2147483648) and (v <= 2147483647);
263-end;
264-
265-(* The register of kind k for the value at depth i *)
266-proc regIn(k: Kind; i: INT): INT;
267-begin
268- if k in {kF32, kF64} then return XRegs[i mod NumRegs]; end;
269- return Regs[i mod NumRegs];
270-end;
271-
272-proc regOf(i: INT): INT;
273-begin
274- return regIn(stack[i].k, i);
275-end;
276-
277-proc isReal(i: INT): BOOL;
278-begin
279- return stack[i].k in {kF32, kF64};
280-end;
281-
282-(* A real constant, its bits v, as an operand: 8 bytes in read-only
283- data, as the machine has no instruction that holds one *)
284-proc realConst(v: I64): X.Mem;
285-var c: INT;
286-begin
287- c := Chunk.newChunk(Chunk.secRodata, -1, -1);
288- Chunk.setData(c, ^U8(ADR(v)), 8, 8);
289- return X.memRip(c, 0);
290-end;
291-
292-(* The real i into xmm register x, from wherever it is, as valueTo does
293- for an integer register *)
294-proc xValueTo(i, x: INT);
295-begin
296- match stack[i].loc of
297- | lConst: X.movsXM(x, realConst(stack[i].val), stack[i].k = kF32);
298- | lMem: X.movsXM(x, stack[i].m, stack[i].size = 4);
299- | lHeld: if INT(stack[i].val) # x then X.movX(x, INT(stack[i].val)); end;
300- | lInto: if INT(stack[i].val) # x then X.movX(x, INT(stack[i].val)); end;
301- | lReg: if regOf(i) # x then X.movX(x, regOf(i)); end;
302- | else: X.movsXM(x, X.mem(RBP, stack[i].val), false); (* spilled, as 8 bytes *)
303- end;
304-end;
305-
306-proc loaded(i: INT): INT; forward;
307-proc allocTemp*(size, align: I64): I64; forward;
308-
309-(* The value i, in a register, goes to a frame slot; one noted that
310- holds its register, as an index, is worked out in it first *)
311-proc spill(i: INT);
312-var s: I64;
313-begin
314- if (stack[i].loc # lReg) or (stack[i].off # 0) then _ := loaded(i); end;
315- s := allocTemp(8, 8);
316- if isReal(i) then X.movsMX(X.mem(RBP, s), regOf(i), false);
317- else X.store(X.mem(RBP, s), regOf(i), 8); end;
318- stack[i].loc := lFrame;
319- stack[i].val := s;
320- owner[i mod NumRegs] := -1;
321-end;
322-
323-(* Each value below depth d read from memory now, as what comes next
324- may change it *)
325-proc readMems(d: INT);
326-var i: INT;
327-begin
328- for i := 0 to d - 1 do
329- if stack[i].loc = lMem then _ := loaded(i); end;
330- end;
331-end;
332-
333-(* Every value below depth d in a register, spilled; one noted in memory
334- is read first, as a call may change it *)
335-proc spillBelow(d: INT);
336-var r: INT;
337-begin
338- readMems(d);
339- for r := 0 to NumRegs - 1 do
340- if (owner[r] >= 0) and (owner[r] < d) then spill(owner[r]); end;
341- end;
342-end;
343-
344-(* The register of kind k of value i, for it to hold: a lower value at
345- its depth's registers is spilled. *)
346-proc claim(i: INT; k: Kind): INT;
347-var r: INT;
348-begin
349- r := i mod NumRegs;
350- if (owner[r] >= 0) and (owner[r] # i) then spill(owner[r]); end;
351- owner[r] := i;
352- return regIn(k, i);
353-end;
354-
355-(* The memory at the noted address i, plus off *)
356-proc adrMem(i: INT; off: I64): X.Mem;
357-begin
358- if stack[i].chunk < 0 then return X.mem(RBP, stack[i].val + off); end;
359- return X.memRip(stack[i].chunk, INT(stack[i].val + off));
360-end;
361-
362-(* The value i, in its register *)
363-proc loaded(i: INT): INT;
364-var r: INT;
365-begin
366- if stack[i].loc = lInto then return INT(stack[i].val); end;
367- if (stack[i].loc # lReg) and isReal(i) then
368- xValueTo(i, claim(i, stack[i].k));
369- stack[i].loc := lReg;
370- elsif stack[i].loc # lReg then
371- r := claim(i, kWord);
372- match stack[i].loc of
373- | lConst: X.movRI(r, stack[i].val);
374- | lHeld: X.movRR(r, INT(stack[i].val));
375- | lAdr: X.lea(r, adrMem(i, 0));
376- | lIdx: X.lea(r, stack[i].m);
377- | lMem: X.load(r, stack[i].m, stack[i].size, stack[i].signed);
378- | else: X.load(r, X.mem(RBP, stack[i].val), 8, false);
379- end;
380- stack[i].loc := lReg;
381- end;
382- if stack[i].off # 0 then
383- X.lea(regOf(i), X.mem(regOf(i), stack[i].off));
384- stack[i].off := 0;
385- end;
386- return regOf(i);
387-end;
388-
389-(* The register value i is in, only to be read: a variable's own, or
390- its register *)
391-proc peek(i: INT): INT;
392-begin
393- if (stack[i].loc = lHeld) and (stack[i].off = 0) then return INT(stack[i].val); end;
394- return loaded(i);
395-end;
396-
397-(* The offset of value i, taken from it, for the caller to add or to
398- make a displacement of *)
399-proc takeOff(i: INT): I64;
400-var o: I64;
401-begin
402- o := stack[i].off;
403- stack[i].off := 0;
404- return o;
405-end;
406-
407-(* The word on top, in a register, has o added: noted, if o can be a
408- displacement, else added now *)
409-proc putOff(o: I64);
410-begin
411- if fits32(stack[depth - 1].off + o) then
412- stack[depth - 1].off := stack[depth - 1].off + o;
413- else
414- X.movRI(RCX, o);
415- X.alu(X.aluAdd, loaded(depth - 1), RCX);
416- end;
417-end;
418-
419-proc top: INT;
420-begin
421- if depth = 0 then Diag.fatal("internal error: the stack is empty"); end;
422- return loaded(depth - 1);
423-end;
424-
425-(* A value on the stack's top. At the stack's last place it is shown as
426- an error and nothing is pushed: see the head of this unit. *)
427-proc newEntry(k: Kind; loc: Loc; v: I64);
428-begin
429- if depth > LEN(stack) - 1 then
430- _ := Scan.mark("the expression is too deep");
431- return;
432- end;
433- stack[depth].k := k;
434- stack[depth].loc := loc;
435- stack[depth].val := v;
436- stack[depth].chunk := -1;
437- stack[depth].off := 0;
438- INC(depth);
439-end;
440-
441-(* An address, lIdx, or a value at it, lMem, noted as the operand m. Its
442- index may be in the register of the value just dropped, at this
443- depth: it is the new value's own, then. *)
444-proc newMem(loc: Loc; m: X.Mem; k: Kind; size: INT; signed: BOOL);
445-begin
446- newEntry(k, loc, 0);
447- stack[depth - 1].m := m;
448- stack[depth - 1].size := size;
449- stack[depth - 1].signed := signed;
450- if m.index = Regs[(depth - 1) mod NumRegs] then owner[(depth - 1) mod NumRegs] := depth - 1; end;
451-end;
452-
453-(* The register a new value on top is to be computed in *)
454-proc target: INT;
455-begin
456- return claim(depth, kWord);
457-end;
458-
459-(* The xmm register a new real on top is to be computed in *)
460-proc xTarget: INT;
461-begin
462- return claim(depth, kF64);
463-end;
464-
465-(* The value just computed in target goes on top *)
466-proc computed(k: Kind);
467-begin
468- newEntry(k, lReg, 0);
469-end;
470-
471-proc drop*;
472-begin
473- DEC(depth);
474- if owner[depth mod NumRegs] = depth then owner[depth mod NumRegs] := -1; end;
475-end;
476-
477-(* rsi and rdi are about to be used for other work, as in copying: a
478- parameter kept in either must go to memory (lost). *)
479-proc clobberArgs;
480-begin
481- if kept # 0 then lost := true; end;
482-end;
483-
484-(* The value i into register r, from wherever it is: a constant or an
485- address is made there, a variable's register or the value's own
486- register copied, a spilled value loaded. Unlike loaded, it leaves the
487- value where it was, so r is its only new copy. *)
488-proc valueTo(i, r: INT);
489-begin
490- if isReal(i) and (stack[i].loc in {lHeld, lInto}) then
491- X.movqRX(r, INT(stack[i].val));
492- else
493- match stack[i].loc of
494- | lConst: X.movRI(r, stack[i].val);
495- | lHeld: X.movRR(r, INT(stack[i].val));
496- | lInto: X.movRR(r, INT(stack[i].val));
497- | lAdr: X.lea(r, adrMem(i, 0));
498- | lIdx: X.lea(r, stack[i].m);
499- | lMem: X.load(r, stack[i].m, stack[i].size, stack[i].signed);
500- | lReg:
501- if isReal(i) then X.movqRX(r, regOf(i));
502- elsif regOf(i) # r then X.movRR(r, regOf(i)); end;
503- | else: X.load(r, X.mem(RBP, stack[i].val), 8, false);
504- end;
505- end;
506- if stack[i].off # 0 then X.lea(r, X.mem(r, stack[i].off)); end;
507-end;
508-
509-(* The value on top, popped into register r *)
510-proc popTo(r: INT);
511-begin
512- valueTo(depth - 1, r);
513- drop();
514-end;
515-
516-(* Whether the value on top is a constant, and if so, which *)
517-proc topConst: (BOOL, I64);
518-begin
519- return stack[depth - 1].loc = lConst, stack[depth - 1].val;
520-end;
521-
522-proc resetStack*(d, p: INT);
523-var r: INT;
524-begin
525- depth := d;
526- pushed := p;
527- for r := 0 to NumRegs - 1 do owner[r] := -1; end;
528-end;
529-
530-proc pushConst*(k: Kind; v: I64);
531-begin
532- newEntry(k, lConst, v);
533-end;
534-
535-(* The register of the word at a, a variable in registers: the variable's
536- own, or for a slice its pointer's (off 0) or its length's (off 8) *)
537-proc regAt(a: Adr): INT;
538-var r: INT;
539-begin
540- if a.off = 0 then r := a.chunk; else r := a.hi; end;
541- if r >= XmmVar then r := r - XmmVar; end; (* an xmm register, XVarRegs *)
542- return r;
543-end;
544-
545-(* The memory a names. An address on the stack is popped, and is in its
546- register still; one in a slot is loaded into r. *)
547-proc place(a: Adr; r: INT): X.Mem;
548-var m: X.Mem; ra: INT; o: I64;
549-begin
550- if a.base = bReg then Diag.fatal("internal error: a register has no address"); end;
551- match a.base of
552- | bFrame: return X.mem(RBP, a.off);
553- | bGlobal: return X.memRip(a.chunk, INT(a.off));
554- | bStack:
555- if stack[depth - 1].loc = lAdr then
556- m := adrMem(depth - 1, a.off);
557- drop();
558- return m;
559- elsif stack[depth - 1].loc = lIdx then
560- m := stack[depth - 1].m;
561- m.disp := m.disp + INT(a.off);
562- drop();
563- return m;
564- end;
565- (* an offset noted on the address is the operand's, as
566- p^.f + 8: [r8 + 8] *)
567- if fits32(a.off + stack[depth - 1].off) then o := takeOff(depth - 1); else o := 0; end;
568- ra := peek(depth - 1);
569- drop();
570- return X.mem(ra, a.off + o);
571- | else: (* bSlot: the address is in the frame slot a.chunk *)
572- X.load(r, X.mem(RBP, a.chunk), 8, false);
573- return X.mem(r, a.off);
574- end;
575-end;
576-
577-(* The address a names, on top of the stack *)
578-proc pushAdr*(a: Adr);
579-var m: X.Mem; r: INT;
580-begin
581- if (a.base = bStack) and (a.off = 0) then return; end; (* it is on top already *)
582- if a.base in {bFrame, bGlobal} then
583- newEntry(kWord, lAdr, a.off);
584- if a.base = bGlobal then stack[depth - 1].chunk := a.chunk; end;
585- return;
586- end;
587- (* The order matters. With the address on the stack, place pops it and
588- must come first, so that target may reuse its register; otherwise
589- target comes first, since place may need r to load a slot's pointer. *)
590- if a.base = bStack then
591- m := place(a, -1); r := target();
592- else
593- r := target(); m := place(a, r);
594- end;
595- X.lea(r, m);
596- computed(kWord);
597-end;
598-
599-proc pushVar*(a: Adr; size: INT; signed: BOOL; k: Kind);
600-var m: X.Mem; r: INT;
601-begin
602- r := inPlace;
603- inPlace := -1;
604- if r >= XmmVar then r := r - XmmVar; end;
605- if (a.base = bReg) and (regAt(a) = r) then
606- newEntry(k, lInto, r);
607- return;
608- end;
609- if a.base = bReg then
610- newEntry(k, lHeld, regAt(a));
611- return;
612- end;
613- (* a variable in the frame or a chunk, or at an address only noted, is
614- 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
616- m := place(a, -1);
617- newMem(lMem, m, k, size, signed);
618- return;
619- end;
620- (* in the order pushAdr explains *)
621- if a.base = bStack then
622- m := place(a, -1); r := target();
623- else
624- r := target(); m := place(a, r);
625- end;
626- if k in {kF32, kF64} then X.movsXM(xTarget(), m, size = 4);
627- else X.load(r, m, size, signed); end;
628- computed(k);
629-end;
630-
631-proc pushProc*(c: INT; ext: BOOL);
632-var r: INT;
633-begin
634- r := target();
635- if ext then X.load(r, X.memRip(c, 0), 8, false);
636- else X.lea(r, X.memRip(c, 0)); end;
637- computed(kWord);
638-end;
639-
640-(* The slot of the variable in xmm register x *)
641-proc homeOf(x: INT): X.Mem;
642-begin
643- return X.mem(RBP, homes[x + XmmVar - XVarRegs[0]]);
644-end;
645-
646-(* Pops a value into the variable at a; an address on the stack is under
647- the value. *)
648-proc popVar*(a: Adr; size: INT);
649-var r: INT; v: I64; c, fl: BOOL;
650-begin
651- if (a.base = bReg) and isReal(depth - 1) then
652- xValueTo(depth - 1, regAt(a));
653- drop();
654- X.movsMX(homeOf(regAt(a)), regAt(a), false); (* written through, as xHome says *)
655- return;
656- end;
657- if a.base = bReg then
658- c, v := topConst();
659- if c then X.movRI(regAt(a), v);
660- elsif peek(depth - 1) # regAt(a) then X.movRR(regAt(a), peek(depth - 1)); end; (* else it is there, lInto *)
661- drop();
662- return;
663- end;
664- c, v := topConst();
665- if c and fits32(v) then
666- drop();
667- X.storeI(place(a, RCX), INT(v), size);
668- return;
669- end;
670- if c then r := RAX; X.movRI(RAX, v);
671- else r := peek(depth - 1); end;
672- fl := (stack[depth - 1].loc # lConst) and isReal(depth - 1);
673- drop();
674- if fl then X.movsMX(place(a, RCX), r, size = 4);
675- else X.store(place(a, RCX), r, size); end;
676-end;
677-
678-(* Register src to dst, an xmm register's if fl *)
679-proc movReg(fl: BOOL; dst, src: INT);
680-begin
681- if fl then X.movX(dst, src); else X.movRR(dst, src); end;
682-end;
683-
684-(* The two values on top, of one kind, change places. *)
685-proc swap*;
686-var e: Entry; x, y, t: INT; rx, ry, fl: BOOL;
687-begin
688- x := depth - 2; y := depth - 1;
689- (* a value noted at an address that uses its register is worked out,
690- so that its register moves with it *)
691- if stack[x].loc in {lIdx, lMem} then _ := loaded(x); end;
692- if stack[y].loc in {lIdx, lMem} then _ := loaded(y); end;
693- rx := stack[x].loc = lReg;
694- ry := stack[y].loc = lReg;
695- fl := isReal(y);
696- if fl then t := 0; else t := RAX; end; (* xmm0, or rax *)
697- if rx and ry then
698- movReg(fl, t, regOf(x));
699- movReg(fl, regOf(x), regOf(y));
700- movReg(fl, regOf(y), t);
701- elsif rx then
702- owner[x mod NumRegs] := -1;
703- movReg(fl, claim(y, stack[y].k), regOf(x));
704- elsif ry then
705- owner[y mod NumRegs] := -1;
706- movReg(fl, claim(x, stack[x].k), regOf(y));
707- end;
708- e := stack[x]; stack[x] := stack[y]; stack[y] := e;
709-end;
710-
711-(* Copying *)
712-
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. *)
717-proc copyBytes(size: I64);
718-var o, n: I64;
719-begin
720- if size > 64 then
721- X.movRI(RCX, size);
722- X.repMovsb();
723- return;
724- end;
725- o := 0;
726- while o < size do
727- n := 8;
728- while n > size - o do n := n div 2; end;
729- X.load(RCX, X.mem(RSI, o), INT(n), false);
730- X.store(X.mem(RDI, o), RCX, INT(n));
731- INC(o, n);
732- end;
733-end;
734-
735-(* Pops a source's address, and a destination's under it, and copies
736- size bytes to off bytes past the destination. *)
737-proc copyBlock*(size, off: I64);
738-begin
739- clobberArgs();
740- popTo(RSI);
741- popTo(RDI);
742- if off # 0 then X.lea(RDI, X.mem(RDI, off)); end;
743- copyBytes(size);
744-end;
745-
746-(* Pops a source's address, and copies size bytes to a: for a slice in
747- registers, its two words into them. *)
748-proc copyTo*(a: Adr; size: I64);
749-begin
750- clobberArgs();
751- popTo(RSI);
752- if a.base = bReg then
753- X.load(a.chunk, X.mem(RSI, 0), 8, false);
754- X.load(a.hi, X.mem(RSI, 8), 8, false);
755- return;
756- end;
757- X.lea(RDI, place(a, RDI));
758- copyBytes(size);
759-end;
760-
761-proc zeroVar*(a: Adr; size: I64);
762-begin
763- clobberArgs();
764- X.lea(RDI, place(a, RDI));
765- X.movRI(RCX, size);
766- X.movRI(RAX, 0);
767- X.repStosb();
768-end;
769-
770-(* Operations *)
771-
772-(* n if v is 2^n, which is 0 for 1; -1 if v isn't a power of two *)
773-proc exactLog2(v: I64): INT;
774-var n: INT;
775-begin
776- n := 0;
777- while (v > 1) and ((v & 1) = 0) do v := v shr 1; INC(n); end;
778- if v # 1 then n := -1; end;
779- return n;
780-end;
781-
782-(* r times v, a size: by a shift where v is a power of two, as it
783- mostly is, since a shift takes one cycle and imul three *)
784-proc mulI(r: INT; v: I64);
785-begin
786- if exactLog2(v) > 0 then X.shiftI(X.shShl, r, exactLog2(v));
787- elsif v # 1 then X.imulI(r, INT(v)); end;
788-end;
789-
790-(* r compared with v, through rdx if v needs more than 32 bits; with
791- zero by test, which sets the flags as cmp would and is shorter *)
792-proc cmpI(r: INT; v: I64);
793-begin
794- if v = 0 then X.testRR(r, r);
795- elsif fits32(v) then X.aluI(X.aluCmp, r, INT(v));
796- else X.movRI(RDX, v); X.alu(X.aluCmp, r, RDX); end;
797-end;
798-
799-(* r div or mod 2^k, 1 <= k <= 62, with shifts: div truncates towards
800- zero, so a negative dividend first gets 2^k - 1 added (the bias). *)
801-proc divPow2(sy: Scan.Sym; r, k: INT; unsign: BOOL);
802-begin
803- (* unsigned: div shifts right; mod keeps the low k bits, by shifting
804- them up to the top and back down *)
805- if unsign then
806- if sy = Scan.sDiv then X.shiftI(X.shShr, r, k);
807- else X.shiftI(X.shShl, r, 64 - k); X.shiftI(X.shShr, r, 64 - k); end;
808- return;
809- end;
810- (* signed: sar 63 makes the sign into all ones or all zeros, and shr
811- 64 - k keeps k of them, the bias 2^k - 1 or 0; with it added, sar k
812- rounds towards zero. The remainder is r less the quotient times 2^k. *)
813- X.movRR(RCX, r);
814- X.shiftI(X.shSar, RCX, 63);
815- X.shiftI(X.shShr, RCX, 64 - k);
816- X.alu(X.aluAdd, RCX, r);
817- X.shiftI(X.shSar, RCX, k);
818- if sy = Scan.sDiv then X.movRR(r, RCX);
819- else X.shiftI(X.shShl, RCX, k); X.alu(X.aluSub, r, RCX); end;
820-end;
821-
822-(* Before rax div y, of a signed type of bits < 64: its smallest value
823- divided by -1 overflows it, which must stop the program as it does for
824- an I64 (report section 6.1). idiv on the 64-bit values wouldn't fault,
825- so then rax is made the smallest I64, and it does. *)
826-proc divTrap(bits, y: INT);
827-var L: INT;
828-begin
829- L := NoLabel;
830- cmpI(y, -1);
831- X.jcc(X.ccNE, L);
832- cmpI(RAX, I64(-1) shl (bits - 1));
833- X.jcc(X.ccNE, L);
834- X.shiftI(X.shShl, RAX, 64 - bits);
835- X.fixLink(L);
836-end;
837-
838-(* Whether the value on top is a word in memory that can be the right
839- operand of an instruction as it is: add r, [m] *)
840-proc topInMem: BOOL;
841-begin
842- return (stack[depth - 1].loc = lMem) and (stack[depth - 1].size = 8);
843-end;
844-
845-(* The right operand of the two values on top, popped, in register y:
846- its own, or rcx for a constant; the left one stays, in its register,
847- which is returned with y. *)
848-proc operands: (INT, INT);
849-var v: I64; c: BOOL; y: INT;
850-begin
851- c, v := topConst();
852- if c then X.movRI(RCX, v); y := RCX; else y := peek(depth - 1); end;
853- drop();
854- return top(), y;
855-end;
856-
857-(* The two reals on top, the left op the right, worked out in the left's
858- xmm register. The right is taken from memory where it is, as a
859- constant, a variable or a spilled value is: mulsd xmm8, [rbp - 16]. *)
860-proc realOp(sy: Scan.Sym; k: Kind);
861-var f: BOOL; c, x, y: INT; m: X.Mem;
862-begin
863- f := k = kF32;
864- match sy of
865- | sPlus: c := 58H; (* addsd, or addss for an F32 *)
866- | sMinus: c := 5CH; (* subsd, subss *)
867- | sTimes: c := 59H; (* mulsd, mulss *)
868- | else: c := 5EH; (* divsd, divss *)
869- end;
870- if stack[depth - 1].loc in {lConst, lMem, lFrame} then
871- match stack[depth - 1].loc of
872- | lConst: m := realConst(stack[depth - 1].val);
873- | lMem: m := stack[depth - 1].m;
874- | else: m := X.mem(RBP, stack[depth - 1].val);
875- end;
876- drop();
877- X.sseM(c, top(), m, f);
878- else
879- y := peek(depth - 1);
880- drop();
881- x := top();
882- X.sse(c, x, y, f);
883- end;
884-end;
885-
886-(* The group 1 operation of +, -, &, | and xor *)
887-proc aluOf(sy: Scan.Sym): INT;
888-begin
889- match sy of
890- | sPlus: return X.aluAdd;
891- | sMinus: return X.aluSub;
892- | sAmp: return X.aluAnd;
893- | sBar: return X.aluOr;
894- | else: return X.aluXor;
895- end;
896-end;
897-
898-const
899- (* the condition codes of the comparisons, from sEql: = # < <= > >= *)
900- CcSigned: [6]INT = [X.ccE, X.ccNE, X.ccL, X.ccLE, X.ccG, X.ccGE];
901- CcUnsigned: [6]INT = [X.ccE, X.ccNE, X.ccB, X.ccBE, X.ccA, X.ccAE];
902-
903-(* The two values on top, the left op the right, an integer of size
904- bytes, signed or not, brought back to its width. *)
905-proc op*(sy: Scan.Sym; k: Kind; size: INT; signed: BOOL);
906-var v, o: I64; r, y, sh, bits: INT; c: BOOL; m: X.Mem;
907-begin
908- if k in {kF32, kF64} then realOp(sy, k); return; end;
909- bits := size * 8;
910- (* a constant on the left of an operation whose order doesn't matter
911- goes right, where it can be an immediate or a shift *)
912- if (((sy = Scan.sPlus) or (sy = Scan.sTimes) or (sy = Scan.sAmp) or (sy = Scan.sBar) or (sy = Scan.sXor))) and (stack[depth - 2].loc = lConst)
913- and (stack[depth - 1].loc # lConst) then swap(); end;
914- c, v := topConst();
915- (* A word's offset (see Entry) is carried through + and -, and
916- through * by a constant, as (x + a) * k is x * k + a * k: the
917- operation is done on the registers, the offsets worked out here,
918- and put on the result. x + 1 is only noted. A value changed in
919- place, lInto, has no offset. *)
920- o := 0;
921- if (bits = 64) and (stack[depth - 2].loc # lInto)
922- and ((((sy = Scan.sPlus) or (sy = Scan.sMinus))) or ((sy = Scan.sTimes) and c and fits32(v))) then
923- o := takeOff(depth - 2);
924- if sy = Scan.sTimes then o := o * v;
925- elsif c and fits32(v) then
926- if sy = Scan.sPlus then o := o + v; else o := o - v; end;
927- drop();
928- if not (stack[depth - 1].loc in {lReg, lHeld}) then _ := top(); end;
929- putOff(o);
930- return;
931- elsif sy = Scan.sPlus then o := o + takeOff(depth - 1);
932- else o := o - takeOff(depth - 1); end;
933- end;
934- sh := -1;
935- if c and (((sy = Scan.sTimes) or (sy = Scan.sDiv) or (sy = Scan.sMod))) then sh := exactLog2(v); end;
936- if c and (sh >= 1) then
937- drop();
938- r := top();
939- if sy = Scan.sTimes then X.shiftI(X.shShl, r, sh); else divPow2(sy, r, sh, not signed); end;
940- elsif c and fits32(v) and (((sy = Scan.sPlus) or (sy = Scan.sMinus) or (sy = Scan.sBar) or (sy = Scan.sXor) or (sy = Scan.sAmp) or (sy = Scan.sTimes) or (sy = Scan.sShl) or (sy = Scan.sShr))) then
941- drop();
942- r := top();
943- match sy of
944- | sTimes: X.imulI(r, INT(v));
945- | sShl: X.shiftI(X.shShl, r, INT(v & I64(bits - 1)));
946- | sShr:
947- if signed then X.shiftI(X.shSar, r, INT(v & I64(bits - 1)));
948- else X.shiftI(X.shShr, r, INT(v & I64(bits - 1))); end;
949- | else: X.aluI(aluOf(sy), r, INT(v));
950- end;
951- elsif topInMem() and (((sy = Scan.sPlus) or (sy = Scan.sMinus) or (sy = Scan.sAmp) or (sy = Scan.sBar) or (sy = Scan.sXor))) then
952- m := stack[depth - 1].m;
953- drop();
954- r := top();
955- X.aluM(aluOf(sy), r, m);
956- else
957- r, y := operands();
958- if ((sy = Scan.sPlus) or (sy = Scan.sMinus) or (sy = Scan.sAmp) or (sy = Scan.sBar) or (sy = Scan.sXor)) then
959- X.alu(aluOf(sy), r, y);
960- elsif sy = Scan.sTimes then
961- X.imul(r, y);
962- elsif ((sy = Scan.sDiv) or (sy = Scan.sMod)) then
963- X.movRR(RAX, r);
964- if not signed then
965- X.movRI(RDX, 0); X.unary(6, y); (* div *)
966- else
967- (* only -1 can make the division overflow, so a constant
968- divisor other than -1 needs no check *)
969- if (bits < 64) and (not c or (v = -1)) then divTrap(bits, y); end;
970- X.cqo(); X.unary(7, y); (* idiv, of rdx:rax, which cqo made from rax *)
971- end;
972- if sy = Scan.sDiv then X.movRR(r, RAX); else X.movRR(r, RDX); end;
973- else (* sShl, sShr *)
974- (* the count modulo the width: the machine takes it modulo 64 *)
975- if y # RCX then X.movRR(RCX, y); end;
976- if bits < 64 then X.aluI(X.aluAnd, RCX, bits - 1); end;
977- if sy = Scan.sShl then X.shift(X.shShl, r);
978- elsif signed then X.shift(X.shSar, r);
979- else X.shift(X.shShr, r); end;
980- end;
981- end;
982- if bits < 64 then X.extend(r, size, signed); end;
983- stack[depth - 1].k := k;
984- if o # 0 then putOff(o); end;
985-end;
986-
987-(* The left op the right of the two values on top, as a BOOL *)
988-proc compare*(sy: Scan.Sym; k: Kind; signed: BOOL);
989-var f: BOOL; r, x, y, i: INT; v: I64; c: BOOL; m: X.Mem;
990-begin
991- i := INT(sy) - INT(Scan.sEql);
992- if k in {kF32, kF64} then
993- f := k = kF32;
994- y := peek(depth - 1);
995- drop();
996- x := peek(depth - 1);
997- drop();
998- r := target(); (* the BOOL, in the left's integer register *)
999- (* ucomis sets the flags as an unsigned comparison would, but for an
1000- unordered pair (a NaN) it sets zero, parity and carry all. So only
1001- "above" can be tested straight: it is false for NaN, as every
1002- comparison but # must be. a < b is made b > a. = also asks for
1003- no parity, as NaN = NaN sets the zero flag, and # asks for
1004- parity as well. *)
1005- match sy of
1006- | sEql: X.ucomis(x, y, f); X.setCC(X.ccE, r); X.setCC(X.ccNP, RCX); X.alu(X.aluAnd, r, RCX);
1007- | sNeq: X.ucomis(x, y, f); X.setCC(X.ccNE, r); X.setCC(X.ccP, RCX); X.alu(X.aluOr, r, RCX);
1008- | sLss: X.ucomis(y, x, f); X.setCC(X.ccA, r);
1009- | sLeq: X.ucomis(y, x, f); X.setCC(X.ccAE, r);
1010- | sGtr: X.ucomis(x, y, f); X.setCC(X.ccA, r);
1011- | else: X.ucomis(x, y, f); X.setCC(X.ccAE, r);
1012- end;
1013- computed(kWord);
1014- else
1015- c, v := topConst();
1016- if c then
1017- drop(); r := top(); cmpI(r, v);
1018- elsif topInMem() then
1019- m := stack[depth - 1].m; drop(); r := top(); X.aluM(X.aluCmp, r, m);
1020- else
1021- r, y := operands(); X.alu(X.aluCmp, r, y);
1022- end;
1023- if signed then X.setCC(CcSigned[i], r); else X.setCC(CcUnsigned[i], r); end;
1024- end;
1025- stack[depth - 1].k := kWord;
1026-end;
1027-
1028-(* A real is negated by flipping its sign bit, in rax *)
1029-proc neg*(k: Kind; size: INT; signed: BOOL);
1030-var r: INT;
1031-begin
1032- r := top();
1033- if k in {kF32, kF64} then
1034- X.movqRX(RAX, r);
1035- if k = kF32 then X.btc(RAX, 31); else X.btc(RAX, 63); end;
1036- X.movqXR(r, RAX);
1037- else
1038- X.unary(3, r); (* neg *)
1039- if size < 8 then X.extend(r, size, signed); end;
1040- end;
1041-end;
1042-
1043-proc complement*(size: INT; signed: BOOL);
1044-var r: INT;
1045-begin
1046- r := top();
1047- X.unary(2, r); (* not *)
1048- if size < 8 then X.extend(r, size, signed); end;
1049-end;
1050-
1051-proc notBool*;
1052-begin
1053- X.aluI(X.aluXor, top(), 1);
1054-end;
1055-
1056-(* The integer on top, brought to size bytes *)
1057-proc narrow*(size: INT; signed: BOOL);
1058-var r: INT;
1059-begin
1060- r := top();
1061- if size < 8 then X.extend(r, size, signed); end;
1062- stack[depth - 1].k := kWord;
1063-end;
1064-
1065-(* The integer on top, as a real of kind k; big if it may be a U64 above
1066- high(I64), which the machine would take as negative *)
1067-proc intToReal*(k: Kind; big: BOOL);
1068-var L1, L2, r, x: INT; f: BOOL;
1069-begin
1070- f := k = kF32;
1071- r := top();
1072- x := regIn(k, depth - 1); (* its xmm register *)
1073- if big then
1074- (* above high(I64): halve, keeping the low bit, and double *)
1075- L1 := NoLabel; L2 := NoLabel;
1076- X.testRR(r, r);
1077- X.jcc(X.ccS, L1);
1078- X.cvtsi2s(x, r, f);
1079- X.jmp(L2);
1080- X.fixLink(L1);
1081- X.movRR(RCX, r);
1082- X.shiftI(X.shShr, RCX, 1);
1083- X.aluI(X.aluAnd, r, 1);
1084- X.alu(X.aluOr, RCX, r);
1085- X.cvtsi2s(x, RCX, f);
1086- X.sse(58H, x, x, f); (* adds it to itself: doubles *)
1087- X.fixLink(L2);
1088- else
1089- X.cvtsi2s(x, r, f);
1090- end;
1091- stack[depth - 1].k := k;
1092-end;
1093-
1094-(* The real of kind k on top, truncated to an integer *)
1095-proc realToInt*(k: Kind);
1096-var x: INT;
1097-begin
1098- x := top();
1099- X.cvtts2si(regIn(kWord, depth - 1), x, k = kF32);
1100- stack[depth - 1].k := kWord;
1101-end;
1102-
1103-(* The real of kind k on top, as the other kind *)
1104-proc realToReal*(k: Kind);
1105-var x: INT;
1106-begin
1107- x := top();
1108- X.sse(5AH, x, x, k = kF32); (* cvtss2sd, or cvtsd2ss *)
1109- if k = kF32 then stack[depth - 1].k := kF64; else stack[depth - 1].k := kF32; end;
1110-end;
1111-
1112-(* Whether the slices in the frame at a and b (the offsets of their
1113- pointers, the lengths 8 bytes on) are equal (or not, if not eq): the
1114- lengths, then the bytes, len shl shift of them, compared where the
1115- comparison stands. *)
1116-proc compareSeq*(a, b: I64; shift: INT; eq: BOOL);
1117-var differ, r: INT;
1118-begin
1119- clobberArgs();
1120- r := target();
1121- X.load(RCX, X.mem(RBP, b + 8), 8, false);
1122- X.aluM(X.aluCmp, RCX, X.mem(RBP, a + 8));
1123- differ := NoLabel;
1124- X.jcc(X.ccNE, differ);
1125- X.load(RSI, X.mem(RBP, b), 8, false);
1126- X.load(RDI, X.mem(RBP, a), 8, false);
1127- if shift > 0 then X.shiftI(X.shShl, RCX, shift); end;
1128- (* repe cmpsb with rcx = 0 leaves the flags alone, so make them say
1129- equal first, which is right if there are no bytes *)
1130- X.alu(X.aluCmp, RCX, RCX);
1131- X.repeCmpsb();
1132- X.fixLink(differ);
1133- if eq then X.setCC(X.ccE, r); else X.setCC(X.ccNE, r); end;
1134- computed(kWord);
1135-end;
1136-
1137-(* An error points at its message's length, an 8-byte word, with the
1138- text after it; nil is no error. Pops one, and makes the slice of its
1139- message at tmp, empty for nil. *)
1140-proc errorText*(tmp: I64);
1141-var L: INT;
1142-begin
1143- popTo(RAX);
1144- X.movRI(RCX, 0);
1145- L := NoLabel;
1146- X.testRR(RAX, RAX);
1147- X.jcc(X.ccE, L);
1148- X.load(RCX, X.mem(RAX, 0), 8, false);
1149- X.lea(RAX, X.mem(RAX, 8));
1150- X.fixLink(L);
1151- X.store(X.mem(RBP, tmp), RAX, 8);
1152- X.store(X.mem(RBP, tmp + 8), RCX, 8);
1153-end;
1154-
1155-(* Pops a step and an integer variable's address, and adds the step to
1156- it, or takes it away. *)
1157-proc incDec*(size: INT; signed, dec: BOOL);
1158-var r, y, o: INT; v: I64; a: Adr; c: BOOL;
1159-begin
1160- c, v := topConst();
1161- if dec then o := X.aluSub; else o := X.aluAdd; end;
1162- if c and fits32(v) then
1163- drop();
1164- a.base := bStack; a.off := 0;
1165- X.aluMI(o, place(a, RCX), INT(v), size);
1166- return;
1167- end;
1168- r, y := operands();
1169- drop();
1170- X.load(RAX, X.mem(r, 0), size, signed);
1171- X.alu(o, RAX, y);
1172- X.store(X.mem(r, 0), RAX, size);
1173-end;
1174-
1175-(* INC or DEC of the variable in register r, by the value on top; a
1176- narrow one wraps at its width *)
1177-proc incDecReg*(r, size: INT; signed, dec: BOOL);
1178-var y, o: INT; v: I64; c: BOOL;
1179-begin
1180- if dec then o := X.aluSub; else o := X.aluAdd; end;
1181- c, v := topConst();
1182- if c and fits32(v) then X.aluI(o, r, INT(v));
1183- else y := top(); X.alu(o, r, y); end;
1184- drop();
1185- if size < 8 then X.extend(r, size, signed); end;
1186-end;
1187-
1188-(* The pointer on top, which NEW got, to size zero bytes unless nil *)
1189-proc zeroNew*(size: I64);
1190-var L, r: INT;
1191-begin
1192- clobberArgs();
1193- r := top();
1194- L := NoLabel;
1195- X.testRR(r, r);
1196- X.jcc(X.ccE, L);
1197- X.movRR(RDI, r);
1198- X.movRI(RCX, size);
1199- X.movRI(RAX, 0);
1200- X.repStosb();
1201- X.fixLink(L);
1202-end;
1203-
1204-(* CAS(p, old, new), XCHG(p, v) or XADD(p, v), from the stack: the
1205- result where p was *)
1206-proc atomic*(which: INT);
1207-var r, n: INT;
1208-begin
1209- if which = Sym.bCas then readMems(depth - 3); else readMems(depth - 2); end; (* what it writes may be one *)
1210- if which = Sym.bCas then n := top(); drop(); end;
1211- popTo(RAX); (* cmpxchg compares with rax, so CAS's old value goes there *)
1212- r := top();
1213- match which of
1214- | Sym.bCas: X.lockCmpxchg(X.mem(r, 0), n); X.setCC(X.ccE, r);
1215- | Sym.bXchg: X.xchg(X.mem(r, 0), RAX); X.movRR(r, RAX);
1216- | else: X.lockXadd(X.mem(r, 0), RAX); X.movRR(r, RAX);
1217- end;
1218- stack[depth - 1].k := kWord;
1219-end;
1220-
1221-(* The system call and its arguments, n values on the stack. Linux takes
1222- the number in rax and the arguments in rdi, rsi, rdx, r10, r8 and r9,
1223- and the syscall instruction clobbers rcx and r11. Every value in a
1224- register is spilled first, as r8 to r11 are the stack's registers,
1225- and the arguments are loaded from their slots. *)
1226-proc sysCall*(n: INT);
1227-const SysRegs: [7]INT = [RAX, RDI, RSI, RDX, R10, R8, R9];
1228-var i: INT;
1229-begin
1230- clobberArgs();
1231- spillBelow(depth);
1232- for i := 0 to n - 1 do valueTo(depth - n + i, SysRegs[i]); end;
1233- for i := 1 to n do drop(); end;
1234- X.syscall();
1235- X.movRR(target(), RAX);
1236- computed(kWord);
1237-end;
1238-
1239-proc fence*;
1240-begin
1241- X.mfence();
1242-end;
1243-
1244-(* Jumps. A label is the chain of the jumps to it, until it is placed. *)
1245-
1246-proc jump*(var L: INT);
1247-begin
1248- X.jmp(L);
1249-end;
1250-
1251-(* Pops a BOOL, and jumps if it is when *)
1252-proc jumpIf*(var L: INT; when: BOOL);
1253-var r: INT;
1254-begin
1255- r := peek(depth - 1);
1256- drop();
1257- X.testRR(r, r);
1258- if when then X.jcc(X.ccNE, L); else X.jcc(X.ccE, L); end;
1259-end;
1260-
1261-(* Pops two integers, and jumps if the left op the right *)
1262-proc jumpCmp*(sy: Scan.Sym; signed: BOOL; var L: INT);
1263-var r, y, i: INT; v: I64; c: BOOL; m: X.Mem;
1264-begin
1265- i := INT(sy) - INT(Scan.sEql);
1266- (* a comparison changes neither: a variable's register will do *)
1267- c, v := topConst();
1268- if c then
1269- drop(); r := peek(depth - 1); cmpI(r, v);
1270- elsif topInMem() then
1271- m := stack[depth - 1].m; drop(); r := peek(depth - 1); X.aluM(X.aluCmp, r, m);
1272- else
1273- y := peek(depth - 1); drop(); r := peek(depth - 1); X.alu(X.aluCmp, r, y);
1274- end;
1275- drop();
1276- if signed then X.jcc(CcSigned[i], L); else X.jcc(CcUnsigned[i], L); end;
1277-end;
1278-
1279-(* jumpCmp out of an expression, past code that may spill: the values
1280- under the two compared are spilled first, so that they are where the
1281- code after the landing place expects them, whichever way it came. In
1282- v + (a < b and f(x) = 0), a call to f spills v on the way through, so
1283- v must be in its slot too where a < b jumps past the call. *)
1284-proc jumpOut*(sy: Scan.Sym; signed: BOOL; var L: INT);
1285-begin
1286- spillBelow(depth - 2);
1287- jumpCmp(sy, signed, L);
1288-end;
1289-
1290-(* The two values on top, compared, as a BOOL: true unless notOp, the
1291- opposite comparison, holds. fj and tj are the chains of jumps, made
1292- earlier by and, or and not, that are taken when the whole condition is
1293- false and when it is true; they land here, on the 0 and the 1. *)
1294-proc condValue*(notOp: Scan.Sym; signed: BOOL; fj, tj: INT);
1295-var r, e: INT;
1296-begin
1297- jumpOut(notOp, signed, fj);
1298- X.fixLink(tj);
1299- r := target();
1300- X.movRI(r, 1);
1301- e := NoLabel;
1302- X.jmp(e);
1303- X.fixLink(fj);
1304- X.movRI(r, 0);
1305- X.fixLink(e);
1306- computed(kWord);
1307-end;
1308-
1309-(* jumpBack, fix, fixTo and joinJumps are Gen's names for the encoder's,
1310- so that a port can place jumps its own way. fix(L) places label L here;
1311- fixTo(L, top) makes every jump on chain L go to the earlier place top;
1312- joinJumps makes one chain of two. *)
1313-proc jumpBack*(top: INT);
1314-begin
1315- X.jmpBack(top);
1316-end;
1317-
1318-proc fix*(L: INT);
1319-begin
1320- X.fixLink(L);
1321-end;
1322-
1323-(* A jump table, for a match on the integer in frame slot slot, whose
1324- labels run from lo up for n values. The selector less lo, compared
1325- unsigned (so below lo is above n too), is out of the table if it
1326- isn't below n, and goes to the else arm at elseAt, or, if there is
1327- none, to endL, the end of the match. Else it indexes a table of
1328- 4-byte offsets, each from the start of the lea, that follows the
1329- jump, and the code jumps to its start plus the entry:
1330-
1331- mov rax, [slot]
1332- sub rax, lo
1333- cmp rax, n - 1
1334- ja else
1335- lea rcx, [rip + start] start: this very lea
1336- movsxd rax, [rcx + rax*4 + 17]
1337- add rax, rcx
1338- jmp rax
1339- table: .long arm0 - start, arm1 - start, ...
1340-
1341- The four instructions after the compare are 7, 5, 3 and 2 bytes, so
1342- the table is 17 bytes on, which jumpTable checks. It returns start;
1343- the caller then makes the n entries with tableEntry. *)
1344-proc jumpTable*(slot, lo: I64; n, elseAt: INT; var endL: INT): INT;
1345-const TableAt = 17;
1346-var start: INT;
1347-begin
1348- X.load(RAX, X.mem(RBP, slot), 8, false);
1349- if lo # 0 then X.aluI(X.aluSub, RAX, INT(lo)); end;
1350- X.aluI(X.aluCmp, RAX, n - 1);
1351- if elseAt # NoLabel then X.jccBack(X.ccA, elseAt); else X.jcc(X.ccA, endL); end;
1352- start := Chunk.pc;
1353- X.lea(RCX, X.here());
1354- X.load(RAX, X.memIdx(RCX, RAX, 4, TableAt), 4, true);
1355- X.alu(X.aluAdd, RAX, RCX);
1356- X.jmpR(RAX);
1357- if Chunk.pc # start + TableAt then Diag.fatal("internal error: the jump table is not where it was said"); end;
1358- return start;
1359-end;
1360-
1361-(* The next entry of the table that jumpTable started at table: the
1362- code at target *)
1363-proc tableEntry*(table, target: INT);
1364-begin
1365- Chunk.put4(target - table);
1366-end;
1367-
1368-proc alignLoop*;
1369-begin
1370- X.align(32);
1371-end;
1372-
1373-proc joinJumps*(L1, L2: INT): INT;
1374-begin
1375- return X.joinLinks(L1, L2);
1376-end;
1377-
1378-proc fixTo*(L, top: INT);
1379-begin
1380- X.fixLinkTo(L, top);
1381-end;
1382-
1383-(* Checks *)
1384-
1385-const
1386- NoBase = -2; (* a Mem that is no memory *)
1387- ARegister = -3; (* a Mem that is no memory but a register, its index *)
1388-
1389-(* The name s, interned *)
1390-proc internStr(s: []U8): INT;
1391-begin
1392- return Scan.intern(ADR(s[0]), LEN(s));
1393-end;
1394-
1395-(* The program goes on if the condition cc holds, and otherwise stops
1396- in Rt.fail(what, a, b, len, at, name), which says what failed at p,
1397- found by at, which a stub works out from where it was called; what is
1398- an index a (0), a slice a..b (1), each for a length len, a position a
1399- of the enumeration called name (2), a slice of a pointer a..b that
1400- runs backwards (3), or a nil pointer (4). Rt.fail knows 5 and 6, a
1401- division fault and a stack overflow, which this machine catches
1402- itself, so no check here has them. The arguments go in rdi, rsi, rdx,
1403- rcx, r8 and r9: a is in register ra, b in RDX; len is in memory at m,
1404- or n if m.base is NoBase, or in register m.index if it is ARegister.
1405- rdi and rsi are passed on as they were, since a parameter may be kept
1406- in them, for the trap report to show: so a goes to the stub in rax.
1407- The failing code is out of the way, at the
1408- procedure's end (endFails), so that a check that holds costs a jump
1409- not taken; it has p for its place (at is p's offset in the source),
1410- never returns, and may use any register once it has read what it
1411- needs. *)
1412-proc check(cc, what: INT; p: Diag.Pos; ra: INT; m: X.Mem; n: I64; name: INT);
1413-begin
1414- if numFails > LEN(fails) - 1 then
1415- _ := Scan.mark(Diag.say("more than {} checks in one procedure", [Fmt.int(LEN(fails))]));
1416- return;
1417- end;
1418- fails[numFails].L := NoLabel;
1419- X.jcc(cc xor 1, fails[numFails].L); (* x86's conditions come in pairs, the other one its last bit flipped *)
1420- fails[numFails].what := what;
1421- fails[numFails].ra := ra;
1422- fails[numFails].m := m;
1423- fails[numFails].n := n;
1424- fails[numFails].name := name;
1425- fails[numFails].at := p.a;
1426- INC(numFails);
1427-end;
1428-
1429-(* The failures of the procedure's checks: each gives Rt.fail its values
1430- and the place of the offending expression, through a stub for its
1431- kind, which takes the place from where it was called *)
1432-proc endFails;
1433-var i, line, col: INT; f: Fail;
1434-begin
1435- for i := 0 to numFails - 1 do
1436- f := fails[i];
1437- X.fixLink(f.L);
1438- line, col := Scan.lineCol(f.at);
1439- Chunk.noteLine(line, col);
1440- if f.ra # RAX then X.movRR(RAX, f.ra); end;
1441- if f.m.base = NoBase then X.movRI(RCX, f.n);
1442- elsif f.m.base = ARegister then X.movRR(RCX, f.m.index);
1443- else X.load(RCX, f.m, 8, false); end;
1444- if f.name >= 0 then X.lea(R9, X.memRip(f.name, 0)); end;
1445- if failStubs[f.what] < 0 then
1446- failStubs[f.what] := Chunk.newChunk(Chunk.secText, internStr("Rt"), internStr(StubNames[f.what]));
1447- end;
1448- X.callChunk(failStubs[f.what]);
1449- end;
1450- numFails := 0;
1451-end;
1452-
1453-(* For check: a length known here, not in memory *)
1454-proc noMem: X.Mem;
1455-begin
1456- return X.mem(NoBase, 0);
1457-end;
1458-
1459-(* For check: a length in register r, a slice's in registers *)
1460-proc inRegister(r: INT): X.Mem;
1461-var m: X.Mem;
1462-begin
1463- m := X.mem(ARegister, 0);
1464- m.index := r;
1465- return m;
1466-end;
1467-
1468-(* The index on top is below n, unsigned *)
1469-proc checkIndex*(n: I64; p: Diag.Pos);
1470-var r: INT;
1471-begin
1472- r := peek(depth - 1);
1473- cmpI(r, n);
1474- check(X.ccB, 0, p, r, noMem(), n, -1);
1475-end;
1476-
1477-(* The integer on top is a position of an enumeration of n names *)
1478-proc checkEnum*(n: I64; name: INT; p: Diag.Pos);
1479-var r: INT;
1480-begin
1481- r := top();
1482- cmpI(r, n);
1483- check(X.ccB, 2, p, r, noMem(), n, name);
1484-end;
1485-
1486-(* The address on top, from a pointer, which is to be used reach bytes
1487- past: the program stops if it is nil, unless the machine would stop
1488- it, as for a reach within NilPage. *)
1489-proc checkNil*(reach: I64; p: Diag.Pos);
1490-var r: INT;
1491-begin
1492- if reach <= NilPage then return; end;
1493- r := top();
1494- X.testRR(r, r);
1495- check(X.ccNE, 4, p, r, noMem(), 0, -1);
1496-end;
1497-
1498-(* The displacement disp of an element of size bytes, with the offset of
1499- the index on top taken into it if it fits: s[k - 1] is [r13 + r9 * 8
1500- - 8] *)
1501-proc indexOff(size, disp: I64): I64;
1502-begin
1503- if fits32(disp + stack[depth - 1].off * size) then return disp + takeOff(depth - 1) * size; end;
1504- return disp;
1505-end;
1506-
1507-(* Pops an index, and the address of the slice at a if it is on the
1508- stack, and pushes the address of its element of size bytes: the
1509- index, checked against the length, times size, plus the pointer.
1510- It is worked out in the index's own register, which then holds the
1511- address; but if the slice's address is on the stack, under the
1512- index, the element's register is the one that holds that, still
1513- needed, so the work is done in rax. A slice in registers is
1514- compared with and added to them; for an element of 1, 2, 4 or 8
1515- bytes, its address is only noted, as the operand [pointer + index *
1516- size], to be read or written where it is used (lIdx). *)
1517-proc indexSlice*(a: Adr; size: I64; checked: BOOL; p: Diag.Pos);
1518-var m, ml: X.Mem; r: INT; inRax: BOOL; o: I64;
1519-begin
1520- if (a.base = bReg) and (((size = 1) or (size = 2) or (size = 4) or (size = 8))) then
1521- o := 0;
1522- if not checked then o := indexOff(size, 0); end;
1523- r := peek(depth - 1);
1524- if checked then
1525- X.alu(X.aluCmp, r, a.hi);
1526- check(X.ccB, 0, p, r, inRegister(a.hi), 0, -1);
1527- end;
1528- drop();
1529- newMem(lIdx, X.memIdx(a.chunk, r, INT(size), o), kWord, 8, false);
1530- return;
1531- end;
1532- inRax := a.base = bStack;
1533- if inRax then r := RAX; popTo(RAX);
1534- else r := top(); drop(); end;
1535- if a.base = bReg then
1536- if checked then
1537- X.alu(X.aluCmp, r, a.hi);
1538- check(X.ccB, 0, p, r, inRegister(a.hi), 0, -1);
1539- end;
1540- mulI(r, size);
1541- X.alu(X.aluAdd, r, a.chunk);
1542- else
1543- m := place(a, RCX);
1544- ml := m; ml.disp := ml.disp + 8;
1545- if checked then
1546- X.aluM(X.aluCmp, r, ml);
1547- check(X.ccB, 0, p, r, ml, 0, -1);
1548- end;
1549- mulI(r, size);
1550- X.aluM(X.aluAdd, r, m);
1551- end;
1552- if inRax then X.movRR(target(), RAX);
1553- else _ := claim(depth, kWord); end; (* the index's register again, now for the address *)
1554- computed(kWord);
1555-end;
1556-
1557-(* Pops an index, checked, and makes the address of the element it
1558- picks of the array at a. An element of 1, 2,
1559- 4 or 8 bytes is only noted, as the operand [base + index * size]
1560- (lIdx): an array in the frame has rbp as its base, and one in a
1561- chunk, if the index is a variable's register, its address made in
1562- the value's own register. Any other is added up. *)
1563-proc indexArray*(a: Adr; size: I64);
1564-var r, b: INT; o: I64;
1565-begin
1566- if (((size = 1) or (size = 2) or (size = 4) or (size = 8))) and (a.base = bFrame) then
1567- o := indexOff(size, a.off);
1568- r := peek(depth - 1);
1569- drop();
1570- newMem(lIdx, X.memIdx(RBP, r, INT(size), o), kWord, 8, false);
1571- elsif (((size = 1) or (size = 2) or (size = 4) or (size = 8))) and (a.base = bGlobal) and (stack[depth - 1].loc = lHeld) then
1572- o := indexOff(size, 0);
1573- r := peek(depth - 1);
1574- drop();
1575- b := target();
1576- X.lea(b, X.memRip(a.chunk, INT(a.off)));
1577- newMem(lIdx, X.memIdx(b, r, INT(size), o), kWord, 8, false);
1578- else
1579- mulI(top(), size);
1580- pushAdr(a);
1581- op(Scan.sPlus, kWord, 8, false);
1582- end;
1583-end;
1584-
1585-(* Pops lo and hi, and the address of the array or slice at a if it is
1586- on the stack, and makes the slice lo..hi of it, with elements of size
1587- bytes, in the frame at tmp; the array has n elements. *)
1588-proc slice*(a: Adr; isArray: BOOL; n, size, tmp: I64; checked: BOOL; p: Diag.Pos);
1589-var m, ml: X.Mem;
1590-begin
1591- popTo(RDX);
1592- popTo(RCX);
1593- if a.base = bSlot then clobberArgs(); end; (* place loads its slot into rdi *)
1594- if a.base = bReg then
1595- ml := inRegister(a.hi); (* a slice in registers *)
1596- else
1597- m := place(a, RDI);
1598- ml := m; ml.disp := ml.disp + 8;
1599- end;
1600- if checked then
1601- (* two checks, both unsigned, so that a negative bound fails too:
1602- hi against the length, then lo against hi *)
1603- if isArray then cmpI(RDX, n); ml := noMem();
1604- elsif a.base = bReg then X.alu(X.aluCmp, RDX, a.hi);
1605- else X.aluM(X.aluCmp, RDX, ml); end;
1606- check(X.ccBE, 1, p, RCX, ml, n, -1);
1607- X.alu(X.aluCmp, RCX, RDX);
1608- check(X.ccBE, 1, p, RCX, ml, n, -1);
1609- end;
1610- X.movRR(RAX, RDX);
1611- X.alu(X.aluSub, RAX, RCX);
1612- X.store(X.mem(RBP, tmp + 8), RAX, 8);
1613- mulI(RCX, size);
1614- if isArray then X.lea(RAX, m);
1615- elsif a.base = bReg then X.movRR(RAX, a.chunk);
1616- else X.load(RAX, m, 8, false); end;
1617- X.alu(X.aluAdd, RAX, RCX);
1618- X.store(X.mem(RBP, tmp), RAX, 8);
1619-end;
1620-
1621-(* COPY: the elements of the slice in the frame at sOff, of size bytes
1622- each, to the start of the one at dOff, which must be at least as long
1623- (the source may be shorter), as one block; backwards when the
1624- destination is above the source, so that an overlap comes out right. *)
1625-proc copySlice*(dOff, sOff, size: I64; checked: BOOL; p: Diag.Pos);
1626-var ml: X.Mem; L, E: INT;
1627-begin
1628- clobberArgs();
1629- X.load(RDX, X.mem(RBP, sOff + 8), 8, false);
1630- if checked then
1631- ml := X.mem(RBP, dOff + 8);
1632- X.movRI(RAX, 0);
1633- X.aluM(X.aluCmp, RDX, ml);
1634- check(X.ccBE, 1, p, RAX, ml, 0, -1);
1635- end;
1636- X.movRR(RCX, RDX);
1637- mulI(RCX, size);
1638- X.load(RSI, X.mem(RBP, sOff), 8, false);
1639- X.load(RDI, X.mem(RBP, dOff), 8, false);
1640- X.alu(X.aluCmp, RDI, RSI);
1641- L := NoLabel;
1642- X.jcc(X.ccBE, L); (* the destination is not above: forwards, at L *)
1643- (* backwards: std makes rep movsb run downward, so it starts at the
1644- last byte of each *)
1645- X.lea(RSI, X.memIdx(RSI, RCX, 1, -1));
1646- X.lea(RDI, X.memIdx(RDI, RCX, 1, -1));
1647- X.std();
1648- X.repMovsb();
1649- X.cld();
1650- E := NoLabel;
1651- X.jmp(E);
1652- X.fixLink(L);
1653- X.repMovsb();
1654- X.fixLink(E);
1655-end;
1656-
1657-(* Pops a pointer, lo and hi, and makes the slice p[lo..hi] at tmp. Its
1658- bounds can't be known, but it can't run backwards. *)
1659-proc slicePtr*(size, tmp: I64; checked: BOOL; p: Diag.Pos);
1660-begin
1661- clobberArgs();
1662- popTo(RDX);
1663- popTo(RCX);
1664- popTo(RDI);
1665- if checked then
1666- X.alu(X.aluCmp, RCX, RDX);
1667- check(X.ccLE, 3, p, RCX, noMem(), 0, -1);
1668- end;
1669- X.movRR(RAX, RDX);
1670- X.alu(X.aluSub, RAX, RCX);
1671- X.store(X.mem(RBP, tmp + 8), RAX, 8);
1672- mulI(RCX, size);
1673- X.alu(X.aluAdd, RCX, RDI);
1674- X.store(X.mem(RBP, tmp), RCX, 8);
1675-end;
1676-
1677-(* Calls *)
1678-
1679-(* The call c, its c.n arguments the values on top of the stack, in
1680- registers, noted as constants or spilled. They go to registers or the
1681- machine's stack, the procedure is called, and its result, if any,
1682- comes back: one value is pushed, two results are pushed as two values,
1683- a slice or a record is stored in the temporary c.ret.
1684-
1685- ni and nf count the integer and the real registers used so far, k the
1686- arguments on the machine's stack, and pad is 1 when a padding quadword
1687- is needed. *)
1688-
1689-proc call*(var c: CallInfo);
1690-var
1691- res: ^Sym.Type; i, ni, nf, k, pad, r, first: INT;
1692- onStack: [64]BOOL; late: [2]INT; (* late: the values for r8 and r9 *)
1693-begin
1694- (* the arguments are the c.n values on top, where computing them left
1695- them; the registers in use under them are saved around the call *)
1696- clobberArgs();
1697- first := depth - c.n;
1698- spillBelow(first);
1699- res := c.sig^.base;
1700- c.ret := 0;
1701- ni := 0; nf := 0;
1702- if (res # nil) and (Sym.behindPointer(res) or (res^.form = Sym.fSlice)) then
1703- c.ret := allocTemp(res^.size, res^.align);
1704- if Sym.behindPointer(res) then ni := 1; end;
1705- end;
1706- (* the System V classes: each argument in the next free register of
1707- its kind, or else on the stack *)
1708- k := 0;
1709- for i := 0 to c.n - 1 do
1710- if c.isF[i] then
1711- onStack[i] := nf >= 8;
1712- if nf < 8 then INC(nf); end;
1713- else
1714- (* a slice's words both go in registers, or both on the stack *)
1715- if (i > 0) and c.pair[i - 1] then onStack[i] := onStack[i - 1];
1716- elsif c.pair[i] then onStack[i] := ni > 4;
1717- else onStack[i] := ni >= 6; end;
1718- if not onStack[i] then INC(ni); end;
1719- end;
1720- if onStack[i] then INC(k); end;
1721- end;
1722- (* System V wants rsp a multiple of 16 at the call. A procedure's body
1723- has it so (push rbp, and a frame size that is a multiple of 16), so
1724- a quadword of padding makes the count pushed since even. The stack
1725- arguments go right to left, so that the first is at the lowest
1726- address. *)
1727- pad := 0;
1728- if ((pushed + k) & 1) # 0 then pad := 1; end;
1729- if pad # 0 then X.aluI(X.aluSub, RSP, 8); end;
1730- for i := c.n - 1 to 0 by -1 do
1731- if onStack[i] then
1732- valueTo(first + i, RAX);
1733- X.push(RAX);
1734- end;
1735- end;
1736- ni := 0; nf := 0;
1737- late[0] := -1; late[1] := -1;
1738- if (c.ret # 0) and Sym.behindPointer(res) then X.lea(RDI, X.mem(RBP, c.ret)); ni := 1; end;
1739- (* rdi, rsi, rdx, rcx and the xmm registers first; r8 and r9 last, as
1740- they are stack registers and may hold arguments not yet moved: late
1741- is the value for each. The fifth goes through rax, so that writing r8
1742- doesn't destroy a value still wanted for r9. *)
1743- for i := 0 to c.n - 1 do
1744- if not onStack[i] then
1745- if c.isF[i] then
1746- xValueTo(first + i, nf);
1747- INC(nf);
1748- else
1749- if ni < 4 then valueTo(first + i, IntRegs[ni]); else late[ni - 4] := first + i; end;
1750- INC(ni);
1751- end;
1752- end;
1753- end;
1754- if late[0] >= 0 then valueTo(late[0], RAX); end;
1755- if late[1] >= 0 then valueTo(late[1], R9); end;
1756- if late[0] >= 0 then X.movRR(R8, RAX); end;
1757- for i := 1 to c.n do drop(); end;
1758- (* a procedure taking ... is told in al how many xmm registers it got *)
1759- if c.sig^.variadic then X.movRI(RAX, nf); end;
1760- if c.ext then X.callM(X.memRip(c.chunk, 0));
1761- elsif c.chunk >= 0 then X.callChunk(c.chunk);
1762- else
1763- (* r11 is scratch: caller-saved, carrying no argument, and free,
1764- as the value stack was spilled above *)
1765- X.load(R11, X.mem(RBP, c.target), 8, false);
1766- X.callR(R11);
1767- end;
1768- if k + pad > 0 then X.aluI(X.aluAdd, RSP, 8 * (k + pad)); end;
1769- (* the variables in xmm registers, which the call may have changed,
1770- from their slots *)
1771- for i := 0 to 3 do
1772- if (regMask & (1 shl (XBit + i))) # 0 then
1773- X.movsXM(XVarRegs[i] - XmmVar, X.mem(RBP, homes[i]), false);
1774- end;
1775- end;
1776- (* the result: a slice in rax and rdx goes to the caller's temporary,
1777- two results on the stack, the first under the second, and a single
1778- value on top *)
1779- if res # nil then
1780- if res^.form = Sym.fSlice then
1781- X.store(X.mem(RBP, c.ret), RAX, 8);
1782- X.store(X.mem(RBP, c.ret + 8), RDX, 8);
1783- elsif Sym.inTwoRegs(res) then
1784- X.movRR(target(), RAX); computed(kWord);
1785- X.movRR(target(), RDX); computed(kWord);
1786- elsif (c.ret = 0) and (res^.form = Sym.fReal) then
1787- X.movX(xTarget(), 0);
1788- computed(kindOf(res));
1789- elsif c.ret = 0 then
1790- r := target();
1791- X.movRR(r, RAX);
1792- if res^.form = Sym.fBool then X.extend(r, 1, false);
1793- elsif (res^.form = Sym.fInt) and (res^.size < 8) then X.extend(r, INT(res^.size), res^.signed); end;
1794- computed(kindOf(res));
1795- end;
1796- end;
1797-end;
1798-
1799-(* Frames *)
1800-
1801-(* A slot of size bytes in the frame: its offset from rbp, negative, as
1802- the frame grows down. A temporary is released at the end of its
1803- statement (tempMark, releaseTemps); allocPerm's lasts the procedure. *)
1804-proc allocTemp*(size, align: I64): I64;
1805-begin
1806- if align < 1 then align := 1; end;
1807- frameTop := Sym.alignUp(frameTop + size, align);
1808- if frameTop > frameMax then frameMax := frameTop; end;
1809- return -frameTop;
1810-end;
1811-
1812-proc allocPerm*(size, align: I64): I64;
1813-var s: I64;
1814-begin
1815- s := allocTemp(size, align);
1816- permTop := frameTop;
1817- return s;
1818-end;
1819-
1820-proc tempMark*: I64;
1821-begin
1822- return frameTop;
1823-end;
1824-
1825-(* The slots allocated since the mark m are free again, but those
1826- allocPerm made stay *)
1827-proc releaseTemps*(m: I64);
1828-begin
1829- if m < permTop then m := permTop; end;
1830- frameTop := m;
1831-end;
1832-
1833-(* Every slot used so far stays reserved for the rest of the procedure:
1834- a deferred statement's temporaries live until it runs. *)
1835-proc keepTemps*;
1836-begin
1837- frameTop := frameMax;
1838- permTop := frameMax;
1839-end;
1840-
1841-(* The parameters' places: each in a frame slot of its own, stored there
1842- from its register on entry, or above the frame where the caller
1843- pushed it. A var parameter, and a record or array passed by value,
1844- holds an address (ind). *)
1845-proc beginProc*(sig: ^Sym.Type; params: ^Sym.Obj);
1846-var p: ^Sym.Obj; ni, nf, k: INT; stackOff: I64; f: BOOL;
1847-begin
1848- frameTop := 0; frameMax := 0; permTop := 0;
1849- resetStack(0, 0);
1850- exitL := NoLabel;
1851- numIn := 0;
1852- lost := false;
1853- kept := 0;
1854- resType := sig^.base;
1855- procParams := params;
1856- regMask := 0;
1857- ni := 0; nf := 0; stackOff := 16; (* stackOff: above the saved rbp and the return address *)
1858- if (resType # nil) and Sym.behindPointer(resType) then
1859- retSlot := allocPerm(8, 8);
1860- inReg[0] := RDI; inSlot[0] := retSlot; inSize[0] := 8; inObj[0] := nil;
1861- numIn := 1; ni := 1;
1862- end;
1863- p := params;
1864- while p # nil do
1865- p^.ind := p^.isVar or (Sym.isAggregate(p^.typ) and (p^.typ^.form # Sym.fSlice));
1866- f := (p^.typ^.form = Sym.fReal) and not p^.isVar;
1867- if (p^.typ^.form = Sym.fSlice) and not p^.isVar then
1868- (* its two words, in two registers or both on the stack *)
1869- if ni <= 4 then
1870- p^.val := allocPerm(16, 8);
1871- for k := 0 to 1 do
1872- inReg[numIn] := IntRegs[ni]; inSlot[numIn] := p^.val + I64(8 * k);
1873- inSize[numIn] := 8; inObj[numIn] := p;
1874- INC(numIn); INC(ni);
1875- end;
1876- else
1877- p^.val := stackOff;
1878- INC(stackOff, 16);
1879- end;
1880- elsif (f and (nf < 8)) or (not f and (ni < 6)) then
1881- p^.val := allocPerm(8, 8);
1882- (* a real's register, xmm nf, is told from an integer register by
1883- a negative number (enterBody decodes it) *)
1884- if f then
1885- inReg[numIn] := -1 - nf; INC(nf);
1886- else
1887- inReg[numIn] := IntRegs[ni]; INC(ni);
1888- end;
1889- inSlot[numIn] := p^.val;
1890- inObj[numIn] := p;
1891- if p^.ind then inSize[numIn] := 8;
1892- elsif p^.typ^.form in {Sym.fInt, Sym.fBool, Sym.fEnum, Sym.fSet, Sym.fReal} then inSize[numIn] := INT(p^.typ^.size);
1893- else inSize[numIn] := 8; end;
1894- INC(numIn);
1895- else
1896- p^.val := stackOff;
1897- INC(stackOff, 8);
1898- end;
1899- p := p^.next;
1900- end;
1901- paramTop := frameTop;
1902-end;
1903-
1904-(* The frame as beginProc left it, with the parameters' slots only: the
1905- locals are given theirs again once their registers are chosen. *)
1906-proc resetLocals*;
1907-begin
1908- frameTop := paramTop; frameMax := paramTop; permTop := paramTop;
1909-end;
1910-
1911-(* The register the word (0, or 1 for a slice's second) of parameter o
1912- arrives in, or -1 if it comes on the stack or in an xmm register *)
1913-proc arrivesIn(o: ^Sym.Obj; word: INT): INT;
1914-var i, r: INT;
1915-begin
1916- r := -1;
1917- for i := 0 to numIn - 1 do
1918- if (inObj[i] = o) and (inSlot[i] = o^.val + I64(8 * word)) and (inReg[i] >= 0) then r := inReg[i]; end;
1919- end;
1920- return r;
1921-end;
1922-
1923-(* Parameter o, of a procedure that calls nothing, stays in the register
1924- it arrives in if that is rdi or rsi, which only a call or a copy needs:
1925- no register is saved for it, and nothing is moved. A slice stays only
1926- if it has both. If the procedure turns out to copy after all, lost is
1927- set, and it is compiled again with o in memory. *)
1928-proc keepArrived*(o: ^Sym.Obj);
1929-var r: INT;
1930-begin
1931- r := arrivesIn(o, 0);
1932- if o^.typ^.form = Sym.fSlice then
1933- if (r = RDI) and (arrivesIn(o, 1) = RSI) then o^.reg := RDI; o^.reg2 := RSI; end;
1934- elsif (r = RDI) or (r = RSI) then o^.reg := r; end;
1935-end;
1936-
1937-(* Whether parameter o is kept where it arrived *)
1938-proc keptIn*(o: ^Sym.Obj): BOOL;
1939-begin
1940- return (o^.reg = RDI) or (o^.reg = RSI);
1941-end;
1942-
1943-(* The locals in memory have their slots: the prologue zeroes those and
1944- nothing below. The procedure keeps variables in the registers of
1945- mask, which are saved next, a quadword each, in slots that need no
1946- zeroing; the frame as it then stands is where a second try at the
1947- body starts. *)
1948-proc useRegs*(mask: INT);
1949-var i, k: INT; p: ^Sym.Obj;
1950-begin
1951- zeroTop := permTop;
1952- regMask := mask;
1953- (* the parameters left in rdi and rsi, as they arrived *)
1954- kept := 0;
1955- p := procParams;
1956- while p # nil do
1957- if ((p^.reg = RDI) or (p^.reg = RSI)) then kept := kept | (1 shl p^.reg); end;
1958- if ((p^.reg2 = RDI) or (p^.reg2 = RSI)) then kept := kept | (1 shl p^.reg2); end;
1959- p := p^.next;
1960- end;
1961- k := 0;
1962- for i := 0 to 4 do
1963- if (mask & (1 shl i)) # 0 then INC(k); end;
1964- end;
1965- if k > 0 then saveAt := allocPerm(8 * k, 8); end;
1966- frameAt[0] := frameTop; frameAt[1] := frameMax; frameAt[2] := permTop;
1967-end;
1968-
1969-(* The variable in xmm register r of XVarRegs has a slot of 8 bytes at
1970- slot, kept as it changes *)
1971-proc xHome*(r: INT; slot: I64);
1972-begin
1973- homes[r - XVarRegs[0]] := slot;
1974-end;
1975-
1976-proc markCode*(var m: CodeMark);
1977-begin
1978- m.pc := Chunk.pc; m.fixups := Chunk.numFixups; m.lines := Chunk.numLines; m.said := X.saidCount();
1979- m.fails := numFails;
1980-end;
1981-
1982-(* The code made since m taken back, as if it had never been made; the
1983- frame is left as it is *)
1984-proc rewind*(m: CodeMark);
1985-begin
1986- Chunk.rewindTo(m.pc, m.fixups, m.lines);
1987- X.unsay(m.said);
1988- numFails := m.fails;
1989-end;
1990-
1991-(* For a second try at the body: the code as it was at m, and the frame
1992- as useRegs found it *)
1993-proc redo*(m: CodeMark);
1994-begin
1995- Chunk.rewindTo(m.pc, m.fixups, m.lines);
1996- X.unsay(m.said);
1997- numFails := 0;
1998- lost := false;
1999- frameTop := frameAt[0]; frameMax := frameAt[1]; permTop := frameAt[2];
2000- exitL := NoLabel;
2001-end;
2002-
2003-(* The prologue, which is for the procedure's first line. Only the
2004- locals in memory are zeroed, from the parameters' slots down to
2005- zeroTop: the parameters are stored over their slots next, the
2006- registers of variables are zeroed in place, their save slots are
2007- written before they are read, and so is every temporary. *)
2008-proc enterBody*(c, line: INT);
2009-var i, loop, r: INT; n: I64; p: ^Sym.Obj;
2010-begin
2011- Chunk.beginChunk(c);
2012- codeChunk := c;
2013- Chunk.noteLine(line, 1); (* a declaration starts a line *)
2014- X.push(RBP);
2015- X.movRR(RBP, RSP);
2016- X.say("sub rsp, frame");
2017- (* sub rsp, imm32: always the form with a 32-bit field, so that endProc
2018- can patch the frame's size in *)
2019- Chunk.put1(48H); Chunk.put1(81H); Chunk.put1(0ECH);
2020- frameFix := Chunk.pc; Chunk.put4(0);
2021- 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);
2033- end;
2034- (* each register that holds a variable is saved, for the caller, and
2035- zeroed, as a variable starts at zero *)
2036- Chunk.setSaves(c, regMask & ((1 shl XBit) - 1), INT(saveAt));
2037- n := 0;
2038- for i := 0 to 4 do
2039- if (regMask & (1 shl i)) # 0 then
2040- X.store(X.mem(RBP, saveAt + 8 * n), VarRegs[i], 8);
2041- X.movRI(VarRegs[i], 0);
2042- INC(n);
2043- end;
2044- end;
2045- (* and each xmm register that holds a variable, zeroed, as its slot
2046- is: the caller keeps its own *)
2047- for i := 0 to 3 do
2048- if (regMask & (1 shl (XBit + i))) # 0 then
2049- X.movRI(RAX, 0);
2050- X.movqXR(XVarRegs[i] - XmmVar, RAX);
2051- end;
2052- end;
2053- (* the parameters that came in registers, to their slots or, for a
2054- register variable, to its register: a slice's second word, the one
2055- for the slot 8 bytes into its own, to its length's *)
2056- for i := 0 to numIn - 1 do
2057- if inReg[i] < 0 then
2058- X.movsMX(X.mem(RBP, inSlot[i]), -1 - inReg[i], false);
2059- if inObj[i]^.reg # 0 then X.movX(inObj[i]^.reg - XmmVar, -1 - inReg[i]); end;
2060- elsif (inObj[i] # nil) and (inObj[i]^.reg # 0) then
2061- r := inObj[i]^.reg;
2062- if inSlot[i] # inObj[i]^.val then r := inObj[i]^.reg2; end;
2063- if r # inReg[i] then X.movRR(r, inReg[i]); end; (* else it is kept where it is *)
2064- if inSize[i] < 8 then X.extend(r, inSize[i], inObj[i]^.typ^.signed); end;
2065- else
2066- X.store(X.mem(RBP, inSlot[i]), inReg[i], inSize[i]);
2067- end;
2068- end;
2069- (* a register variable's parameter that came on the stack, above the
2070- frame (val > 0), is loaded from there *)
2071- p := procParams;
2072- while p # nil do
2073- if (p^.reg # 0) and (p^.val > 0) then
2074- if p^.typ^.form = Sym.fReal then
2075- X.movsXM(p^.reg - XmmVar, X.mem(RBP, p^.val), p^.typ^.size = 4);
2076- elsif p^.typ^.form in {Sym.fInt, Sym.fBool, Sym.fEnum, Sym.fSet} then
2077- X.load(p^.reg, X.mem(RBP, p^.val), INT(p^.typ^.size), p^.typ^.signed);
2078- else
2079- X.load(p^.reg, X.mem(RBP, p^.val), 8, false);
2080- if p^.typ^.form = Sym.fSlice then X.load(p^.reg2, X.mem(RBP, p^.val + 8), 8, false); end;
2081- end;
2082- end;
2083- p := p^.next;
2084- end;
2085-end;
2086-
2087-(* Pops one of several results, a value of size bytes, into its place
2088- off bytes into the caller's, behind the hidden pointer. *)
2089-proc resultTo*(off: I64; size: INT);
2090-var r: INT; fl: BOOL;
2091-begin
2092- r := top();
2093- fl := isReal(depth - 1);
2094- drop();
2095- X.load(RCX, X.mem(RBP, retSlot), 8, false);
2096- if fl then X.movsMX(X.mem(RCX, off), r, size = 4);
2097- else X.store(X.mem(RCX, off), r, size); end;
2098-end;
2099-
2100-(* Pops an address, and copies size bytes from it to the result, off
2101- bytes into it. *)
2102-proc copyResult*(off, size: I64);
2103-begin
2104- clobberArgs();
2105- popTo(RSI);
2106- X.load(RDI, X.mem(RBP, retSlot), 8, false);
2107- if off # 0 then X.lea(RDI, X.mem(RDI, off)); end;
2108- copyBytes(size);
2109-end;
2110-
2111-(* return: the result, a value on top, goes in rax or xmm0; two words,
2112- the two values on top, in rax and rdx; one behind the hidden pointer
2113- goes back with that pointer in rax. *)
2114-proc returnJump*;
2115-begin
2116- if resType # nil then
2117- if Sym.behindPointer(resType) then
2118- X.load(RAX, X.mem(RBP, retSlot), 8, false);
2119- elsif Sym.inTwoRegs(resType) then
2120- popTo(RDX);
2121- popTo(RAX);
2122- elsif resType^.form = Sym.fReal then
2123- xValueTo(depth - 1, 0);
2124- drop();
2125- else
2126- popTo(RAX);
2127- end;
2128- end;
2129- X.jmp(exitL);
2130-end;
2131-
2132-(* The first of what try does where the error isn't nil (the report, 7.8):
2133- the machine's stack made even, as the deferred statements about to be
2134- run expect to find it. try can stand among the arguments of another
2135- call, where quadwords have been pushed. Nothing is lost: the frame is
2136- above rsp, and the code returns through the frame pointer. *)
2137-proc tryAlign*;
2138-begin
2139- X.aluI(X.aluAnd, RSP, -16);
2140-end;
2141-
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);
2147-var f: ^Sym.Obj;
2148-begin
2149- if Sym.behindPointer(resType) then
2150- X.load(RDI, X.mem(RBP, retSlot), 8, false);
2151- X.movRI(RCX, resType^.size);
2152- X.movRI(RAX, 0);
2153- X.repStosb();
2154- f := resType^.fields;
2155- while f^.next # nil do f := f^.next; end;
2156- X.load(RCX, X.mem(RBP, slot), 8, false);
2157- X.load(RDX, X.mem(RBP, retSlot), 8, false);
2158- X.store(X.mem(RDX, f^.val), RCX, 8);
2159- X.load(RAX, X.mem(RBP, retSlot), 8, false);
2160- elsif Sym.inTwoRegs(resType) then
2161- X.load(RDX, X.mem(RBP, slot), 8, false);
2162- X.movRI(RAX, 0);
2163- else
2164- X.load(RAX, X.mem(RBP, slot), 8, false);
2165- end;
2166- X.jmp(exitL);
2167-end;
2168-
2169-(* The end of the procedure in chunk c: the code that returns, and the
2170- frame's size, known only now, patched into its prologue. If it is
2171- open, running off its end, it returns zeros. *)
2172-proc endProc*(c: INT; open: BOOL): ERROR;
2173-var n: I64; i: INT;
2174-begin
2175- codeChunk := -1;
2176- if (depth # 0) or (pushed # 0) then Diag.fatal("internal error: stack depth"); end;
2177- if open then
2178- if Sym.behindPointer(resType) then
2179- X.load(RDI, X.mem(RBP, retSlot), 8, false);
2180- X.movRI(RCX, resType^.size);
2181- X.movRI(RAX, 0);
2182- X.repStosb();
2183- X.load(RAX, X.mem(RBP, retSlot), 8, false);
2184- else
2185- X.movRI(RAX, 0);
2186- if Sym.inTwoRegs(resType) then X.movRI(RDX, 0); end;
2187- X.movqXR(0, RAX);
2188- end;
2189- else
2190- X.dropJumpTo(exitL);
2191- end;
2192- X.fixLink(exitL);
2193- n := 0;
2194- for i := 0 to 4 do
2195- if (regMask & (1 shl i)) # 0 then
2196- X.load(VarRegs[i], X.mem(RBP, saveAt + 8 * n), 8, false);
2197- INC(n);
2198- end;
2199- end;
2200- X.leave();
2201- X.ret();
2202- endFails();
2203- n := Sym.alignUp(frameMax, 16);
2204- if n < 16 then n := 16; end;
2205- if n > 2147483647 then return Scan.mark("frame too big"); end;
2206- Chunk.put4At(frameFix, INT(n));
2207- (* the listing's text for the sub, which starts 3 bytes (REX.W, opcode,
2208- ModRM) before its immediate *)
2209- if X.listing then X.restate(frameFix - 3, Diag.say("sub rsp, {}", [Fmt.int(INT(n))])); end;
2210- Chunk.endChunk(c);
2211- return nil;
2212-end;
2213-
2214-(* A deferred statement is compiled where it stands, as a subroutine of
2215- its procedure that the code jumps over, in the procedure's own frame
2216- (the same rbp), so that it sees all its variables; deferBegin gives its
2217- address and what pushed was, and starts it, with the return address
2218- pushed. The stack is empty where it is called, and where it begins. *)
2219-proc deferBegin*(var L: INT): (INT, INT);
2220-var saved: INT;
2221-begin
2222- X.jmp(L);
2223- saved := pushed;
2224- pushed := 1;
2225- return Chunk.pc, saved;
2226-end;
2227-
2228-proc deferEnd*(L, saved: INT);
2229-begin
2230- keepTemps();
2231- X.ret();
2232- X.fixLink(L);
2233- pushed := saved;
2234-end;
2235-
2236-proc runDefer*(at: INT);
2237-begin
2238- X.callBack(at);
2239-end;
2240-
2241-(* The entry point, _start, and its chunk: it saves argc and argv, and
2242- the address of the places for Rt; runs every used module's body, then
2243- main; and ends with Rt.exit, its status main's or 0. A dynamic program
2244- starts as C's crt1 does, through __libc_start_main(main, argc, argv,
2245- nil, nil, rtld_fini, stack_end), with rsp aligned; its main first
2246- gives Rt C's exit, in cExit.
2247-
2248- dynamic: the program uses C. first: the first module, whose chain
2249- gives the order of the bodies. mainObj: the program's main procedure, or
2250- nil. cExit and exitProc: the chunks of Rt's cExit and exit. The
2251- first numLinks of links: the addresses Rt is given, of what the program
2252- has: the places, and the profiler and calls; what it isn't given,
2253- nothing reaches, and the linker leaves out. *)
2254-proc entryPoint*(dynamic: BOOL; first: ^Sym.Module; mainObj: ^Sym.Obj; cExit, exitProc: INT; links: []Link; numLinks: INT): INT;
2255-var entry, start, i: INT; m: ^Sym.Module;
2256-begin
2257- entry := Chunk.newChunk(Chunk.secText, -1, internStr("_start"));
2258- if dynamic then
2259- start := Chunk.newChunk(Chunk.secText, -1, internStr("main"));
2260- Chunk.beginChunk(entry);
2261- (* at the start rdx holds rtld_fini, from the dynamic loader, and the
2262- stack argc, then argv *)
2263- X.movRI(X.RBP, 0); (* no frame above, where a trace stops *)
2264- X.movRR(R9, RDX); (* rtld_fini, the sixth argument *)
2265- X.pop(RSI); (* argc, the second *)
2266- X.movRR(RDX, RSP); (* argv, the third *)
2267- X.aluI(X.aluAnd, RSP, -16);
2268- X.push(RAX); (* padding, so that the next push, the seventh *)
2269- X.push(RSP); (* argument, stack_end, leaves rsp aligned *)
2270- X.movRI(R8, 0); (* fini and init: none *)
2271- X.movRI(RCX, 0);
2272- X.lea(RDI, X.memRip(start, 0)); (* main, the first argument *)
2273- X.callM(X.memRip(Chunk.externChunk(internStr("__libc_start_main")), 0));
2274- X.ud2(); (* it never returns *)
2275- Chunk.endChunk(entry);
2276- Chunk.beginChunk(start);
2277- X.push(RBP); (* aligns the stack again *)
2278- X.store(X.memRip(argcChunk, 0), RDI, 8);
2279- X.store(X.memRip(argvChunk, 0), RSI, 8);
2280- X.load(RAX, X.memRip(Chunk.externChunk(internStr("exit")), 0), 8, false);
2281- X.store(X.memRip(cExit, 0), RAX, 8);
2282- else
2283- start := entry;
2284- Chunk.beginChunk(entry);
2285- X.load(RAX, X.mem(RSP, 0), 8, false);
2286- X.store(X.memRip(argcChunk, 0), RAX, 8);
2287- X.lea(RAX, X.mem(RSP, 8));
2288- X.store(X.memRip(argvChunk, 0), RAX, 8);
2289- end;
2290- for i := 0 to numLinks - 1 do
2291- X.lea(RAX, X.memRip(links[i].chunk, 0));
2292- X.store(X.memRip(links[i].into, 0), RAX, 8);
2293- end;
2294- m := first;
2295- while m # nil do
2296- if m^.used and (m^.body >= 0) then X.callChunk(m^.body); end;
2297- m := m^.next;
2298- end;
2299- if mainObj # nil then X.callChunk(mainObj^.chunk); end;
2300- if (mainObj # nil) and (mainObj^.typ^.base # nil) then X.movRR(RDI, RAX); else X.movRI(RDI, 0); end;
2301- X.callChunk(exitProc);
2302- X.ud2(); (* exit never returns: trap if it does *)
2303- Chunk.endChunk(start);
2304- (* Rt.fail, for the failures of each kind: the place is where the
2305- check's call is. The return address is the next instruction's, which
2306- may belong to another line; one byte back is inside the call, so the
2307- lookup finds the call's line. rsp is aligned for the call, as the
2308- check's code may have pushed an odd number of quadwords. rdi and rsi
2309- as the failing code had them go on the stack, as Rt.fail's last two
2310- arguments, and a comes in rax (endFails). *)
2311- for i := 0 to LEN(failStubs) - 1 do
2312- if failStubs[i] >= 0 then
2313- Chunk.beginChunk(failStubs[i]);
2314- X.load(R8, X.mem(RSP, 0), 8, false);
2315- X.aluI(X.aluSub, R8, 1);
2316- X.aluI(X.aluAnd, RSP, -16);
2317- X.push(RSI);
2318- X.push(RDI);
2319- X.movRR(RSI, RAX);
2320- X.movRI(RDI, i);
2321- X.callChunk(rtFail);
2322- X.ud2();
2323- Chunk.endChunk(failStubs[i]);
2324- end;
2325- end;
2326- return entry;
2327-end;
2328-
2329-(* A code procedure: its instructions, read by the assembler (X64),
2330- are the whole of chunk c *)
2331-proc codeProc*(c: INT; constExpr: X.ConstFn): ERROR;
2332-begin
2333- Chunk.beginChunk(c);
2334- try X.assemble(constExpr);
2335- Chunk.endChunk(c);
2336- return nil;
2337-end;
2338-
2339-var i: INT;
2340-begin
2341- for i := 0 to LEN(failStubs) - 1 do failStubs[i] := -1; end;
2342- inPlace := -1;
2343- codeChunk := -1;
2344- resetStack(0, 0);
2345- rtFail := Chunk.newChunk(Chunk.secText, internStr("Rt"), internStr("fail"));
2346- argcChunk := Chunk.newChunk(Chunk.secBss, -1, internStr("argc"));
2347- Chunk.setBss(argcChunk, 8, 8);
2348- argvChunk := Chunk.newChunk(Chunk.secBss, -1, internStr("argv"));
2349- Chunk.setBss(argvChunk, 8, 8);
2350-end Gen.

self/Item.raz deleted +0 -1729

@@ -1,1729 +0,0 @@
1-(* Item: operands, their types, and what they mean.
2-
3- The parser describes each operand as an item, as in Wirth's
4- compilers: a constant, a variable at an address it can name, a value
5- on Gen's stack, a procedure, a string. The routines here check the
6- items' types, fold constants, and have Gen make the code, as calls of
7- its stack machine; nothing here knows the machine.
8-
9- Depends on: Scan for errors, Sym for types, Chunk for data, Gen for
10- code.
11- Leaves out: the language's syntax, which is Parse; the machine, which
12- is Gen.
13-
14- An error the seed's `Mark` ended in a jump back to the parser's
15- recovery point. Here the routine that finds it shows it and returns
16- `Scan.Failed`, and every routine that calls one passes it up with
17- `try`, to where the parser reads on: what has been made by then is
18- what the seed had made when it jumped. So most routines here return an
19- ERROR, as the last of their results.
20-
21- The seed's `Mismatch` of two operands is `mismatchOps` (raz has no
22- overloading), and what the parser sets, `demoted` and `checks`, has a
23- setter each, as an exported variable is read-only outside its module.
24- The seed's `TItem` is `Item` and `TMode` is `Mode`; its procedures begin
25- in lower case. *)
26-module Item;
27-import Fmt, Diag, Scan, Sym, Chunk, Gen;
28-
29-type
30- Mode* = (mConst, mVar, mStack, mProc, mType, mStr, mBuiltin, mCase, mNone, mCond,
31- mWords); (* two results of a call, on the stack, the first under the second *)
32-
33- Item* = record
34- mode*: Mode;
35- typ*: ^Sym.Type;
36- rel*: Scan.Sym; (* mCond: the comparison of the two integers on
37- the stack, not yet made, as Wirth's compilers
38- keep a condition *)
39- relSigned*: BOOL;
40- fj*, tj*: INT; (* mCond: the chains of jumps already made that are
41- taken when the whole condition is false, and when
42- it is true, not yet given a place (and, or and
43- not make them); see Gen's jumpOut *)
44- val*: I64; (* mConst: the value, an F64's bits; mStr: its length *)
45- base*: Gen.Base; (* mVar: what the address is relative to *)
46- chunk*: INT; (* mVar with bGlobal, mStr: the chunk; bSlot: the slot *)
47- off*: I64; (* mVar: added to the base *)
48- vol*: BOOL; (* mVar: reached through ^VOLATILE *)
49- isVar*: BOOL; (* mVar: a variable of the program, not a temporary *)
50- odd*: BOOL; (* mVar: in a packed record, so maybe misaligned *)
51- ro*: BOOL; (* mVar: another module's exported variable, or part
52- of one, which only that module changes *)
53- deref*: BOOL; (* mVar: at an address from a pointer, which may be
54- nil and isn't tested yet (nilTest) *)
55- obj*: ^Sym.Obj; (* mProc, mBuiltin, mCase; mVar: the variable named *)
56- pos*: Diag.Pos; (* where it is in the source, for messages *)
57- end;
58-
59-const
60- (* the comparison that holds when the one at the same place doesn't, for integers *)
61- NegatedOps: [6]Scan.Sym = [Scan.sNeq, Scan.sEql, Scan.sGeq, Scan.sGtr, Scan.sLeq, Scan.sLss];
62-
63-const
64- MaxI64 = 9223372036854775807;
65- MinI64 = -9223372036854775807 - 1;
66-
67-var
68- demoted*: BOOL; (* address wanted a register variable's address: its
69- procedure is compiled again, the variable in memory *)
70- checks*: BOOL; (* the module's index and slice checks are made: it
71- doesn't say check off *)
72- result: ^Sym.Type; (* the result of the procedure being compiled, or nil *)
73- passing: ^Sym.Obj; (* the parameter the argument at passingAt goes to *)
74- passingAt: Diag.Pos;
75-
76-proc setDemoted*(yes: BOOL);
77-begin
78- demoted := yes;
79-end;
80-
81-proc setChecks*(yes: BOOL);
82-begin
83- checks := yes;
84-end;
85-
86-(* The comparison that holds when op doesn't *)
87-proc negated(op: Scan.Sym): Scan.Sym;
88-begin
89- return NegatedOps[INT(op) - INT(Scan.sEql)];
90-end;
91-
92-proc isRel(op: Scan.Sym): BOOL;
93-begin
94- return (op >= Scan.sEql) and (op <= Scan.sGeq);
95-end;
96-
97-(* Whether op is one of the list: Scan.Sym has too many names for a set *)
98-proc oneOf(op: Scan.Sym; list: []Scan.Sym): BOOL;
99-var i: INT;
100-begin
101- for i := 0 to LEN(list) - 1 do
102- if list[i] = op then return true; end;
103- end;
104- return false;
105-end;
106-
107-proc bit(f: BOOL): I64;
108-begin
109- if f then return 1; end;
110- return 0;
111-end;
112-
113-(* A message, from a format and the strings that fill it *)
114-proc say1(f, a: []U8): []U8;
115-begin
116- return Diag.say(f, [Fmt.str(a)]);
117-end;
118-
119-proc say2(f, a, b: []U8): []U8;
120-begin
121- return Diag.say(f, [Fmt.str(a), Fmt.str(b)]);
122-end;
123-
124-(* Items *)
125-
126-proc makeConst*(var x: Item; t: ^Sym.Type; v: I64);
127-var p: Diag.Pos;
128-begin
129- p := x.pos;
130- x := {};
131- x.pos := p;
132- x.mode := mConst;
133- x.typ := t;
134- x.val := v;
135-end;
136-
137-(* A real constant: untyped, unless typed later. Its value is an F64,
138- which for an F32 is one an F32 can hold. *)
139-proc makeReal*(var x: Item; r: F64);
140-var p: ^F64;
141-begin
142- makeConst(x, Sym.tRConst, 0);
143- p := ^F64(ADR(x.val));
144- p^ := r;
145-end;
146-
147-proc isF32(t: ^Sym.Type): BOOL;
148-begin
149- return (t^.form = Sym.fReal) and (t^.size = 4);
150-end;
151-
152-proc realOf*(x: Item): F64;
153-var v: I64; p: ^F64;
154-begin
155- v := x.val;
156- p := ^F64(ADR(v));
157- return p^;
158-end;
159-
160-(* Gives a real constant the real type t, rounded to it. *)
161-proc realTo(var x: Item; t: ^Sym.Type);
162-var r: F64;
163-begin
164- r := realOf(x);
165- if isF32(t) then makeReal(x, F64(F32(r))); else makeReal(x, r); end;
166- x.typ := t;
167-end;
168-
169-(* The current string literal, as an item of its own chunk. *)
170-proc makeStr*(var x: Item);
171-begin
172- x := {};
173- x.mode := mStr;
174- x.typ := Sym.tStr;
175- x.val := Scan.slen;
176- x.chunk := Chunk.newChunk(Chunk.secRodata, -1, -1);
177- Chunk.setData(x.chunk, Scan.strWithZero(), Scan.slen + 1, 1);
178-end;
179-
180-proc frameAdr*(off: I64): Gen.Adr;
181-var a: Gen.Adr;
182-begin
183- a.base := Gen.bFrame;
184- a.chunk := -1;
185- a.off := off;
186- a.hi := 0;
187- return a;
188-end;
189-
190-proc globalAdr*(c: INT): Gen.Adr;
191-var a: Gen.Adr;
192-begin
193- a.base := Gen.bGlobal;
194- a.chunk := c;
195- a.off := 0;
196- a.hi := 0;
197- return a;
198-end;
199-
200-(* Where the variable x is, for Gen; a slice in registers has two *)
201-proc adrOf*(x: Item): Gen.Adr;
202-var a: Gen.Adr;
203-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;
210-end;
211-
212-(* An item for "found ...": a constant without a type of its own as it
213- is written, so that "found 1.5" says what is wrong; else its type. *)
214-proc what*(x: Item): []U8;
215-begin
216- if (x.mode = mConst) and ((x.typ = Sym.tConst) or (x.typ = Sym.tRConst)) then
217- return Diag.source(x.pos);
218- end;
219- return Sym.typeName(x.typ);
220-end;
221-
222-(* Two operands of different types. Numbers convert, so say how. *)
223-proc mismatchOps(x, y: Item; xt, yt: ^Sym.Type): ERROR;
224-var text: []U8;
225-begin
226- text := say2("{} and {} are different types", Sym.typeName(xt), Sym.typeName(yt));
227- if (Sym.isInt(xt) or (xt^.form = Sym.fReal)) and (Sym.isInt(yt) or (yt^.form = Sym.fReal))
228- and (xt # Sym.tConst) and (xt # Sym.tRConst) then
229- return Scan.markHelp(Diag.join(x.pos, y.pos), text,
230- say2("convert one to the other's type, as in {}({})", Sym.typeName(xt), Diag.source(y.pos)));
231- end;
232- return Scan.markAt(Diag.join(x.pos, y.pos), text);
233-end;
234-
235-(* An item that is not a value, by what it is. *)
236-proc notValue(x: Item): ERROR;
237-begin
238- match x.mode of
239- | mType: return Scan.markAt(x.pos, say1("{} is a type, not a value", Sym.typeName(x.typ)));
240- | mBuiltin: return Scan.markAt(x.pos, say1("{} is a built-in procedure, not a value", Scan.nameOf(x.obj^.name)));
241- | mCase: return Scan.markAt(x.pos, say1("{} is a case, not a value", Scan.nameOf(x.obj^.name)));
242- | mNone:
243- if x.obj # nil then return Scan.markAt(x.pos, say1("{} returns nothing", Scan.nameOf(x.obj^.name))); end;
244- return Scan.markAt(x.pos, "the procedure returns nothing");
245- | else: return Scan.markAt(x.pos, "a string can't be an operand");
246- end;
247-end;
248-
249-proc makeItem*(var x: Item; o: ^Sym.Obj): ERROR;
250-begin
251- x := {};
252- x.typ := o^.typ;
253- x.obj := o;
254- match o^.cls of
255- | oConst:
256- if o^.typ = Sym.tStr then
257- x.mode := mStr; x.val := o^.val; x.chunk := o^.chunk;
258- elsif o^.typ^.form in {Sym.fArray, Sym.fRecord} then
259- (* an array or record constant: a variable in read-only data, not one of
260- the program's, so nothing can change it *)
261- x.mode := mVar; x.base := Gen.bGlobal; x.chunk := o^.chunk;
262- else
263- x.mode := mConst; x.val := o^.val;
264- end;
265- | oVar:
266- x.mode := mVar;
267- x.ro := (o^.lev = 0) and (o^.home # Sym.curModule);
268- x.isVar := not x.ro;
269- if o^.ext then
270- Gen.pushVar(globalAdr(o^.chunk), 8, false, Gen.kWord);
271- x.base := Gen.bStack;
272- elsif o^.lev = 0 then
273- x.base := Gen.bGlobal; x.chunk := o^.chunk;
274- elsif o^.ind then
275- x.base := Gen.bSlot; x.chunk := INT(o^.val); x.off := o^.off;
276- elsif o^.reg # 0 then
277- x.base := Gen.bReg; x.chunk := o^.reg;
278- else
279- x.base := Gen.bFrame; x.off := o^.val;
280- end;
281- | oProc: x.mode := mProc;
282- | oType: x.mode := mType;
283- | oBuiltin: x.mode := mBuiltin;
284- | oCase: x.mode := mCase;
285- | else: return Scan.mark(say1("{} is not a value", Scan.nameOf(o^.name)));
286- end;
287- return nil;
288-end;
289-
290-proc scalarSize*(t: ^Sym.Type): INT;
291-begin
292- if t^.form in {Sym.fInt, Sym.fBool, Sym.fEnum, Sym.fSet, Sym.fReal} then return INT(t^.size); end;
293- return 8;
294-end;
295-
296-(* The width an operation on t is brought back to, and whether signed *)
297-proc intSize(t: ^Sym.Type): INT;
298-begin
299- if t^.form = Sym.fInt then return INT(t^.size); end;
300- return 8;
301-end;
302-
303-proc signed(t: ^Sym.Type): BOOL;
304-begin
305- return ((t^.form = Sym.fInt) and t^.signed) or (t^.form = Sym.fConst);
306-end;
307-
308-proc cut(v: I64; t: ^Sym.Type): I64;
309-begin
310- if t^.form # Sym.fInt then return v; end;
311- match t^.size of
312- | 1: if t^.signed then return I64(I8(v)); end; return I64(U8(v));
313- | 2: if t^.signed then return I64(I16(v)); end; return I64(U16(v));
314- | 4: if t^.signed then return I64(I32(v)); end; return I64(U32(v));
315- | else: return v;
316- end;
317-end;
318-
319-(* Code computing with a real is noted on its chunk, at the first place,
320- for a target without reals (report 5.1) to refuse if the chunk turns
321- out to be used. A real moved whole, as a record's bytes are copied,
322- needs nothing the target lacks, and isn't noted. *)
323-proc usesReals*(p: Diag.Pos);
324-begin
325- if (Gen.codeChunk >= 0) and not Chunk.chunks[Gen.codeChunk].reals then
326- Chunk.setReals(Gen.codeChunk, p);
327- end;
328-end;
329-
330-(* x, at an address from a pointer, is about to be used: Gen tests the
331- address for nil where the machine wouldn't stop at it (report section
332- 10), from its offset to its end. *)
333-proc nilTest*(var x: Item);
334-begin
335- if (x.mode = mVar) and x.deref then Gen.checkNil(x.off + x.typ^.size, x.pos); end;
336- x.deref := false;
337-end;
338-
339-(* x's value, on top of the stack *)
340-proc value*(var x: Item): ERROR;
341-var f: F32; p: ^U32;
342-begin
343- if x.mode = mCond then
344- if (x.fj = Gen.NoLabel) and (x.tj = Gen.NoLabel) then Gen.compare(x.rel, Gen.kWord, x.relSigned);
345- else Gen.condValue(negated(x.rel), x.relSigned, x.fj, x.tj); end;
346- x.mode := mStack;
347- return nil;
348- end;
349- if x.typ^.form = Sym.fReal then usesReals(x.pos); end;
350- nilTest(x);
351- match x.mode of
352- | mConst:
353- if (x.typ^.form = Sym.fError) and (x.val > 0) then Gen.pushAdr(globalAdr(INT(x.val) - 1));
354- elsif isF32(x.typ) then
355- f := F32(realOf(x));
356- p := ^U32(ADR(f));
357- Gen.pushConst(Gen.kF32, I64(p^));
358- else Gen.pushConst(Gen.kindOf(x.typ), x.val); end;
359- | mVar:
360- if not Sym.isScalar(x.typ) then
361- return Scan.markAt(x.pos, say1("expected a single value, found {}", what(x)));
362- end;
363- Gen.pushVar(adrOf(x), scalarSize(x.typ), (x.typ^.form = Sym.fInt) and x.typ^.signed, Gen.kindOf(x.typ));
364- | mStack: x.mode := mStack;
365- | mProc:
366- if x.obj^.isCode and (x.obj^.typ^.base # nil) and x.obj^.typ^.base^.tuple then
367- return Scan.markAt(x.pos, "a code procedure with two results can only be called");
368- end;
369- Gen.pushProc(x.obj^.chunk, x.obj^.ext);
370- | else: return notValue(x);
371- end;
372- x.mode := mStack;
373- return nil;
374-end;
375-
376-(* The address of the variable or string x, on top of the stack *)
377-proc address*(var x: Item): ERROR;
378-begin
379- nilTest(x);
380- if (x.mode = mVar) and (x.base = Gen.bReg) then
381- (* its address is wanted after all: the procedure is compiled again
382- with the variable in memory; till then, this code is thrown away *)
383- x.obj^.reg := 0;
384- x.obj^.reg2 := 0;
385- demoted := true;
386- x.base := Gen.bFrame;
387- x.off := x.obj^.val;
388- end;
389- if x.mode = mStr then Gen.pushAdr(globalAdr(x.chunk));
390- elsif x.mode = mVar then
391- Gen.pushAdr(adrOf(x));
392- x.base := Gen.bStack; x.off := 0;
393- else return Scan.markAt(x.pos, "expected a variable"); end;
394- return nil;
395-end;
396-
397-(* x isn't wanted: what it has on the stack is dropped *)
398-proc discard*(x: Item): ERROR;
399-var y: Item;
400-begin
401- if x.mode = mCond then
402- y := x;
403- try value(y);
404- Gen.drop();
405- return nil;
406- end;
407- if (x.mode = mStack) or ((x.mode = mVar) and (x.base = Gen.bStack)) then Gen.drop(); end;
408- if x.mode = mWords then Gen.drop(); Gen.drop(); end;
409- return nil;
410-end;
411-
412-(* Frames *)
413-
414-proc tempItem*(var x: Item; t: ^Sym.Type; off: I64);
415-var p: Diag.Pos;
416-begin
417- p := x.pos;
418- x := {};
419- x.pos := p;
420- x.mode := mVar; x.typ := t; x.base := Gen.bFrame; x.off := off;
421-end;
422-
423-proc toSlot*(var x: Item): (I64, ERROR);
424-var s: I64;
425-begin
426- try value(x);
427- s := Gen.allocTemp(8, 8);
428- Gen.popVar(frameAdr(s), 8);
429- return s, nil;
430-end;
431-
432-(* Copying *)
433-
434-(* x, copied to a temporary *)
435-proc copyToTemp*(var x: Item): ERROR;
436-var t: I64; f, g: ^Sym.Obj; a: Gen.Adr;
437-begin
438- if x.vol then return Scan.markAt(x.pos, "can't copy through a volatile pointer"); end;
439- t := Gen.allocTemp(x.typ^.size, x.typ^.align);
440- if (x.mode = mVar) and (x.base = Gen.bReg) then
441- (* a slice in registers, which has no address: its words stored *)
442- a := adrOf(x);
443- Gen.pushVar(a, 8, false, Gen.kWord);
444- Gen.popVar(frameAdr(t), 8);
445- a.off := 8;
446- Gen.pushVar(a, 8, false, Gen.kWord);
447- Gen.popVar(frameAdr(t + 8), 8);
448- tempItem(x, x.typ, t);
449- return nil;
450- end;
451- if x.mode = mWords then
452- (* the second result is on top, so it is popped first *)
453- f := x.typ^.fields; g := f^.next;
454- Gen.popVar(frameAdr(t + g^.val), scalarSize(g^.typ));
455- Gen.popVar(frameAdr(t + f^.val), scalarSize(f^.typ));
456- tempItem(x, x.typ, t);
457- return nil;
458- end;
459- try address(x);
460- Gen.copyTo(frameAdr(t), x.typ^.size);
461- tempItem(x, x.typ, t);
462- return nil;
463-end;
464-
465-(* A slice made from an address on the stack and a length. *)
466-proc sliceOf*(var x: Item; t: ^Sym.Type; len: I64);
467-var s: I64;
468-begin
469- s := Gen.allocTemp(16, 8);
470- Gen.popVar(frameAdr(s), 8);
471- Gen.pushConst(Gen.kWord, len);
472- Gen.popVar(frameAdr(s + 8), 8);
473- tempItem(x, t, s);
474-end;
475-
476-(* An INT goes silently into an I64, and a UINT into a U64, losing
477- nothing on any target (report section 5.10). *)
478-proc widens(s, t: ^Sym.Type): BOOL;
479-begin
480- return ((s = Sym.tInt) and Sym.same(t, Sym.tI64)) or ((s = Sym.tUInt) and Sym.same(t, Sym.tU64));
481-end;
482-
483-(* Another module's exported variable can be read, not changed, nor
484- handed to anything that could change it (report section 3). *)
485-proc notReadOnly*(x: Item): ERROR;
486-begin
487- if x.ro then
488- return Scan.markAt(x.pos, Diag.say("{} is {}'s, and can't be changed outside it",
489- [Fmt.str(Diag.source(x.pos)), Fmt.str(Scan.nameOf(x.obj^.home^.name))]));
490- end;
491- return nil;
492-end;
493-
494-(* An error in x's type; if x is an argument, a note at the parameter
495- it goes to. *)
496-proc mismatch(x: Item; text: []U8): ERROR;
497-begin
498- Diag.error(x.pos, text);
499- if (passing # nil) and (x.pos.f = passingAt.f) and (x.pos.a = passingAt.a) and (x.pos.b = passingAt.b) then
500- Diag.note(passing^.pos, say1("it goes to {}, declared here", Scan.nameOf(passing^.name)));
501- end;
502- return Scan.Failed;
503-end;
504-
505-proc coerce*(var x: Item; t: ^Sym.Type): ERROR;
506-var s: ^Sym.Type; tmp: I64;
507-begin
508- if x.mode = mCond then try value(x); end;
509- s := x.typ;
510- if x.mode = mStr then
511- if (t^.form = Sym.fSlice) and (t^.base = Sym.tU8) then
512- try address(x); sliceOf(x, t, x.val);
513- elsif (t^.form = Sym.fPtr) and (t^.base = Sym.tU8) then
514- try address(x); x.mode := mStack; x.typ := t;
515- elsif (t^.form = Sym.fArray) and (t^.base = Sym.tU8) and (t^.len >= x.val) then
516- tmp := Gen.allocTemp(t^.size, 1);
517- try address(x);
518- Gen.copyTo(frameAdr(tmp), x.val);
519- if t^.len > x.val then Gen.zeroVar(frameAdr(tmp + x.val), t^.len - x.val); end;
520- tempItem(x, t, tmp);
521- else return mismatch(x, say1("can't use a string as {}", Sym.typeName(t))); end;
522- return nil;
523- end;
524- if x.mode in {mType, mBuiltin, mNone, mCase} then return notValue(x); end;
525- if Sym.same(s, t) then return nil; end;
526- if widens(s, t) then x.typ := t; (* the same bits, on a 64-bit target *)
527- elsif (s = Sym.tRConst) and (t^.form = Sym.fReal) then realTo(x, t);
528- elsif (s^.form = Sym.fConst) and (t^.form = Sym.fInt) then
529- if (x.mode = mConst) and not Sym.fits(x.val, t) then
530- return Scan.markAt(x.pos, Diag.say("{} doesn't fit {}", [Fmt.int(x.val), Fmt.str(Sym.typeName(t))]));
531- end;
532- x.typ := t;
533- elsif (s^.form = Sym.fNil) and (t^.form in {Sym.fPtr, Sym.fProc, Sym.fError}) then
534- x.typ := t;
535- elsif (s^.form = Sym.fPtr) and (t^.form = Sym.fPtr) and t^.vol and not s^.vol
536- and Sym.same(s^.base, t^.base) then
537- x.typ := t;
538- elsif (s^.form = Sym.fArray) and (t^.form = Sym.fSlice) and Sym.same(s^.base, t^.base) then
539- try notReadOnly(x);
540- if x.vol then return Scan.markAt(x.pos, "can't make a slice through a volatile pointer"); end;
541- if x.odd then return Scan.markAt(x.pos, "can't make a slice of a field of a packed record"); end;
542- try address(x);
543- sliceOf(x, t, s^.len);
544- elsif (x.mode = mProc) and (t^.form # Sym.fProc) and (s^.base = nil) then
545- return Scan.markAt(x.pos, say1("{} is a procedure, and returns nothing", Diag.source(x.pos)));
546- elsif (x.mode = mProc) and (t^.form # Sym.fProc) then
547- return Scan.markHelp(x.pos,
548- say2("can't use {} as {}", Sym.typeName(s), Sym.typeName(t)),
549- say1("to call it, write {}()", Diag.source(x.pos)));
550- else
551- return mismatch(x, say2("can't use {} as {}", Sym.typeName(s), Sym.typeName(t)));
552- end;
553- return nil;
554-end;
555-
556-(* coerce where the types must be the same, as in a for loop, INC and
557- several results, which don't widen an INT to an I64 (report sections
558- 5.10, 6.1 and 7.2); help, if not empty, says why. *)
559-proc coerceExact*(var x: Item; t: ^Sym.Type; help: []U8): ERROR;
560-var h: []U8;
561-begin
562- if widens(x.typ, t) then
563- h := help;
564- if LEN(h) = 0 then
565- h := say2("they don't mix here: write {}({})", Sym.typeName(t), Diag.source(x.pos));
566- end;
567- return Scan.markHelp(x.pos, say2("expected {}, found {}", Sym.typeName(t), what(x)), h);
568- end;
569- return coerce(x, t);
570-end;
571-
572-(* dst := src. The address of dst, if it has to be computed, is on the
573- stack already, under src's. *)
574-proc assign*(var dst, src: Item): ERROR;
575-begin
576- try coerce(src, dst.typ);
577- if Sym.isScalar(dst.typ) then
578- try value(src);
579- Gen.popVar(adrOf(dst), scalarSize(dst.typ));
580- else
581- if dst.vol or src.vol then return Scan.markAt(src.pos, "can't copy through a volatile pointer"); end;
582- if (src.mode = mVar) and (src.base = Gen.bReg) then try copyToTemp(src); end; (* a slice in registers *)
583- try address(src);
584- if dst.base = Gen.bStack then Gen.copyBlock(dst.typ^.size, dst.off);
585- else Gen.copyTo(adrOf(dst), dst.typ^.size); end;
586- end;
587- return nil;
588-end;
589-
590-(* t's name, ending in a zero byte, for Rt.fail *)
591-proc nameChunk(t: ^Sym.Type): INT;
592-var s: []U8; p: ^U8; n, c: INT;
593-begin
594- s := Sym.typeName(t);
595- n := LEN(s);
596- p := Scan.grab(n + 1);
597- COPY(p[0..n], s);
598- p[n] := 0;
599- c := Chunk.newChunk(Chunk.secRodata, -1, -1);
600- Chunk.setData(c, p, n + 1, 1);
601- return c;
602-end;
603-
604-(* Selectors *)
605-
606-proc deref*(var x: Item): ERROR;
607-var t: ^Sym.Type;
608-begin
609- t := x.typ;
610- if t^.form # Sym.fPtr then
611- return Scan.markAt(x.pos, say1("expected a pointer, found {}", Sym.typeName(t)));
612- end;
613- if t^.base = nil then
614- return Scan.markAt(x.pos, say1("{} points to a type never declared", Sym.typeName(t)));
615- end;
616- try value(x);
617- x.mode := mVar; x.base := Gen.bStack; x.off := 0; x.deref := true;
618- x.typ := t^.base; x.vol := t^.vol; x.isVar := true; x.odd := false; x.ro := false;
619- return nil;
620-end;
621-
622-(* A field of a packed record, of more than one byte's alignment, may
623- sit anywhere; it is read and written, but has no address and no
624- volatile access, which a machine that can't reach a misaligned word
625- couldn't make one access (report section 5.5). *)
626-proc field*(var x: Item; f: ^Sym.Obj): ERROR;
627-begin
628- if x.typ^.packd and (f^.typ^.align > 1) then
629- if x.vol then return Scan.markAt(x.pos, "a field of a packed record can't be volatile"); end;
630- x.odd := true;
631- end;
632- x.off := x.off + f^.val;
633- x.typ := f^.typ;
634- return nil;
635-end;
636-
637-proc indexPrep*(var x: Item): ERROR;
638-begin
639- nilTest(x);
640- if x.mode = mStr then try coerce(x, Sym.tBytes); end;
641- if (x.typ^.form = Sym.fPtr) and (x.typ^.base^.form = Sym.fArray) then
642- return Scan.markAt(x.pos, "a pointer to an array is indexed as p^[i]");
643- end;
644- if x.typ^.form = Sym.fPtr then try value(x);
645- elsif not ((x.mode = mVar) and (x.typ^.form in {Sym.fArray, Sym.fSlice})) then
646- return Scan.markAt(x.pos, say1("expected an array, a slice or a pointer, found {}", what(x)));
647- end;
648- return nil;
649-end;
650-
651-(* The index on top, times the size of an element *)
652-proc scaleBy(s: I64);
653-begin
654- if s # 1 then
655- Gen.pushConst(Gen.kWord, s);
656- Gen.op(Scan.sTimes, Gen.kWord, 8, true);
657- end;
658-end;
659-
660-proc index*(var x, y: Item): ERROR;
661-var t: ^Sym.Type; s: I64;
662-begin
663- t := x.typ;
664- s := t^.base^.size;
665- if not Sym.isInt(y.typ) then
666- return Scan.markAt(y.pos, say1("an index is an integer, found {}", what(y)));
667- end;
668- if t^.form = Sym.fPtr then
669- try value(y);
670- scaleBy(s);
671- Gen.op(Scan.sPlus, Gen.kWord, 8, false);
672- x.mode := mVar; x.base := Gen.bStack; x.off := 0;
673- x.vol := t^.vol; x.isVar := true; x.odd := false; x.ro := false;
674- elsif (t^.form = Sym.fArray) and (y.mode = mConst) then
675- if (y.val < 0) or (y.val >= t^.len) then
676- return Scan.markAt(y.pos, Diag.say("index {} is out of range for a length of {}", [Fmt.int(y.val), Fmt.int(t^.len)]));
677- end;
678- x.off := x.off + y.val * s;
679- elsif t^.form = Sym.fArray then
680- try value(y);
681- if checks then Gen.checkIndex(t^.len, y.pos); end;
682- if x.base = Gen.bStack then scaleBy(s); Gen.op(Scan.sPlus, Gen.kWord, 8, false);
683- else Gen.indexArray(adrOf(x), s); x.off := 0; end;
684- x.base := Gen.bStack;
685- else
686- try value(y);
687- Gen.indexSlice(adrOf(x), s, checks, y.pos);
688- x.base := Gen.bStack; x.off := 0; x.isVar := true; x.vol := false; x.ro := false;
689- end;
690- x.typ := t^.base;
691- return nil;
692-end;
693-
694-proc sliceLo*(var lo: Item): ERROR;
695-begin
696- if not Sym.isInt(lo.typ) then
697- return Scan.markAt(lo.pos, say1("an index is an integer, found {}", what(lo)));
698- end;
699- return value(lo);
700-end;
701-
702-proc slice*(var x, lo, hi: Item): ERROR;
703-var t, st: ^Sym.Type; tmp: I64;
704-begin
705- t := x.typ;
706- if not Sym.isInt(hi.typ) then
707- return Scan.markAt(hi.pos, say1("an index is an integer, found {}", what(hi)));
708- end;
709- if x.vol then return Scan.markAt(x.pos, "can't make a slice through a volatile pointer"); end;
710- if x.odd then return Scan.markAt(x.pos, "can't make a slice of a field of a packed record"); end;
711- if t^.form = Sym.fArray then try notReadOnly(x); end;
712- try value(hi);
713- tmp := Gen.allocTemp(16, 8);
714- if t^.form = Sym.fPtr then Gen.slicePtr(t^.base^.size, tmp, checks, lo.pos);
715- else Gen.slice(adrOf(x), t^.form = Sym.fArray, t^.len, t^.base^.size, tmp, checks, lo.pos); end;
716- st := Sym.newType(Sym.fSlice, 16, 8);
717- st^.base := t^.base;
718- tempItem(x, st, tmp);
719- return nil;
720-end;
721-
722-(* Operators *)
723-
724-proc neg*(var x: Item): ERROR;
725-begin
726- if x.typ^.form = Sym.fReal then
727- if x.mode = mConst then x.val := x.val xor MinI64;
728- else try value(x); Gen.neg(Gen.kindOf(x.typ), 8, false); end;
729- elsif Sym.isInt(x.typ) then
730- if (x.mode = mConst) and (x.typ^.form = Sym.fConst) and (x.val = MinI64) then
731- return Scan.markAt(x.pos, "the constant is too big for I64");
732- elsif x.mode = mConst then x.val := cut(-x.val, x.typ);
733- else try value(x); Gen.neg(Gen.kWord, intSize(x.typ), signed(x.typ)); end;
734- else return Scan.markAt(x.pos, say1("can't negate {}", Sym.typeName(x.typ))); end;
735- return nil;
736-end;
737-
738-proc notOp*(var x: Item): ERROR;
739-var L: INT;
740-begin
741- if Sym.isInt(x.typ) then
742- return Scan.markHelp(x.pos, say1("\"not\" needs a BOOL, found {}", what(x)), "the bits of an integer flip with ~");
743- end;
744- if x.typ^.form # Sym.fBool then
745- return Scan.markAt(x.pos, say1("\"not\" needs a BOOL, found {}", what(x)));
746- end;
747- if x.mode = mConst then x.val := 1 - x.val;
748- elsif x.mode = mCond then
749- x.rel := negated(x.rel);
750- L := x.fj; x.fj := x.tj; x.tj := L;
751- else try value(x); Gen.notBool(); end;
752- return nil;
753-end;
754-
755-proc complement*(var x: Item): ERROR;
756-begin
757- if x.typ^.form = Sym.fBool then
758- return Scan.markHelp(x.pos, say1("\"~\" needs an integer, found {}", what(x)), "a BOOL is negated with not");
759- end;
760- if not Sym.isInt(x.typ) then
761- return Scan.markAt(x.pos, say1("\"~\" needs an integer, found {}", what(x)));
762- end;
763- if x.mode = mConst then x.val := cut(~x.val, x.typ);
764- else try value(x); Gen.complement(intSize(x.typ), signed(x.typ)); end;
765- return nil;
766-end;
767-
768-(* Arrays, slices and strings, which = and # compare element by element *)
769-proc isSeq(t: ^Sym.Type): BOOL;
770-begin
771- return t^.form in {Sym.fStr, Sym.fArray, Sym.fSlice};
772-end;
773-
774-proc elemOf(t: ^Sym.Type): ^Sym.Type;
775-begin
776- if t^.form = Sym.fStr then return Sym.tU8; end;
777- return t^.base;
778-end;
779-
780-(* An array, slice or string as a slice in a temporary, for comparing. *)
781-proc seqSlice(var x: Item): ERROR;
782-var t: ^Sym.Type;
783-begin
784- t := Sym.newType(Sym.fSlice, 16, 8);
785- t^.base := elemOf(x.typ);
786- if x.typ^.form = Sym.fSlice then
787- x.typ := t; try copyToTemp(x);
788- elsif x.mode = mStr then
789- try address(x); sliceOf(x, t, x.val);
790- else
791- if x.vol then return Scan.markAt(x.pos, "can't compare through a volatile pointer"); end;
792- try address(x); sliceOf(x, t, x.typ^.len);
793- end;
794- return nil;
795-end;
796-
797-(* x, a BOOL, as a condition: a value compared with 0 if it isn't one *)
798-proc makeCond(var x: Item): ERROR;
799-begin
800- if x.mode = mCond then return nil; end;
801- try value(x);
802- Gen.pushConst(Gen.kWord, 0);
803- x.mode := mCond;
804- x.rel := Scan.sNeq;
805- x.relSigned := false;
806- x.fj := Gen.NoLabel;
807- x.tj := Gen.NoLabel;
808- return nil;
809-end;
810-
811-proc op1*(op: Scan.Sym; var x: Item; var L: INT): ERROR;
812-begin
813- L := Gen.NoLabel;
814- if ((op = Scan.sAnd) or (op = Scan.sOr)) and (x.typ^.form = Sym.fBool) then
815- if x.mode = mConst then return nil; end; (* folded by op2 *)
816- try makeCond(x);
817- if op = Scan.sAnd then
818- Gen.jumpOut(negated(x.rel), x.relSigned, x.fj);
819- Gen.fix(x.tj);
820- x.tj := Gen.NoLabel;
821- else
822- Gen.jumpOut(x.rel, x.relSigned, x.tj);
823- Gen.fix(x.fj);
824- x.fj := Gen.NoLabel;
825- end;
826- elsif ((op = Scan.sEql) or (op = Scan.sNeq)) and isSeq(x.typ) then
827- try seqSlice(x);
828- elsif (op = Scan.sPlus) and (x.mode = mStr) then
829- (* two string constants to be joined: nothing to compute *)
830- elsif (op = Scan.sPlus) and isSeq(x.typ) then
831- return Scan.markHelp(x.pos, say1("+ doesn't join {}", what(x)), "strings are joined in a Buf: Buf.str(b, s)");
832- elsif x.mode in {mType, mBuiltin, mNone, mCase, mStr} then
833- return notValue(x);
834- elsif x.mode # mConst then
835- try value(x);
836- end;
837- return nil;
838-end;
839-
840-proc log2(v: I64): INT;
841-var n: INT;
842-begin
843- n := 0;
844- while (v > 1) and ((v & 1) = 0) do v := v shr 1; INC(n); end;
845- if v # 1 then n := -1; end;
846- return n;
847-end;
848-
849-(* Whether a op b, for + - *, overflows an I64: an untyped constant
850- doesn't wrap, it is an error (report section 4). *)
851-proc overflows(op: Scan.Sym; a, b: I64): BOOL;
852-begin
853- match op of
854- | sPlus: return ((b > 0) and (a > MaxI64 - b)) or ((b < 0) and (a < MinI64 - b));
855- | sMinus: return ((b < 0) and (a > MaxI64 + b)) or ((b > 0) and (a < MinI64 + b));
856- | sTimes:
857- if (a = 0) or (b = 0) then return false; end;
858- if a = -1 then return b = MinI64; end;
859- if b = -1 then return a = MinI64; end;
860- return (a * b) div b # a;
861- | else: return false;
862- end;
863-end;
864-
865-(* A type's width in bits; an untyped constant's is an I64's *)
866-proc bits(t: ^Sym.Type): I64;
867-begin
868- return t^.size * 8;
869-end;
870-
871-proc foldInt(op: Scan.Sym; a, b: I64; t: ^Sym.Type; p: Diag.Pos): (I64, ERROR);
872-var u: BOOL;
873-begin
874- u := (t^.form = Sym.fInt) and not t^.signed;
875- if (t^.form = Sym.fConst) and overflows(op, a, b) then
876- return 0, Scan.markAt(p, "the constant is too big for I64");
877- end;
878- match op of
879- | sPlus: return a + b, nil;
880- | sMinus: return a - b, nil;
881- | sTimes: return a * b, nil;
882- | sDiv, sMod:
883- if b = 0 then return 0, Scan.markAt(p, "division by zero"); end;
884- if u then
885- if op = Scan.sDiv then return I64(U64(a) div U64(b)), nil; end;
886- return I64(U64(a) mod U64(b)), nil;
887- end;
888- if (b = -1) and (a = I64(-1) shl (bits(t) - 1)) then return 0, Scan.markAt(p, "division overflows"); end;
889- if op = Scan.sDiv then return a div b, nil; end;
890- return a mod b, nil;
891- | sAmp: return a & b, nil;
892- | sBar: return a | b, nil;
893- | sXor: return a xor b, nil;
894- | sShl: return a shl (b & (bits(t) - 1)), nil;
895- | sShr:
896- if u then return I64(U64(a) shr (b & (bits(t) - 1))), nil; end;
897- return a shr (b & (bits(t) - 1)), nil;
898- | sEql: return bit(a = b), nil;
899- | sNeq: return bit(a # b), nil;
900- | sLss:
901- if u then return bit(U64(a) < U64(b)), nil; end;
902- return bit(a < b), nil;
903- | sLeq:
904- if u then return bit(U64(a) <= U64(b)), nil; end;
905- return bit(a <= b), nil;
906- | sGtr:
907- if u then return bit(U64(a) > U64(b)), nil; end;
908- return bit(a > b), nil;
909- | sGeq:
910- if u then return bit(U64(a) >= U64(b)), nil; end;
911- return bit(a >= b), nil;
912- | else: return 0, Scan.markAt(p, "bad operator");
913- end;
914-end;
915-
916-(* Folds x op y, of the real type t: an F32 rounded at each step, as
917- the machine would. *)
918-proc foldReal(op: Scan.Sym; x, y: Item; t: ^Sym.Type; var r: Item): BOOL;
919-var a, b: F64; ok: BOOL;
920-begin
921- a := realOf(x); b := realOf(y);
922- ok := true;
923- match op of
924- | sPlus: makeReal(r, a + b);
925- | sMinus: makeReal(r, a - b);
926- | sTimes: makeReal(r, a * b);
927- | sSlash: makeReal(r, a / b);
928- | sEql: makeConst(r, Sym.tBool, bit(a = b));
929- | sNeq: makeConst(r, Sym.tBool, bit(a # b));
930- | sLss: makeConst(r, Sym.tBool, bit(a < b));
931- | sLeq: makeConst(r, Sym.tBool, bit(a <= b));
932- | sGtr: makeConst(r, Sym.tBool, bit(a > b));
933- | sGeq: makeConst(r, Sym.tBool, bit(a >= b));
934- | else: ok := false;
935- end;
936- if r.typ^.form = Sym.fReal then realTo(r, t); end;
937- return ok;
938-end;
939-
940-(* and, or and not are for BOOLs; &, |, xor and ~ for the bits of
941- integers: x is the wrong kind for op, and the message names the
942- operator it may have meant *)
943-proc wrongLogic(op: Scan.Sym; var x: Item): ERROR;
944-var bitsOf: []U8;
945-begin
946- bitsOf := "the bits of integers take ";
947- if (op = Scan.sAnd) and Sym.isInt(x.typ) then
948- return Scan.markHelp(x.pos, say1("\"and\" needs BOOLs, found {}", what(x)), say1("{}&", bitsOf));
949- elsif (op = Scan.sOr) and Sym.isInt(x.typ) then
950- return Scan.markHelp(x.pos, say1("\"or\" needs BOOLs, found {}", what(x)), say1("{}|", bitsOf));
951- elsif op = Scan.sAmp then
952- return Scan.markHelp(x.pos, say1("\"&\" needs integers, found {}", what(x)), "BOOLs take and");
953- elsif op = Scan.sBar then
954- return Scan.markHelp(x.pos, say1("\"|\" needs integers, found {}", what(x)), "BOOLs take or");
955- elsif op = Scan.sXor then
956- return Scan.markHelp(x.pos, say1("\"xor\" needs integers, found {}", what(x)), "BOOLs that differ are #");
957- end;
958- return Scan.markAt(x.pos, say2("{} needs BOOLs, found {}", Scan.symText(op), what(x)));
959-end;
960-
961-(* x + y, of two string constants: one string, in a chunk of its own
962- (report section 4) *)
963-proc joinStr(var x, y: Item): ERROR;
964-var p: ^U8; c, xs, ys, xl, yl: INT;
965-begin
966- if y.mode # mStr then
967- return Scan.markAt(y.pos, say1("\"+\" joins two strings, found {}", what(y)));
968- end;
969- xs := Chunk.chunks[x.chunk].start;
970- ys := Chunk.chunks[y.chunk].start;
971- xl := INT(x.val);
972- yl := INT(y.val);
973- p := Scan.grab(xl + yl + 1);
974- COPY(p[0..xl], Chunk.rodata[xs..xs + xl]);
975- COPY(p[xl..xl + yl + 1], Chunk.rodata[ys..ys + yl + 1]);
976- c := Chunk.newChunk(Chunk.secRodata, -1, -1);
977- Chunk.setData(c, p, xl + yl + 1, 1);
978- x.chunk := c;
979- x.val := x.val + y.val;
980- return nil;
981-end;
982-
983-(* A set's operations, as operations on its bits: the two values on top *)
984-proc setOp(op: Scan.Sym);
985-begin
986- match op of
987- | sPlus: Gen.op(Scan.sBar, Gen.kWord, 8, false);
988- | sTimes: Gen.op(Scan.sAmp, Gen.kWord, 8, false);
989- | sMinus: Gen.complement(8, false); Gen.op(Scan.sAmp, Gen.kWord, 8, false);
990- | sLeq, sGeq:
991- (* x <= y has no bit of x outside y *)
992- if op = Scan.sGeq then Gen.swap(); end;
993- Gen.complement(8, false);
994- Gen.op(Scan.sAmp, Gen.kWord, 8, false);
995- Gen.pushConst(Gen.kWord, 0);
996- Gen.compare(Scan.sEql, Gen.kWord, false);
997- | sIn:
998- Gen.swap();
999- Gen.op(Scan.sShr, Gen.kWord, 8, false);
1000- Gen.pushConst(Gen.kWord, 1);
1001- Gen.op(Scan.sAmp, Gen.kWord, 8, false);
1002- | else: Gen.compare(op, Gen.kWord, false);
1003- end;
1004-end;
1005-
1006-(* The operators the arithmetic of integers, of reals and of sets
1007- stand for, and the comparisons *)
1008-proc intOp(op: Scan.Sym): BOOL;
1009-begin
1010- return isRel(op) or oneOf(op, [Scan.sPlus, Scan.sMinus, Scan.sTimes, Scan.sDiv, Scan.sMod,
1011- Scan.sAmp, Scan.sBar, Scan.sXor, Scan.sShl, Scan.sShr]);
1012-end;
1013-
1014-proc doesntApply(op: Scan.Sym; x, y: Item; t: ^Sym.Type): ERROR;
1015-begin
1016- return Scan.markAt(Diag.join(x.pos, y.pos), say2("{} doesn't apply to {}", Scan.symText(op), Sym.typeName(t)));
1017-end;
1018-
1019-proc op2*(op: Scan.Sym; var x, y: Item; _L: INT): ERROR;
1020-var xt, yt, t, e: ^Sym.Type; r: Item; scale: INT; isPtr: BOOL; a, b, v: I64;
1021-begin
1022- xt := x.typ; yt := y.typ;
1023- if y.mode in {mType, mBuiltin, mNone, mCase} then return notValue(y); end;
1024- if (op = Scan.sPlus) and (x.mode = mStr) then return joinStr(x, y); end;
1025-
1026- if (op = Scan.sAnd) or (op = Scan.sOr) then
1027- if xt^.form # Sym.fBool then return wrongLogic(op, x); end;
1028- if yt^.form # Sym.fBool then return wrongLogic(op, y); end;
1029- if (x.mode = mConst) and (y.mode = mConst) then
1030- if op = Scan.sAnd then x.val := x.val & y.val; else x.val := x.val | y.val; end;
1031- elsif x.mode = mConst then
1032- (* true and y, false or y: y; else x, y computed and dropped *)
1033- if (x.val = 1) = (op = Scan.sAnd) then x := y;
1034- else try discard(y); end;
1035- else
1036- try makeCond(y);
1037- if op = Scan.sAnd then x.fj := Gen.joinJumps(x.fj, y.fj); x.tj := y.tj;
1038- else x.tj := Gen.joinJumps(x.tj, y.tj); x.fj := y.fj; end;
1039- x.rel := y.rel;
1040- x.relSigned := y.relSigned;
1041- end;
1042- return nil;
1043- end;
1044-
1045- if oneOf(op, [Scan.sAmp, Scan.sBar, Scan.sXor]) and (xt^.form = Sym.fBool) then return wrongLogic(op, x); end;
1046- if oneOf(op, [Scan.sAmp, Scan.sBar, Scan.sXor]) and (yt^.form = Sym.fBool) then return wrongLogic(op, y); end;
1047-
1048- (* the lengths, then the bytes, LEN * SIZE(T) of them: the elements
1049- are of types whose bytes say all there is to their values *)
1050- if ((op = Scan.sEql) or (op = Scan.sNeq)) and isSeq(xt) then
1051- e := elemOf(xt);
1052- if not isSeq(yt) then
1053- return Scan.markAt(Diag.join(x.pos, y.pos), say1("can't compare an array with {}", Sym.typeName(yt)));
1054- elsif not Sym.same(e, elemOf(yt)) then
1055- return Scan.markAt(Diag.join(x.pos, y.pos),
1056- say2("can't compare an array of {} with one of {}", Sym.typeName(e), Sym.typeName(elemOf(yt))));
1057- end;
1058- if e^.form = Sym.fReal then
1059- return Scan.markHelp(Diag.join(x.pos, y.pos),
1060- say1("can't compare arrays of reals with {}", Scan.symText(op)),
1061- "-0.0 = 0.0 and a NaN equals nothing, though their bytes say otherwise: write a loop");
1062- elsif not (e^.form in {Sym.fInt, Sym.fBool, Sym.fEnum, Sym.fSet, Sym.fPtr}) then
1063- return Scan.markHelp(Diag.join(x.pos, y.pos),
1064- say2("can't compare arrays of {} with {}", Sym.typeName(e), Scan.symText(op)), "write a loop");
1065- end;
1066- try seqSlice(y);
1067- Gen.compareSeq(x.off, y.off, log2(e^.size), op = Scan.sEql);
1068- makeConst(x, Sym.tBool, 0);
1069- x.mode := mStack;
1070- return nil;
1071- end;
1072-
1073- (* the type of the result, and the checks *)
1074- t := nil; scale := 1; isPtr := false;
1075- if Sym.isInt(xt) and Sym.isInt(yt) then
1076- if op = Scan.sSlash then
1077- return Scan.markHelp(Diag.join(x.pos, y.pos), "\"/\" divides reals, not integers",
1078- say2("to divide integers, write {} div {}", Diag.source(x.pos), Diag.source(y.pos)));
1079- end;
1080- if (op = Scan.sShl) or (op = Scan.sShr) then
1081- if xt^.form = Sym.fConst then t := Sym.tConst; else t := xt; end;
1082- elsif (xt^.form = Sym.fConst) and (yt^.form = Sym.fConst) then t := Sym.tConst;
1083- elsif xt^.form = Sym.fConst then
1084- if (x.mode = mConst) and not Sym.fits(x.val, yt) then
1085- return Scan.markAt(x.pos, Diag.say("{} doesn't fit {}", [Fmt.int(x.val), Fmt.str(Sym.typeName(yt))]));
1086- end;
1087- t := yt;
1088- elsif yt^.form = Sym.fConst then
1089- if (y.mode = mConst) and not Sym.fits(y.val, xt) then
1090- return Scan.markAt(y.pos, Diag.say("{} doesn't fit {}", [Fmt.int(y.val), Fmt.str(Sym.typeName(xt))]));
1091- end;
1092- t := xt;
1093- elsif Sym.same(xt, yt) then t := xt;
1094- else return mismatchOps(x, y, xt, yt); end;
1095- if not intOp(op) then return doesntApply(op, x, y, t); end;
1096- elsif (xt^.form = Sym.fReal) and (yt^.form = Sym.fReal) then
1097- if not (isRel(op) or oneOf(op, [Scan.sPlus, Scan.sMinus, Scan.sTimes, Scan.sSlash])) then
1098- return doesntApply(op, x, y, xt);
1099- end;
1100- if xt = Sym.tRConst then t := yt;
1101- elsif (yt = Sym.tRConst) or Sym.same(xt, yt) then t := xt;
1102- else return mismatchOps(x, y, xt, yt); end;
1103- if (x.mode = mConst) and (x.typ # t) then realTo(x, t); end;
1104- if (y.mode = mConst) and (y.typ # t) then realTo(y, t); end;
1105- elsif (xt^.form = Sym.fBool) and (yt^.form = Sym.fBool) then
1106- if (op # Scan.sEql) and (op # Scan.sNeq) then return doesntApply(op, x, y, xt); end;
1107- t := Sym.tBool;
1108- elsif (xt^.form = Sym.fPtr) and Sym.isInt(yt) and ((op = Scan.sPlus) or (op = Scan.sMinus)) then
1109- t := xt; scale := INT(xt^.base^.size); isPtr := true;
1110- if y.mode = mConst then y.typ := Sym.tInt; end;
1111- elsif (xt^.form = Sym.fPtr) and (yt^.form = Sym.fPtr) and (op = Scan.sMinus) then
1112- if not Sym.same(xt, yt) then return mismatchOps(x, y, xt, yt); end;
1113- t := Sym.tInt; scale := INT(xt^.base^.size); isPtr := true;
1114- elsif (xt^.form in {Sym.fPtr, Sym.fProc, Sym.fNil, Sym.fError}) and (yt^.form in {Sym.fPtr, Sym.fProc, Sym.fNil, Sym.fError}) then
1115- if not isRel(op) then return doesntApply(op, x, y, xt); end;
1116- if (xt^.form in {Sym.fProc, Sym.fError}) or (yt^.form in {Sym.fProc, Sym.fError}) then
1117- if (op # Scan.sEql) and (op # Scan.sNeq) then return doesntApply(op, x, y, xt); end;
1118- end;
1119- if (xt^.form # Sym.fNil) and (yt^.form # Sym.fNil) and not Sym.same(xt, yt) then
1120- if not ((xt^.form = Sym.fPtr) and (yt^.form = Sym.fPtr) and Sym.same(xt^.base, yt^.base)) then
1121- return mismatchOps(x, y, xt, yt);
1122- end;
1123- end;
1124- t := Sym.tU64;
1125- elsif (xt^.form = Sym.fEnum) and Sym.same(xt, yt) then
1126- if not isRel(op) then return doesntApply(op, x, y, xt); end;
1127- t := xt;
1128- elsif (xt^.form = Sym.fSet) and Sym.same(xt, yt) then
1129- if not oneOf(op, [Scan.sPlus, Scan.sTimes, Scan.sMinus, Scan.sEql, Scan.sNeq, Scan.sLeq, Scan.sGeq]) then
1130- return doesntApply(op, x, y, xt);
1131- end;
1132- t := xt;
1133- elsif (op = Scan.sIn) and (yt^.form = Sym.fSet) and Sym.same(xt, yt^.base) then
1134- t := yt;
1135- else
1136- return mismatchOps(x, y, xt, yt);
1137- end;
1138-
1139- (* constants *)
1140- if (x.mode = mConst) and (y.mode = mConst) and not isPtr then
1141- if t^.form = Sym.fReal then
1142- if not foldReal(op, x, y, t, r) then return doesntApply(op, x, y, xt); end;
1143- x := r;
1144- elsif t^.form = Sym.fSet then
1145- a := x.val; b := y.val;
1146- match op of
1147- | sPlus: makeConst(x, t, a | b);
1148- | sTimes: makeConst(x, t, a & b);
1149- | sMinus: makeConst(x, t, a & ~b);
1150- | sIn: makeConst(x, Sym.tBool, (b shr a) & 1);
1151- | sLeq: makeConst(x, Sym.tBool, bit((a & ~b) = 0));
1152- | sGeq: makeConst(x, Sym.tBool, bit((b & ~a) = 0));
1153- | else: makeConst(x, Sym.tBool, bit((a = b) = (op = Scan.sEql)));
1154- end;
1155- elsif isRel(op) then
1156- v := try foldInt(op, x.val, y.val, t, Diag.join(x.pos, y.pos));
1157- makeConst(x, Sym.tBool, v);
1158- else
1159- v := try foldInt(op, x.val, y.val, t, Diag.join(x.pos, y.pos));
1160- makeConst(x, t, cut(v, t));
1161- end;
1162- return nil;
1163- end;
1164-
1165- (* x and y on the stack, x under y; a constant x goes on after y, and
1166- is left on top where the order doesn't matter, as Gen takes a
1167- constant best on the right: 0.25 * e is mulsd xmm8, [0.25] *)
1168- try value(y);
1169- if x.mode = mConst then
1170- try value(x);
1171- if not oneOf(op, [Scan.sPlus, Scan.sTimes, Scan.sAmp, Scan.sBar, Scan.sXor]) or isPtr then Gen.swap(); end;
1172- end;
1173-
1174- if t^.form = Sym.fReal then
1175- if isRel(op) then Gen.compare(op, Gen.kindOf(t), false);
1176- else Gen.op(op, Gen.kindOf(t), 8, false); end;
1177- elsif t^.form = Sym.fSet then
1178- setOp(op);
1179- elsif isRel(op) then
1180- x.mode := mCond;
1181- x.rel := op;
1182- x.relSigned := signed(t);
1183- x.fj := Gen.NoLabel;
1184- x.tj := Gen.NoLabel;
1185- x.typ := Sym.tBool;
1186- return nil;
1187- elsif isPtr then
1188- if t # Sym.tInt then scaleBy(scale); end;
1189- Gen.op(op, Gen.kWord, 8, false);
1190- if (t = Sym.tInt) and (scale # 1) then
1191- Gen.pushConst(Gen.kWord, scale);
1192- Gen.op(Scan.sDiv, Gen.kWord, 8, true);
1193- end;
1194- else
1195- Gen.op(op, Gen.kindOf(t), intSize(t), signed(t));
1196- end;
1197- x.mode := mStack;
1198- if isRel(op) or (op = Scan.sIn) then x.typ := Sym.tBool; else x.typ := t; end;
1199- return nil;
1200-end;
1201-
1202-(* INT and UINT, the integers as big as an address, through which
1203- integers and pointers convert (report section 6.7) *)
1204-proc isWord*(t: ^Sym.Type): BOOL;
1205-begin
1206- return Sym.same(t, Sym.tInt) or Sym.same(t, Sym.tUInt);
1207-end;
1208-
1209-proc convert*(var x: Item; t: ^Sym.Type): ERROR;
1210-var s: ^Sym.Type; r: F64;
1211-begin
1212- s := x.typ;
1213- if x.mode in {mType, mBuiltin, mNone, mCase, mStr} then
1214- if x.mode = mStr then return Scan.markAt(x.pos, "can't convert a string"); end;
1215- return notValue(x);
1216- end;
1217- if Sym.same(s, t) then return nil; end;
1218- if (Sym.isInt(s) or (s^.form in {Sym.fEnum, Sym.fSet})) and (t^.form = Sym.fInt) then
1219- if x.mode = mConst then x.val := cut(x.val, t);
1220- else try value(x); Gen.narrow(INT(t^.size), t^.signed); end;
1221- elsif Sym.isInt(s) and (t^.form = Sym.fEnum) then
1222- if x.mode = mConst then
1223- if (x.val < 0) or (x.val >= t^.len) then
1224- return Scan.markAt(x.pos, Diag.say("{} isn't a position of {}", [Fmt.int(x.val), Fmt.str(Sym.typeName(t))]));
1225- end;
1226- else try value(x); Gen.checkEnum(t^.len, nameChunk(t), x.pos); end;
1227- elsif Sym.isInt(s) and (t^.form = Sym.fSet) then
1228- if x.mode = mConst then
1229- if t^.len < 64 then x.val := x.val & ((I64(1) shl t^.len) - 1); end;
1230- else
1231- try value(x);
1232- if t^.len < 64 then
1233- Gen.pushConst(Gen.kWord, (I64(1) shl t^.len) - 1);
1234- Gen.op(Scan.sAmp, Gen.kWord, 8, false);
1235- end;
1236- end;
1237- elsif Sym.isInt(s) and (t^.form = Sym.fReal) then
1238- if x.mode = mConst then
1239- if (s^.form = Sym.fInt) and not s^.signed then r := F64(U64(x.val)); else r := F64(x.val); end;
1240- makeReal(x, r);
1241- realTo(x, t);
1242- else
1243- try value(x);
1244- Gen.intToReal(Gen.kindOf(t), (s^.form = Sym.fInt) and not s^.signed and (s^.size = 8));
1245- end;
1246- elsif (s^.form = Sym.fReal) and (t^.form = Sym.fReal) then
1247- (* F32 to F64, F64 to F32, or a real constant to either *)
1248- if x.mode = mConst then realTo(x, t);
1249- else try value(x); Gen.realToReal(Gen.kindOf(s)); end;
1250- elsif (s^.form = Sym.fReal) and (t^.form = Sym.fInt) then
1251- if x.mode = mConst then
1252- r := realOf(x);
1253- (* NaN or out of range folds to low(int64), the "integer
1254- indefinite" cvttsd2si gives at run time *)
1255- if (r # r) or (r >= 9.2233720368547758E18) or (r < -9.2233720368547758E18) then
1256- x.val := cut(MinI64, t);
1257- else x.val := cut(I64(r), t); end;
1258- else
1259- try value(x); Gen.realToInt(Gen.kindOf(s)); Gen.narrow(INT(t^.size), t^.signed);
1260- end;
1261- elsif (isWord(s) or (s^.form in {Sym.fConst, Sym.fPtr, Sym.fProc, Sym.fNil})) and (t^.form in {Sym.fPtr, Sym.fProc}) then
1262- if x.mode # mConst then try value(x); end;
1263- elsif (s^.form in {Sym.fPtr, Sym.fProc}) and isWord(t) then
1264- try value(x);
1265- else
1266- return Scan.markAt(x.pos, say2("can't convert {} to {}", Sym.typeName(s), Sym.typeName(t)));
1267- end;
1268- x.typ := t;
1269- return nil;
1270-end;
1271-
1272-(* Calls *)
1273-
1274-proc beginCall*(var c: Gen.CallInfo; var x: Item): ERROR;
1275-begin
1276- if x.mode = mProc then
1277- c.sig := x.obj^.typ; c.chunk := x.obj^.chunk; c.target := 0;
1278- c.obj := x.obj; c.ext := x.obj^.ext;
1279- else
1280- c.obj := nil; c.ext := false;
1281- if x.typ^.form # Sym.fProc then
1282- return Scan.markAt(x.pos, say1("expected a procedure, found {}", what(x)));
1283- end;
1284- c.sig := x.typ; c.chunk := -1;
1285- c.target := try toSlot(x);
1286- end;
1287- c.param := c.sig^.fields;
1288- c.n := 0;
1289- return nil;
1290-end;
1291-
1292-(* Too many arguments or too few, at p *)
1293-proc wrongCount(var c: Gen.CallInfo; p: Diag.Pos; text: []U8): ERROR;
1294-begin
1295- if c.obj = nil then return Scan.markAt(p, text); end;
1296- Diag.error(p, Diag.say("{}: {} takes {}", [Fmt.str(text), Fmt.str(Scan.nameOf(c.obj^.name)), Fmt.int(c.sig^.len)]));
1297- if c.obj^.home # nil then Diag.note(c.obj^.pos, "the signature is here"); end;
1298- return Scan.Failed;
1299-end;
1300-
1301-(* Pushes the two words of x, a slice or two results (inTwoRegs), read
1302- from memory now, so that what comes after can't change them. *)
1303-proc pushWords(var x: Item): ERROR;
1304-var adr: Gen.Adr; f: ^Sym.Obj;
1305-begin
1306- if x.mode = mWords then return nil; end; (* there already *)
1307- (* copied to a temporary unless its two words are in memory at a place
1308- 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
1310- try copyToTemp(x);
1311- end;
1312- adr := adrOf(x);
1313- if x.typ^.form = Sym.fSlice then
1314- Gen.pushVar(adr, 8, false, Gen.kWord);
1315- INC(adr.off, 8);
1316- Gen.pushVar(adr, 8, false, Gen.kWord);
1317- else
1318- f := x.typ^.fields;
1319- while f # nil do
1320- adr.off := adrOf(x).off + f^.val;
1321- Gen.pushVar(adr, scalarSize(f^.typ), signed(f^.typ), Gen.kindOf(f^.typ));
1322- f := f^.next;
1323- end;
1324- end;
1325- return nil;
1326-end;
1327-
1328-proc passArg*(var c: Gen.CallInfo; var a: Item): ERROR;
1329-var p: ^Sym.Obj;
1330-begin
1331- p := c.param;
1332- if c.n >= LEN(c.isF) - 1 then return Scan.markAt(a.pos, "too many arguments"); end;
1333- if p = nil then
1334- (* past the parameters of a C procedure that ends in ...: a string
1335- goes as a C string, an integer constant as an INT, a real
1336- constant as an F64; C takes no F32 there *)
1337- if not c.sig^.variadic then return wrongCount(c, a.pos, "too many arguments"); end;
1338- if a.mode = mStr then try coerce(a, Sym.tPtrU8);
1339- elsif a.typ^.form = Sym.fConst then try coerce(a, Sym.tInt);
1340- elsif a.typ = Sym.tRConst then try coerce(a, Sym.tReal);
1341- elsif isF32(a.typ) then return Scan.markAt(a.pos, "an F32 goes to ... as F64(x)");
1342- elsif not Sym.isScalar(a.typ) then return Scan.markAt(a.pos, "only a single value goes to ..."); end;
1343- c.isF[c.n] := a.typ^.form = Sym.fReal;
1344- c.pair[c.n] := false;
1345- try value(a);
1346- INC(c.n);
1347- return nil;
1348- end;
1349- c.isF[c.n] := (p^.typ^.form = Sym.fReal) and not p^.isVar;
1350- passing := p;
1351- passingAt := a.pos;
1352- if p^.isVar then
1353- try notReadOnly(a);
1354- if (a.mode # mVar) or not a.isVar then return Scan.markAt(a.pos, "a var parameter needs a variable"); end;
1355- if a.odd then return Scan.markAt(a.pos, "a field of a packed record can't be a var parameter"); end;
1356- if not Sym.same(a.typ, p^.typ) then
1357- return mismatch(a, say2("a var parameter needs exactly {}, found {}", Sym.typeName(p^.typ), what(a)));
1358- end;
1359- if a.vol then return Scan.markAt(a.pos, "can't pass through a volatile pointer to a var parameter"); end;
1360- try address(a);
1361- elsif p^.typ^.form = Sym.fSlice then
1362- try coerce(a, p^.typ);
1363- try pushWords(a);
1364- c.pair[c.n] := true;
1365- INC(c.n);
1366- c.isF[c.n] := false;
1367- elsif Sym.isAggregate(p^.typ) then
1368- try coerce(a, p^.typ);
1369- if a.isVar or a.vol or (a.base # Gen.bFrame) then try copyToTemp(a); end;
1370- try address(a);
1371- else
1372- try coerce(a, p^.typ);
1373- try value(a);
1374- end;
1375- c.pair[c.n] := false;
1376- INC(c.n);
1377- c.param := p^.next;
1378- return nil;
1379-end;
1380-
1381-(* The call c made, with x its result as an item: none; a temporary, for a
1382- slice or a record; two results on Gen's stack (mWords); else one value
1383- on the stack. *)
1384-proc endCall*(var c: Gen.CallInfo; var x: Item): ERROR;
1385-var res: ^Sym.Type;
1386-begin
1387- if c.param # nil then try wrongCount(c, Scan.tokPos(), "too few arguments"); end;
1388- Gen.call(c);
1389- res := c.sig^.base;
1390- x := {};
1391- if res = nil then
1392- x.mode := mNone; x.typ := Sym.tNone; x.obj := c.obj;
1393- elsif c.ret # 0 then
1394- tempItem(x, res, c.ret);
1395- else
1396- x.mode := mStack; x.typ := res;
1397- if res^.tuple then x.mode := mWords; end;
1398- end;
1399- return nil;
1400-end;
1401-
1402-(* Variants *)
1403-
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;
1407-begin
1408- tmp := Gen.allocTemp(t^.size, t^.align);
1409- Gen.zeroVar(frameAdr(tmp), t^.size);
1410- tempItem(x, t, tmp);
1411-end;
1412-
1413-proc construct*(var x: Item; c: ^Sym.Obj);
1414-begin
1415- zeroTemp(x, c^.typ);
1416- Gen.pushConst(Gen.kWord, c^.val);
1417- Gen.popVar(frameAdr(x.off), 8);
1418-end;
1419-
1420-proc setField*(x: Item; f: ^Sym.Obj; var a: Item): ERROR;
1421-begin
1422- try coerce(a, f^.typ);
1423- if Sym.isScalar(f^.typ) then
1424- try value(a);
1425- Gen.popVar(frameAdr(x.off + f^.val), scalarSize(f^.typ));
1426- else
1427- if a.vol then return Scan.markAt(a.pos, "can't copy through a volatile pointer"); end;
1428- try address(a);
1429- Gen.copyTo(frameAdr(x.off + f^.val), f^.typ^.size);
1430- end;
1431- return nil;
1432-end;
1433-
1434-(* The slot match tests: a variant's address, or an enumeration's or an
1435- integer's value. *)
1436-proc matchBegin*(var x: Item): (I64, ERROR);
1437-var p: I64;
1438-begin
1439- if x.typ^.form in {Sym.fEnum, Sym.fInt} then return toSlot(x); end;
1440- if (x.mode # mVar) or (x.typ^.form # Sym.fVariant) then
1441- return 0, Scan.markAt(x.pos, say1("match needs a variant, an enumeration or an integer, found {}", what(x)));
1442- end;
1443- if x.ro then try copyToTemp(x); end; (* its arms' names stand for a copy's fields *)
1444- try address(x);
1445- p := Gen.allocTemp(8, 8);
1446- Gen.popVar(frameAdr(p), 8);
1447- return p, nil;
1448-end;
1449-
1450-(* To L unless the tag of the variant whose address is in slot p is tag *)
1451-proc matchTag*(p: I64; tag: I64; var L: INT);
1452-var a: Gen.Adr;
1453-begin
1454- Gen.pushVar(frameAdr(p), 8, false, Gen.kWord);
1455- a.base := Gen.bStack; a.chunk := -1; a.off := 0; a.hi := 0;
1456- Gen.pushVar(a, 8, false, Gen.kWord);
1457- Gen.pushConst(Gen.kWord, tag);
1458- Gen.jumpCmp(Scan.sNeq, false, L);
1459-end;
1460-
1461-(* To body if the integer in slot p is from lo to hi: less its lo, it is
1462- then at most hi - lo, compared unsigned, which holds for a signed type
1463- or not, with no second jump. *)
1464-proc matchRange*(p, lo, hi: I64; var body: INT);
1465-begin
1466- Gen.pushVar(frameAdr(p), 8, false, Gen.kWord);
1467- if lo = hi then
1468- Gen.pushConst(Gen.kWord, lo);
1469- Gen.jumpCmp(Scan.sEql, false, body);
1470- return;
1471- end;
1472- if lo # 0 then
1473- Gen.pushConst(Gen.kWord, lo);
1474- Gen.op(Scan.sMinus, Gen.kWord, 8, false);
1475- end;
1476- Gen.pushConst(Gen.kWord, hi - lo);
1477- Gen.jumpCmp(Scan.sLeq, false, body);
1478-end;
1479-
1480-(* A for loop's variable o, stepped by step, wrapping as its type does *)
1481-proc forStep*(o: ^Sym.Obj; step: I64): ERROR;
1482-var v, w: Item;
1483-begin
1484- try makeItem(v, o);
1485- if v.base = Gen.bReg then
1486- (* a variable in a register is stepped in it *)
1487- Gen.pushConst(Gen.kWord, step);
1488- Gen.incDecReg(v.chunk, intSize(o^.typ), signed(o^.typ), false);
1489- return nil;
1490- end;
1491- try makeItem(w, o);
1492- try value(w);
1493- Gen.pushConst(Gen.kWord, step);
1494- Gen.op(Scan.sPlus, Gen.kWord, intSize(o^.typ), signed(o^.typ));
1495- return assign(v, w);
1496-end;
1497-
1498-(* For a for loop: pushes the variable o and the limit lim, a constant or
1499- the slot it was put in, and jumps to L if the one is op the other, as
1500- the type of o compares *)
1501-proc forCmp*(o: ^Sym.Obj; lim: Item; op: Scan.Sym; var L: INT): ERROR;
1502-var v, b: Item;
1503-begin
1504- try makeItem(v, o);
1505- try value(v);
1506- b := lim;
1507- try value(b);
1508- Gen.jumpCmp(op, o^.typ^.signed, L);
1509- return nil;
1510-end;
1511-
1512-(* The end of a round of a for loop, for a positive step s, as the report
1513- has it: if v <= b and b - v < s, the loop ends; otherwise v becomes
1514- v + s and the loop goes on while v <= b. Counting the distance left,
1515- rather than comparing after the step, can't be fooled by v wrapping
1516- around. A negative step is the same the other way round: before, past
1517- and within are chosen by up, whether the step is positive.
1518- For a step of 1: v < b goes on to top, where v is stepped; v = b
1519- ends; otherwise the body moved v past b.
1520- For another step: v past b goes to past; else b - v (unsigned, as
1521- v <= b) >= |step| goes on to top, and else the loop ends.
1522- Past: v is stepped here and tested, going to body if within b. *)
1523-proc forNext*(o: ^Sym.Obj; lim: Item; step: I64; var exitL: INT; top, body: INT): ERROR;
1524-var v, b: Item; L, pastL: INT; up: BOOL; before, past, within: Scan.Sym; a: I64;
1525-begin
1526- up := step > 0;
1527- (* by a negative step, by a positive *)
1528- if up then before := Scan.sLss; past := Scan.sGtr; within := Scan.sLeq;
1529- else before := Scan.sGtr; past := Scan.sLss; within := Scan.sGeq; end;
1530- a := step;
1531- if a < 0 then a := -a; end;
1532- L := Gen.NoLabel;
1533- pastL := Gen.NoLabel;
1534- if a = 1 then
1535- try forCmp(o, lim, before, L);
1536- Gen.fixTo(L, top);
1537- try forCmp(o, lim, Scan.sEql, exitL);
1538- else
1539- try forCmp(o, lim, past, pastL);
1540- try makeItem(v, o);
1541- b := lim;
1542- if up then try value(b); try value(v);
1543- else try value(v); try value(b); end;
1544- Gen.op(Scan.sMinus, Gen.kWord, 8, false);
1545- Gen.pushConst(Gen.kWord, a);
1546- Gen.jumpCmp(Scan.sGeq, false, L);
1547- Gen.fixTo(L, top);
1548- Gen.jump(exitL);
1549- end;
1550- Gen.fix(pastL);
1551- try forStep(o, step);
1552- L := Gen.NoLabel;
1553- try forCmp(o, lim, within, L);
1554- Gen.fixTo(L, body);
1555- return nil;
1556-end;
1557-
1558-(* Jumps to L if the condition x is false. The jumps waiting in x.fj join
1559- L; those in x.tj are placed here, as x is true past this. *)
1560-proc condJump*(var x: Item; var L: INT): ERROR;
1561-begin
1562- if x.typ^.form # Sym.fBool then
1563- return Scan.markAt(x.pos, say1("a condition is a BOOL, found {}", what(x)));
1564- end;
1565- if x.mode = mCond then
1566- Gen.jumpCmp(negated(x.rel), x.relSigned, L);
1567- L := Gen.joinJumps(L, x.fj);
1568- Gen.fix(x.tj);
1569- return nil;
1570- end;
1571- try value(x);
1572- Gen.jumpIf(L, false);
1573- return nil;
1574-end;
1575-
1576-(* As condJump, but the jump to L is taken where the condition is true;
1577- x.tj joins L and x.fj is placed here *)
1578-proc condJumpTrue*(var x: Item; var L: INT): ERROR;
1579-begin
1580- if x.typ^.form # Sym.fBool then
1581- return Scan.markAt(x.pos, say1("a condition is a BOOL, found {}", what(x)));
1582- end;
1583- if x.mode = mCond then
1584- Gen.jumpCmp(x.rel, x.relSigned, L);
1585- L := Gen.joinJumps(L, x.tj);
1586- Gen.fix(x.fj);
1587- return nil;
1588- end;
1589- try value(x);
1590- Gen.jumpIf(L, true);
1591- return nil;
1592-end;
1593-
1594-(* Procedures *)
1595-
1596-proc beginProc*(sig: ^Sym.Type; params: ^Sym.Obj);
1597-begin
1598- result := sig^.base;
1599- Gen.beginProc(sig, params);
1600-end;
1601-
1602-(* The result of return x: a value on top, a slice's two words on top,
1603- or one copied behind the hidden pointer *)
1604-proc returnValue*(var x: Item): ERROR;
1605-begin
1606- if result = nil then return Scan.markAt(x.pos, "this procedure returns nothing"); end;
1607- try coerce(x, result);
1608- if Sym.inTwoRegs(result) then try pushWords(x);
1609- elsif Sym.isAggregate(result) then
1610- if x.vol then return Scan.markAt(x.pos, "can't copy through a volatile pointer"); end;
1611- try address(x);
1612- Gen.copyResult(0, result^.size);
1613- else try value(x); end;
1614- return nil;
1615-end;
1616-
1617-(* One of several results: of two words, a value left on top for
1618- returnJump to put in rax or rdx; else into its place behind the
1619- hidden pointer. *)
1620-proc returnField*(f: ^Sym.Obj; var x: Item): ERROR;
1621-begin
1622- try coerce(x, f^.typ);
1623- if Sym.inTwoRegs(result) then try value(x);
1624- elsif Sym.isScalar(f^.typ) then
1625- try value(x);
1626- Gen.resultTo(f^.val, scalarSize(f^.typ));
1627- else
1628- if x.vol then return Scan.markAt(x.pos, "can't copy through a volatile pointer"); end;
1629- try address(x);
1630- Gen.copyResult(f^.val, f^.typ^.size);
1631- end;
1632- return nil;
1633-end;
1634-
1635-(* Several results at once, the call's that return f(x) passes on. *)
1636-proc returnAll*(var x: Item): ERROR;
1637-begin
1638- if Sym.inTwoRegs(result) then try pushWords(x);
1639- else
1640- try address(x);
1641- Gen.copyResult(0, result^.size);
1642- end;
1643- return nil;
1644-end;
1645-
1646-proc returnNone*: ERROR;
1647-begin
1648- if result # nil then
1649- return Scan.mark(say1("return needs a result of {}", Sym.typeName(result)));
1650- end;
1651- Gen.returnJump();
1652- return nil;
1653-end;
1654-
1655-(* Keeps a variable's address in a frame slot, rather than on the stack,
1656- while other code runs. *)
1657-proc pin*(var x: Item): ERROR;
1658-var s: I64;
1659-begin
1660- if (x.mode = mVar) and (x.base = Gen.bStack) then
1661- try address(x);
1662- s := Gen.allocTemp(8, 8);
1663- Gen.popVar(frameAdr(s), 8);
1664- x.base := Gen.bSlot;
1665- x.chunk := INT(s);
1666- end;
1667- return nil;
1668-end;
1669-
1670-(* INC(v, k) or DEC: v's address is on the stack, from address. *)
1671-proc incDec*(var v, k: Item; dec: BOOL): ERROR;
1672-begin
1673- try coerceExact(k, v.typ, "");
1674- try value(k);
1675- if v.base = Gen.bReg then Gen.incDecReg(v.chunk, scalarSize(v.typ), v.typ^.signed, dec);
1676- else Gen.incDec(scalarSize(v.typ), v.typ^.signed, dec); end;
1677- return nil;
1678-end;
1679-
1680-(* COPY(d, s): d, an array variable or a slice, as a slice in the frame,
1681- before s is read *)
1682-proc copyDest*(var d: Item): ERROR;
1683-begin
1684- if not isSeq(d.typ) or (d.mode = mStr) or ((d.typ^.form = Sym.fArray) and ((d.mode # mVar) or not d.isVar)) then
1685- return Scan.markAt(d.pos, say1("COPY copies into an array variable or a slice, found {}", what(d)));
1686- end;
1687- if d.typ^.form = Sym.fArray then try notReadOnly(d); end;
1688- return seqSlice(d);
1689-end;
1690-
1691-(* ... and the elements of s copied to its start *)
1692-proc copyFrom*(var d, s: Item): ERROR;
1693-begin
1694- if not isSeq(s.typ) or not Sym.same(elemOf(s.typ), d.typ^.base) then
1695- return Scan.markAt(s.pos, say2("COPY copies elements of {}, found {}", Sym.typeName(d.typ^.base), what(s)));
1696- end;
1697- try seqSlice(s);
1698- Gen.copySlice(d.off, s.off, d.typ^.base^.size, checks, s.pos);
1699- return nil;
1700-end;
1701-
1702-(* An error is the address of its length, followed by its message. *)
1703-proc errorChunk*(var x: Item; home, name: INT): (INT, ERROR);
1704-var c, xs, xl: INT; p: ^U8; q: ^I64;
1705-begin
1706- if x.mode # mStr then return 0, Scan.markAt(x.pos, "an error is made from a string"); end;
1707- xl := INT(x.val);
1708- p := Scan.grab(xl + 8);
1709- q := ^I64(p);
1710- q^ := x.val;
1711- xs := Chunk.chunks[x.chunk].start;
1712- COPY(p[8..8 + xl], Chunk.rodata[xs..xs + xl]);
1713- c := Chunk.newChunk(Chunk.secRodata, home, name);
1714- Chunk.setData(c, p, xl + 8, 8);
1715- return c, nil;
1716-end;
1717-
1718-proc msg*(var x: Item): ERROR;
1719-var s: I64;
1720-begin
1721- try coerce(x, Sym.tError);
1722- try value(x);
1723- s := Gen.allocTemp(16, 8);
1724- Gen.errorText(s);
1725- tempItem(x, Sym.tBytes, s);
1726- return nil;
1727-end;
1728-
1729-end Item.

self/Link.raz deleted +0 -380

@@ -1,380 +0,0 @@
1-(* Link: tree shaking, layout and patching.
2-
3- Starting from the entry chunk, marks every chunk the program can
4- reach through fixups; the rest is left out. Then gives each live
5- chunk its address and builds the images of text and rodata, with
6- every fixup patched.
7-
8- The file is laid out so that each section can be mapped as it lies:
9- text right after the headers, rodata on the next page, then a
10- writable page that starts with the table the dynamic loader reads
11- (none in a static program) and goes on as bss, in memory only. The
12- loader's other tables come at the end of rodata; Elf writes them
13- in the room left there.
14-
15- Depends on: Chunk for chunks and fixups, Scan for names and memory,
16- Diag for errors and paths.
17- Leaves out: the file format; that is Elf. *)
18-module Link;
19-import Fmt, Diag, Scan, Chunk;
20-
21-const
22- Base* = 400000H;
23- Page* = 4096;
24-
25-var
26- textOff*, textSize*: INT; (* file offset and size of text, at Base + textOff *)
27- roOff*, roSize*: INT; (* rodata, the room for the loader's tables included *)
28- roAdr*: INT; (* where rodata is loaded *)
29- extraAdr*: INT; (* that room *)
30- bssAdr*, bssSize*: INT; (* the writable segment, the loader's table first *)
31- bssOff*: INT; (* the file offset of that table *)
32- textImg*, roImg*: ^U8;
33- placesChunk*: INT; (* the rodata chunk of the places, made by the caller *)
34- linesOff*, linesSize*: INT; (* the line table, in the places: .debug_line *)
35-
36-proc setPlaces*(c: INT);
37-begin
38- placesChunk := c;
39-end;
40-
41-(* Marks live each chunk reached from entry through the fixups. *)
42-proc markLive*(entry: INT);
43-var stack: ^INT; sp, c, f, t: INT; fx: ^Chunk.Fixup;
44-begin
45- stack := ^INT(Scan.grab(Chunk.numChunks * SIZE(INT)));
46- Chunk.setLive(entry);
47- stack[0] := entry;
48- sp := 1;
49- while sp > 0 do
50- DEC(sp);
51- c := stack[sp];
52- if Chunk.chunks[c].size < 0 then
53- Diag.fatal(Diag.say("{} is declared but never defined", [Fmt.str(Chunk.chunkName(c))]));
54- end;
55- (* code and constants have fixups; variables start at zero, holding
56- no addresses *)
57- match Chunk.chunks[c].sec of
58- | secText: fx := Chunk.fixups;
59- | secRodata: fx := Chunk.dataFixups;
60- | secBss: fx := nil;
61- end;
62- if fx # nil then
63- for f := Chunk.chunks[c].firstFix to Chunk.chunks[c].firstFix + Chunk.chunks[c].numFix - 1 do
64- t := fx[f].chunk;
65- if not Chunk.chunks[t].live then
66- Chunk.setLive(t);
67- stack[sp] := t;
68- INC(sp);
69- end;
70- end;
71- end;
72- end;
73-end;
74-
75-(* Gives the live chunks of one section their places, from start;
76- returns the end. *)
77-proc place(sec: Chunk.Section; start: INT): INT;
78-var c, a: INT;
79-begin
80- a := start;
81- for c := 0 to Chunk.numChunks - 1 do
82- if Chunk.chunks[c].live and (Chunk.chunks[c].sec = sec) then
83- a := (a + Chunk.chunks[c].align - 1) div Chunk.chunks[c].align * Chunk.chunks[c].align;
84- Chunk.setAdr(c, a);
85- a := a + Chunk.chunks[c].size;
86- end;
87- end;
88- return a;
89-end;
90-
91-(* The line table, DWARF 4's line program, which gdb reads as
92- .debug_line and Rt to say where code comes from: one sequence for
93- each live procedure with lines, a row for each place noted, its
94- address, file, line and column. A row whose address and line move a
95- little is one byte, a special opcode; the others are made of the
96- standard ones. Made in lp, lpLen bytes long. *)
97-const
98- LineBase = -5; LineRange = 14; OpcodeBase = 13; (* the special opcodes' *)
99-
100-var
101- lp: ^U8;
102- lpLen, lpCap: INT;
103-
104-proc putB(v: INT);
105-begin
106- if lpLen = lpCap then
107- lp := Scan.regrab(lp, lpLen, lpCap * 2 + 256);
108- lpCap := lpCap * 2 + 256;
109- end;
110- lp[lpLen] := U8(v & 0FFH);
111- INC(lpLen);
112-end;
113-
114-(* The n low bytes of v, least significant first *)
115-proc putN(v: INT; n: INT);
116-var i: INT;
117-begin
118- for i := 1 to n do putB(v); v := v shr 8; end;
119-end;
120-
121-(* LEB128, unsigned and signed *)
122-proc putU(v: INT);
123-begin
124- while v >= 80H do putB(v & 7FH | 80H); v := v shr 7; end;
125- putB(v);
126-end;
127-
128-proc putS(v: INT);
129-begin
130- while (v < -64) or (v >= 64) do putB(v & 7FH | 80H); v := v shr 7; end;
131- putB(v & 7FH);
132-end;
133-
134-(* v as the four bytes at at in p *)
135-proc patch4(p: ^U8; at, v: INT);
136-var i: INT;
137-begin
138- for i := 0 to 3 do p[at + i] := U8((v shr (8 * i)) & 0FFH); end;
139-end;
140-
141-(* v as the eight bytes at at in p *)
142-proc patch8(p: ^U8; at, v: INT);
143-var i: INT;
144-begin
145- for i := 0 to 7 do p[at + i] := U8((v shr (8 * i)) & 0FFH); end;
146-end;
147-
148-(* Whether the standard opcode i takes an operand *)
149-proc takesOperand(i: INT): BOOL;
150-begin
151- return (i = 2) or (i = 3) or (i = 4) or (i = 5) or (i = 9) or (i = 12);
152-end;
153-
154-(* The line program of the files paths, nfiles of them, numbered from
155- 1, as they are written in the table *)
156-proc makeLines(paths: ^INT; nfiles: INT);
157-var i, f, c, cf, cl, cc, op, at, da, dl: INT; s: []U8;
158-begin
159- lpLen := 0;
160- putN(0, 4); (* unit_length, patched below *)
161- putN(4, 2); (* version *)
162- putN(0, 4); (* header_length, patched below *)
163- putB(1); putB(1); (* minimum_instruction_length, maximum_operations *)
164- putB(1); (* default_is_stmt *)
165- putB(LineBase); putB(LineRange); putB(OpcodeBase);
166- for i := 1 to OpcodeBase - 1 do
167- if takesOperand(i) then putB(1); else putB(0); end; (* their operands *)
168- end;
169- putB(0); (* no include directories *)
170- for f := 0 to nfiles - 1 do
171- s := Diag.shownPath(Scan.nameOf(paths[f]));
172- for i := 0 to LEN(s) - 1 do putB(INT(s[i])); end;
173- putN(0, 4); (* its end, directory, time, length *)
174- end;
175- putB(0);
176- patch4(lp, 6, lpLen - 10);
177- i := 0;
178- while i < Chunk.numLines do
179- c := Chunk.lines[i].chunk;
180- if not Chunk.chunks[c].live then
181- INC(i);
182- else
183- putB(0); putU(9); putB(2); (* DW_LNE_set_address *)
184- putN(Chunk.chunks[c].adr + Chunk.lines[i].at - Chunk.chunks[c].start, 8);
185- at := Chunk.lines[i].at; cf := 1; cl := 1; cc := 0;
186- while (i < Chunk.numLines) and (Chunk.lines[i].chunk = c) do
187- f := 1;
188- while paths[f - 1] # Chunk.lines[i].path do INC(f); end;
189- if f # cf then putB(4); putU(f); cf := f; end; (* DW_LNS_set_file *)
190- if Chunk.lines[i].col # cc then putB(5); putU(Chunk.lines[i].col); cc := Chunk.lines[i].col; end; (* DW_LNS_set_column *)
191- da := Chunk.lines[i].at - at;
192- dl := Chunk.lines[i].line - cl;
193- op := (dl - LineBase) + LineRange * da + OpcodeBase;
194- if (dl >= LineBase) and (dl < LineBase + LineRange) and (op <= 255) then
195- putB(op); (* a special opcode: a row *)
196- else
197- if da > 0 then putB(2); putU(da); end; (* DW_LNS_advance_pc *)
198- if dl # 0 then putB(3); putS(dl); end; (* DW_LNS_advance_line *)
199- putB(1); (* DW_LNS_copy: a row *)
200- end;
201- at := Chunk.lines[i].at; cl := Chunk.lines[i].line;
202- INC(i);
203- end;
204- putB(2); putU(Chunk.chunks[c].start + Chunk.chunks[c].size - at);
205- putB(0); putU(1); putB(1); (* DW_LNE_end_sequence *)
206- end;
207- end;
208- patch4(lp, 0, lpLen - 4);
209-end;
210-
211-var
212- buf: ^U8; (* the places, being made *)
213- at, names, poolAt: INT; (* where the next number goes, the next name, the pool's start *)
214-
215-(* The name s, in the pool, and its offset from the pool's start, at at *)
216-proc putName(s: []U8);
217-begin
218- patch4(buf, at, names - poolAt);
219- COPY(buf[names..names + LEN(s)], s);
220- buf[names + LEN(s)] := 0;
221- names := names + LEN(s) + 1;
222- at := at + 4;
223-end;
224-
225-(* Whether chunk c is a live procedure, whose places Rt knows *)
226-proc isProc(c: INT): BOOL;
227-begin
228- return Chunk.chunks[c].live and (Chunk.chunks[c].sec = Chunk.secText) and (Chunk.chunks[c].home >= 0);
229-end;
230-
231-(* The places that Rt reads to say where a failed check or a signal
232- was, and what calls were under way: where the line table is in them,
233- where text starts and stops, the numbers of procedures and of their
234- variables (I64s); for each live procedure where it starts and stops,
235- the offset of its name, its first variable and how many it has, and
236- the registers of variables it saves, as bits of Gen's VarRegs, and
237- the frame offset they are saved at (U32s); for each variable the
238- offset of its name, its place in the frame and its kind, as
239- Parse's VarKind (U32s); then the names, each ending in a zero
240- byte; then the line table (makeLines), at linesOff. They are in no
241- order, since Rt looks at them only as the program stops. *)
242-proc makePlaces(start, stop: INT);
243-var
244- files, first, count: ^INT;
245- i, f, nfiles, np, nv, c, v: INT;
246-begin
247- files := ^INT(Scan.grab(Chunk.numLines * SIZE(INT) + SIZE(INT)));
248- first := ^INT(Scan.grab(Chunk.numChunks * SIZE(INT)));
249- count := ^INT(Scan.grab(Chunk.numChunks * SIZE(INT)));
250- for c := 0 to Chunk.numChunks - 1 do first[c] := 0; count[c] := 0; end;
251- for v := Chunk.numVarNotes - 1 to 0 by -1 do
252- first[Chunk.varNotes[v].chunk] := v;
253- INC(count[Chunk.varNotes[v].chunk]);
254- end;
255- nfiles := 0; poolAt := 0; np := 0; nv := 0;
256- for i := 0 to Chunk.numLines - 1 do
257- if Chunk.chunks[Chunk.lines[i].chunk].live then
258- f := 0;
259- while (f < nfiles) and (files[f] # Chunk.lines[i].path) do INC(f); end;
260- if f = nfiles then
261- files[f] := Chunk.lines[i].path;
262- INC(nfiles);
263- end;
264- end;
265- end;
266- makeLines(files, nfiles);
267- for c := 0 to Chunk.numChunks - 1 do
268- if isProc(c) then
269- INC(np);
270- poolAt := poolAt + LEN(Chunk.chunkName(c)) + 1;
271- for v := first[c] to first[c] + count[c] - 1 do
272- poolAt := poolAt + LEN(Scan.nameOf(Chunk.varNotes[v].name)) + 1;
273- end;
274- nv := nv + count[c];
275- end;
276- end;
277- buf := Scan.grab(40 + 28 * np + 12 * nv + poolAt + lpLen);
278- (* the pool of names starts at poolAt, the line table after it *)
279- poolAt := 40 + 28 * np + 12 * nv;
280- names := poolAt;
281- at := 40;
282- v := 0;
283- for c := 0 to Chunk.numChunks - 1 do
284- if isProc(c) then
285- patch4(buf, at, Chunk.chunks[c].adr);
286- patch4(buf, at + 4, Chunk.chunks[c].adr + Chunk.chunks[c].size);
287- at := at + 8;
288- putName(Chunk.chunkName(c));
289- patch4(buf, at, v);
290- patch4(buf, at + 4, count[c]);
291- patch4(buf, at + 8, Chunk.chunks[c].saveMask);
292- patch4(buf, at + 12, Chunk.chunks[c].saveAt);
293- at := at + 16;
294- v := v + count[c];
295- end;
296- end;
297- for c := 0 to Chunk.numChunks - 1 do
298- if isProc(c) then
299- for v := first[c] to first[c] + count[c] - 1 do
300- putName(Scan.nameOf(Chunk.varNotes[v].name));
301- patch4(buf, at, Chunk.varNotes[v].off);
302- patch4(buf, at + 4, Chunk.varNotes[v].kind);
303- at := at + 8;
304- end;
305- end;
306- end;
307- linesOff := names;
308- linesSize := lpLen;
309- COPY(buf[names..names + lpLen], lp[0..lpLen]);
310- patch8(buf, 0, linesOff);
311- patch8(buf, 8, start);
312- patch8(buf, 16, stop);
313- patch8(buf, 24, np);
314- patch8(buf, 32, nv);
315- Chunk.setData(placesChunk, buf, names + lpLen, 8);
316-end;
317-
318-(* Places the live chunks, leaving roExtra bytes at the end of rodata
319- and dynSize at the start of the writable segment. The segments follow
320- each other in the file with no padding, and each is loaded a page
321- further from its file offset than the one before: rodata at Base +
322- Page + roOff, the writable segment at Base + 2 * Page + bssOff. So an
323- address and its offset agree within a page, as the loader needs, and
324- no two segments, with their different permissions, share a page.
325- The bss of a program without the loader's table has no bytes in the
326- file, and starts on a page of its own. *)
327-proc linkAll*(headerSize, roExtra, dynSize: INT);
328-var c, f, at, p, e, v: INT;
329-begin
330- textOff := (headerSize + 31) div 32 * 32; (* as each code chunk is *)
331- e := place(Chunk.secText, Base + textOff);
332- textSize := e - (Base + textOff);
333- if placesChunk >= 0 then makePlaces(Base + textOff, e); end;
334- roOff := (textOff + textSize + 31) div 32 * 32;
335- roAdr := Base + Page + roOff;
336- e := place(Chunk.secRodata, roAdr);
337- extraAdr := (e + 7) div 8 * 8;
338- if roExtra > 0 then e := extraAdr + roExtra; end;
339- roSize := e - roAdr;
340- bssOff := (roOff + roSize + 31) div 32 * 32;
341- if dynSize > 0 then
342- bssAdr := Base + 2 * Page + bssOff;
343- else
344- bssAdr := (roAdr + roSize + Page - 1) div Page * Page;
345- end;
346- e := place(Chunk.secBss, bssAdr + dynSize);
347- bssSize := e - bssAdr;
348-
349- textImg := Scan.grab(textSize + 1);
350- (* the gaps between code chunks are int3, a trap if ever run *)
351- for p := 0 to textSize do textImg[p] := 0CCH; end;
352- roImg := Scan.grab(roSize + 1);
353- for p := 0 to roSize do roImg[p] := 0; end;
354- for c := 0 to Chunk.numChunks - 1 do
355- if Chunk.chunks[c].live then
356- if Chunk.chunks[c].sec = Chunk.secText then
357- p := Chunk.chunks[c].adr - (Base + textOff);
358- COPY(textImg[p..p + Chunk.chunks[c].size], Chunk.text[Chunk.chunks[c].start..Chunk.chunks[c].start + Chunk.chunks[c].size]);
359- for f := Chunk.chunks[c].firstFix to Chunk.chunks[c].firstFix + Chunk.chunks[c].numFix - 1 do
360- at := Chunk.fixups[f].at - Chunk.chunks[c].start;
361- (* rel32: from the end of the field to the target *)
362- v := Chunk.chunks[Chunk.fixups[f].chunk].adr + Chunk.fixups[f].addend
363- - (Chunk.chunks[c].adr + at + 4);
364- patch4(textImg, p + at, v);
365- end;
366- elsif Chunk.chunks[c].sec = Chunk.secRodata then
367- p := Chunk.chunks[c].adr - roAdr;
368- COPY(roImg[p..p + Chunk.chunks[c].size], Chunk.rodata[Chunk.chunks[c].start..Chunk.chunks[c].start + Chunk.chunks[c].size]);
369- for f := Chunk.chunks[c].firstFix to Chunk.chunks[c].firstFix + Chunk.chunks[c].numFix - 1 do
370- patch8(roImg, p + Chunk.dataFixups[f].at,
371- Chunk.chunks[Chunk.dataFixups[f].chunk].adr + Chunk.dataFixups[f].addend);
372- end;
373- end;
374- end;
375- end;
376-end;
377-
378-begin
379- placesChunk := -1;
380-end Link.

self/Parse.raz deleted +0 -3775

@@ -1,3775 +0,0 @@
1-(* Parse: the parser.
2-
3- Reads modules by recursive descent and has Gen emit code as it goes:
4- one pass, no tree. Importing a module that isn't compiled yet
5- compiles it there and then, so modules are finished in an order where
6- each comes after the modules it imports; that is the order in which
7- their bodies run.
8-
9- A module may come in one file per target (Name.linux-x86_64.raz and
10- so on). The file for this target is compiled; the others beside it
11- are read for their declarations only, and must export the same
12- interface.
13-
14- Depends on: Scan, Sym, Chunk for data, Item and Gen for code.
15- Leaves out: linking; a module only records the libraries it names,
16- and whether it uses C or says link static.
17-
18- The seed's errors ended in a jump back to the statement or
19- declaration being read (Scan.mark, longjmp). Here every routine that
20- can find an error returns an ERROR as its last result, and the ones
21- that call it pass it up with try, as Item does; the statement or
22- declaration that is a recovery point (guard) looks at what comes back
23- and reads on. What has been made by then is what the seed had made
24- when it jumped. A seed `var` that only gave a value back is a result
25- where that is shorter; the others stay as they were. A set of
26- Scan.Sym is a chain of tests, since it has more names than a set
27- holds. *)
28-module Parse;
29-import Fmt, Diag, Scan, Sym, Chunk, Gen, Item, Sys, Str, Buf, Heap;
30-
31-type
32- PType = ^Sym.Type;
33- PObj = ^Sym.Obj;
34- PModule = ^Sym.Module;
35- TItem = Item.Item;
36-
37- (* The innermost loop: the chain of its breaks and the deferred
38- statements in force outside it *)
39- Loop = record
40- brk: INT;
41- base: INT;
42- end;
43- PLoop = ^Loop;
44-
45- (* A generic module's import whose instance isn't made yet (deferred,
46- numDeferred); not to be confused with a defer statement (defers) *)
47- Deferred = record
48- o: PObj; (* the name it imports as *)
49- home: PModule; (* the module that imports it *)
50- mname: INT; (* the generic module *)
51- args: Scan.State; (* at the "(" of its arguments *)
52- at: Diag.Pos; (* the import *)
53- end;
54-
55-const
56- (* Whether the target has reals (report, appendix A): x86-64 always has
57- SSE2. Without them, used code that computes with one is an error,
58- which Raz reports once it knows what the program uses. *)
59- HasReals* = true;
60-
61- MaxNames = 64; (* names in one declaration, and the like *)
62- MaxFwd = 256; (* pointers to types not yet declared *)
63- MaxDefers = 64; (* defer statements in force *)
64- MaxDrops = 4096; (* calls that drop results, in one module *)
65- MaxDeferred = 64; (* generic imports not yet made *)
66- MaxLabels = 1024; (* labels of one match *)
67- MaxElements = 1024; (* elements of an array literal *)
68- MaxFixes = 4096; (* addresses in one constant *)
69- MaxPending = 64; (* modules being compiled at once *)
70- Suffixes: [4][]U8 = [".linux-x86_64", ".linux", ".x86_64", ""];
71-
72-var
73- libDir*, mainDir: []U8;
74- incDirs*: [16][]U8;
75- numInc*: INT;
76- firstModule*, lastModule*: PModule; (* in the order they were finished *)
77-
78- checkMode: BOOL; (* reading a file only for its interface *)
79- inTypes: BOOL; (* in a type section: ^T may name a later type *)
80- fwdTypes: [MaxFwd]PType;
81- fwdPos: [MaxFwd]Diag.Pos; (* where each names its type *)
82- numFwd: INT;
83- lastCalled: PObj; (* the procedure the last call was of, if it had a name *)
84- passOn: BOOL; (* the next factor may be a call with several results, for return *)
85- curProc: PObj; (* the procedure being compiled, or nil *)
86- declExported: BOOL; (* the export mark of the declaration being read *)
87- curLoop: PLoop; (* the innermost loop, or nil *)
88- defers: [MaxDefers]INT; (* the defer statements in force, their code's addresses *)
89- numDefers: INT;
90- deferring: BOOL; (* compiling a defer statement's statement *)
91- directDefer: BOOL; (* ... as the statement itself, not in a list *)
92- deferSlot: I64; (* keeps a result while deferred statements run *)
93- curResult: PType; (* the result type of the procedure being compiled *)
94- inExtern: BOOL; (* reading an extern's signature: ... allowed *)
95- tArgv, tBodySig: PType;
96- nameRt, nameFail, nameBody, nameStatic, nameCheck, nameOff, nameAdr: INT;
97- declaring: [MaxNames]INT; (* the names the declaration being read declares *)
98- numDeclaring: INT;
99- skipped: BOOL; (* the last statement had an error and was skipped *)
100- deferred: [MaxDeferred]Deferred; (* generic imports not yet made, not defer statements *)
101- numDeferred: INT;
102- making: BOOL; (* reading an instance's arguments, at its first use *)
103- stray: BOOL; (* an "end" in this procedure stood left of its statement's line *)
104- strayAt: Diag.Pos; (* ... the first such statement *)
105- elseIf: BOOL; (* an "else if" in this procedure *)
106- drops: [MaxDrops]record
107- at: Diag.Pos; (* a call standing on its own that drops results *)
108- n: INT; (* ... how many *)
109- end;
110- numDrops: INT; (* the module being compiled has those from its
111- first one, saved by compileFile, to here *)
112- ends: BOOL; (* the statements just read never go on past
113- their end: each way through them returns *)
114- useAt: Diag.Pos; (* ... which is here *)
115- guards: INT; (* the recovery points open *)
116-
117-proc expression(var x: TItem; want: PType): ERROR; forward;
118-proc parseType: (PType, ERROR); forward;
119-proc statements: ERROR; forward;
120-proc statement: ERROR; forward;
121-
122-(* Little helpers *)
123-
124-proc setLibDir*(dir: []U8);
125-begin
126- libDir := dir;
127-end;
128-
129-proc addIncDir*(dir: []U8);
130-begin
131- incDirs[numInc] := dir;
132- INC(numInc);
133-end;
134-
135-proc nameOf(n: INT): []U8;
136-begin
137- return Scan.nameOf(n);
138-end;
139-
140-(* The name number of s, which isn't empty *)
141-proc internName(s: []U8): INT;
142-begin
143- return Scan.intern(ADR(s[0]), LEN(s));
144-end;
145-
146-proc say1(f, a: []U8): []U8;
147-begin
148- return Diag.say(f, [Fmt.str(a)]);
149-end;
150-
151-proc say2(f, a, b: []U8): []U8;
152-begin
153- return Diag.say(f, [Fmt.str(a), Fmt.str(b)]);
154-end;
155-
156-proc say3(f, a, b, c: []U8): []U8;
157-begin
158- return Diag.say(f, [Fmt.str(a), Fmt.str(b), Fmt.str(c)]);
159-end;
160-
161-(* More than n of what, as a message *)
162-proc tooMany(n: INT; what: []U8): []U8;
163-begin
164- return Diag.say("more than {} {}", [Fmt.int(n), Fmt.str(what)]);
165-end;
166-
167-(* A missing symbol is reported just after the one before it. *)
168-proc expected(what: []U8): ERROR;
169-begin
170- if Scan.tok = Scan.sBlank then
171- return Scan.mark("_ isn't a name: it is the blank, which stands only left of :=");
172- end;
173- return Scan.markAt(Scan.missingPos(), say2("expected {}, found {}", what, Scan.found()));
174-end;
175-
176-proc expect(s: Scan.Sym): ERROR;
177-begin
178- if (Scan.tok = Scan.sLbrace) and ((s = Scan.sThen) or (s = Scan.sDo)) then
179- return Scan.markHelp(Scan.missingPos(), say2("expected {}, found {}", Scan.symText(s), Scan.found()),
180- say1("a block is written {} ... end", Scan.symText(s)));
181- end;
182- if Scan.tok # s then return expected(Scan.symText(s)); end;
183- Scan.next;
184- return nil;
185-end;
186-
187-(* The end of a block statement at start, whose line is indented to
188- ind. An "end" left of that was most likely meant for a block around
189- the statement, which leaves the statement's own "end" missing: the
190- first such is kept for endMissing. *)
191-proc closeEnd(start: Diag.Pos; ind: INT): ERROR;
192-begin
193- if (Scan.tok = Scan.sEnd) and not stray and (Scan.indent() < ind) then
194- stray := true;
195- strayAt := start;
196- end;
197- return expect(Scan.sEnd);
198-end;
199-
200-(* The error of a procedure or module whose own "end" isn't where it
201- should be, with what closeEnd saw *)
202-proc endMissing(p: Diag.Pos; msg: []U8): ERROR;
203-begin
204- Diag.error(p, msg);
205- if stray then Diag.note(strayAt, "is this statement's \"end\" missing? one further left closes it"); end;
206- if elseIf then Diag.help("raz writes elsif: \"else if\" begins an if that needs its own \"end\""); end;
207- return Scan.Failed;
208-end;
209-
210-(* A name being declared, and whether it is exported; at is the name *)
211-proc identDef(var n: INT; var exp: BOOL; var at: Diag.Pos): ERROR;
212-begin
213- if Scan.tok # Scan.sIdent then return expected("a name"); end;
214- n := Scan.id;
215- at := Scan.tokPos();
216- Scan.next;
217- exp := false;
218- if Scan.tok = Scan.sTimes then
219- exp := true;
220- Scan.next;
221- end;
222- return nil;
223-end;
224-
225-(* Declares o in the innermost scope. Its module keeps its declarations
226- in order: its own, for the interface check, and its procedures', to
227- warn of those never used. *)
228-proc declare(o: PObj): ERROR;
229-var m: PModule;
230-begin
231- m := Sym.curModule;
232- try Sym.insert(o, Sym.topScope());
233- if Sym.topScope() = m^.scope then
234- if m^.last = nil then m^.first := o; else m^.last^.chain := o; end;
235- m^.last := o;
236- else
237- if m^.lastLocal = nil then m^.locals := o; else m^.lastLocal^.chain := o; end;
238- m^.lastLocal := o;
239- end;
240- return nil;
241-end;
242-
243-(* o is named: a procedure naming itself doesn't count *)
244-proc named(o: PObj);
245-begin
246- if o # curProc then
247- o^.used := true;
248- o^.read := true;
249- end;
250-end;
251-
252-(* Recovery
253-
254- After an error the parser goes on with the next statement or
255- declaration, so that one run reports every error. Each statement and
256- declaration is a recovery point: it notes the state of the scanner
257- and the parser where it starts, and when what it read comes back with
258- an error, the state is put back, the scanner reads the construct
259- again from its start, skipping to its end, and the parser carries on
260- after it. Nothing is generated after an error, so the code half made
261- for the construct does no harm. A name that isn't declared is
262- declared where it is used, with type tPoison, and what follows from
263- it is not reported again; so are the names of a declaration that had
264- an error.
265-
266- Skipping counts the words that open and close blocks. A symbol at
267- the start of a line is taken to start a declaration of the module,
268- as layout has it: a statement skipped up to one gives up its
269- procedure, and the procedure is skipped up to its end. *)
270-
271-type
272- Recover = record
273- scan: Scan.State;
274- scopes, depth, pushed, numDefers: INT;
275- guards: INT;
276- loop: PLoop;
277- result: PType;
278- deferring, directDefer, quiet: BOOL;
279- end;
280-
281-proc guard(var r: Recover);
282-begin
283- Scan.saveScan(r.scan);
284- r.guards := guards;
285- r.scopes := Sym.scopeDepth(); r.depth := Gen.depth; r.pushed := Gen.pushed; r.numDefers := numDefers;
286- r.loop := curLoop; r.result := curResult;
287- r.deferring := deferring; r.directDefer := directDefer; r.quiet := Diag.quiet;
288- INC(guards);
289- Diag.setQuiet(false);
290-end;
291-
292-proc unguard(var r: Recover);
293-begin
294- guards := r.guards;
295- Diag.setQuiet(r.quiet);
296- Scan.setSkipping(false);
297-end;
298-
299-(* After an error: the state as it was at the start of r's construct,
300- whose first symbol is again the current one *)
301-proc restore(var r: Recover);
302-begin
303- Scan.restoreScan(r.scan);
304- Scan.setSkipping(true);
305- Sym.cutScopes(r.scopes);
306- Gen.resetStack(r.depth, r.pushed);
307- numDefers := r.numDefers;
308- curLoop := r.loop; curResult := r.result;
309- deferring := r.deferring; directDefer := r.directDefer;
310- inTypes := false; declExported := false; inExtern := false; making := false;
311-end;
312-
313-(* Gives up the construct r is for, and the one around it: the error
314- goes on up to the next recovery point, or ends the compile if there
315- is none *)
316-proc giveUp(var r: Recover): ERROR;
317-begin
318- unguard(r);
319- if guards = 0 then Diag.finish(); end;
320- return Scan.Failed;
321-end;
322-
323-(* Reads to the end of a statement or declaration, from its first
324- symbol: up to the ";" that ends it, not read, or to the "end",
325- "else", "elsif", "until" or "|" of the statement around it (an arm's
326- "|" comes after a ";", the operator's after an operand). False if it
327- stopped at a symbol that starts a line, or the end of the file. *)
328-proc skipConstruct: BOOL;
329-var d, p: INT; prev: Scan.Sym;
330-begin
331- d := 0; p := 0; prev := Scan.sSemicolon;
332- repeat
333- match Scan.tok of
334- | sIf, sWhile, sFor, sMatch, sRepeat, sRecord, sVariant: INC(d);
335- | sEnd, sUntil:
336- if d = 0 then return true; end;
337- DEC(d);
338- | sElse, sElsif: if (d = 0) and (p = 0) then return true; end;
339- | sBar: if (d = 0) and (p = 0) and (prev = Scan.sSemicolon) then return true; end;
340- | sLparen, sLbrak, sLbrace: INC(p);
341- | sRparen, sRbrak, sRbrace: if p > 0 then DEC(p); end;
342- | sSemicolon: if (d = 0) and (p = 0) then return true; end;
343- | sEof: return false;
344- | else:
345- end;
346- prev := Scan.tok;
347- Scan.next;
348- until Scan.atLineStart();
349- return false;
350-end;
351-
352-(* Declares n where it is used, after it was reported as not declared,
353- or after the declaration of it had an error *)
354-proc poison(n: INT);
355-var o: PObj;
356-begin
357- o := Sym.newObj(Sym.oConst, n, Sym.tPoison);
358- _ := Sym.insert(o, Sym.topScope()); (* n isn't in this scope, so it can't be twice *)
359-end;
360-
361-proc willDeclare(n: INT);
362-begin
363- if numDeclaring < MaxNames then declaring[numDeclaring] := n; end;
364- INC(numDeclaring);
365-end;
366-
367-(* After a declaration had an error: its names are poison, and reading
368- goes on after it *)
369-proc skipDeclaration;
370-var i: INT;
371-begin
372- for i := 0 to numDeclaring - 1 do
373- if (i < MaxNames) and (Sym.find(Sym.topScope(), declaring[i]) = nil) then
374- poison(declaring[i]);
375- end;
376- end;
377- if skipConstruct() and (Scan.tok = Scan.sSemicolon) then Scan.next; end;
378-end;
379-
380-proc constValue(var x: TItem): (I64, ERROR);
381-begin
382- if x.mode # Item.mConst then return 0, Scan.markAt(x.pos, "expected a constant"); end;
383- return x.val, nil;
384-end;
385-
386-proc constExpr: (I64, ERROR);
387-var x: TItem;
388-begin
389- try expression(x, nil);
390- if not Sym.isInt(x.typ) then
391- return 0, Scan.markAt(x.pos, say1("expected an integer constant, found {}", Item.what(x)));
392- end;
393- return constValue(x);
394-end;
395-
396-(* Help after a name that isn't found: o, the closest name in reach *)
397-proc didYouMean(o: PObj);
398-begin
399- if o # nil then Diag.help(say1("did you mean {}?", nameOf(o^.name))); end;
400-end;
401-
402-(* Where module n is found, if it is: dir and the file in it *)
403-proc moduleFile(n: INT): ([]U8, []U8, BOOL); forward;
404-
405-(* name in lower case, in memory that is never freed, as messages are *)
406-proc lowerCase(s: []U8): []U8;
407-var p: ^U8; i: INT;
408-begin
409- if LEN(s) = 0 then return ""; end;
410- p := Scan.grab(LEN(s));
411- for i := 0 to LEN(s) - 1 do
412- if (s[i] >= 'A') and (s[i] <= 'Z') then p[i] := s[i] + 32; else p[i] := s[i]; end;
413- end;
414- return p[0..LEN(s)];
415-end;
416-
417-(* Reports name n at p as not declared, with what it may have meant *)
418-proc notDeclared(p: Diag.Pos; n: INT);
419-var found: BOOL; low: []U8;
420-begin
421- Diag.error(p, say1("{} isn't declared", nameOf(n)));
422- _, _, found := moduleFile(n);
423- low := lowerCase(nameOf(n));
424- if found then Diag.help(say2("{} is a module: import {}", nameOf(n), nameOf(n)));
425- elsif (nameOf(n) = "elif") or (nameOf(n) = "elseif") then Diag.help("raz writes elsif");
426- elsif Scan.reserved(internName(low)) then Diag.help(say1("a reserved word is written in lower case: {}", low));
427- else didYouMean(Sym.closest(n, -1));
428- end;
429-end;
430-
431-proc firstUse(o: PObj; at: Diag.Pos): ERROR; forward;
432-proc instancesFor(wholeRest: BOOL): ERROR; forward;
433-proc addImport(m, im: PModule); forward;
434-
435-proc qualIdent: (PObj, ERROR);
436-var o: PObj; m: PModule; at: Diag.Pos;
437-begin
438- if Scan.tok # Scan.sIdent then return nil, expected("a name"); end;
439- at := Scan.tokPos();
440- o := Sym.lookup(Scan.id);
441- if o = nil then
442- if not making then poison(Scan.id); end; (* it may yet be declared *)
443- Diag.setQuiet(false);
444- notDeclared(at, Scan.id);
445- if making then Diag.note(useAt, "the instance is made here, where it is first used"); end;
446- return nil, Scan.Failed;
447- end;
448- if o^.typ = Sym.tPoison then Diag.setQuiet(true); end;
449- named(o);
450- Scan.next;
451- if o^.cls = Sym.oModule then
452- if o^.home = nil then try firstUse(o, at); end;
453- try expect(Scan.sPeriod);
454- if Scan.tok # Scan.sIdent then return nil, expected("a name"); end;
455- m := o^.home;
456- o := Sym.find(m^.scope, Scan.id);
457- if (o = nil) or not o^.exported then
458- Diag.error(Scan.tokPos(), say2("{} isn't exported by {}", nameOf(Scan.id), nameOf(m^.name)));
459- if o # nil then Diag.note(o^.pos, say1("{} is declared here, without a *", nameOf(Scan.id)));
460- else didYouMean(Sym.closest(Scan.id, m^.scope));
461- end;
462- return nil, Scan.Failed;
463- end;
464- Scan.next;
465- end;
466- return o, nil;
467-end;
468-
469-(* The field of record type t named by the current symbol *)
470-proc fieldOf(t: PType): (PObj, ERROR);
471-var f: PObj;
472-begin
473- f := Sym.find(t^.scope, Scan.id);
474- if f = nil then
475- Diag.error(Scan.tokPos(), say2("{} has no field {}", Sym.typeName(t), nameOf(Scan.id)));
476- didYouMean(Sym.closest(Scan.id, t^.scope));
477- return nil, Scan.Failed;
478- end;
479- if not f^.exported and (t^.home # Sym.curModule) then
480- Diag.error(Scan.tokPos(), say2("field {} of {} isn't exported", nameOf(Scan.id), Sym.typeName(t)));
481- Diag.note(f^.pos, say1("{} is declared here, without a *", nameOf(Scan.id)));
482- return nil, Scan.Failed;
483- end;
484- return f, nil;
485-end;
486-
487-proc newPtr(base: PType; vol: BOOL): PType;
488-var t: PType;
489-begin
490- t := Sym.newType(Sym.fPtr, 8, 8);
491- t^.base := base;
492- t^.vol := vol;
493- return t;
494-end;
495-
496-(* Types *)
497-
498-proc recordType: (PType, ERROR);
499-var
500- t, ft: PType; f, last: PObj; names: [MaxNames]INT;
501- exps: [MaxNames]BOOL; poss: [MaxNames]Diag.Pos;
502- n, i: INT; off, a, maxA: I64;
503-begin
504- t := Sym.newType(Sym.fRecord, 0, 1);
505- if Scan.tok = Scan.sPacked then t^.packd := true; Scan.next; end;
506- try expect(Scan.sRecord);
507- t^.scope := Sym.newScope();
508- off := 0; maxA := 1; last := nil;
509- while Scan.tok = Scan.sIdent do
510- n := 0;
511- repeat
512- if n >= MaxNames then return nil, Scan.mark(tooMany(MaxNames, "names in one declaration")); end;
513- try identDef(names[n], exps[n], poss[n]);
514- INC(n);
515- if Scan.tok # Scan.sComma then break; end;
516- Scan.next;
517- until false;
518- try expect(Scan.sColon);
519- ft := try parseType();
520- if t^.packd then a := 1; else a := ft^.align; end;
521- for i := 0 to n - 1 do
522- off := Sym.alignUp(off, a);
523- f := Sym.newObj(Sym.oField, names[i], ft);
524- f^.exported := exps[i];
525- f^.pos := poss[i];
526- f^.val := off;
527- try Sym.insert(f, t^.scope);
528- if last = nil then t^.fields := f; else last^.next := f; end;
529- last := f;
530- off := off + ft^.size;
531- end;
532- if a > maxA then maxA := a; end;
533- try expect(Scan.sSemicolon);
534- end;
535- try expect(Scan.sEnd);
536- t^.align := maxA;
537- t^.size := Sym.alignUp(off, maxA);
538- return t, nil;
539-end;
540-
541-proc variantType: (PType, ERROR);
542-var t, ft: PType; c, lastC, f, lastF: PObj; tag, off, maxSize: I64;
543-begin
544- try expect(Scan.sVariant);
545- t := Sym.newType(Sym.fVariant, 8, 8);
546- tag := 0; maxSize := 8; lastC := nil;
547- while Scan.tok = Scan.sIdent do
548- c := Sym.newObj(Sym.oCase, Scan.id, t);
549- c^.val := tag;
550- c^.exported := declExported;
551- try declare(c);
552- if lastC = nil then t^.fields := c; else lastC^.next := c; end;
553- lastC := c;
554- Scan.next;
555- off := 8;
556- if Scan.tok = Scan.sLparen then
557- Scan.next;
558- lastF := nil;
559- repeat
560- repeat
561- if Scan.tok # Scan.sIdent then return nil, expected("a name"); end;
562- f := Sym.newObj(Sym.oField, Scan.id, nil);
563- f^.exported := true;
564- if lastF = nil then c^.fields := f; else lastF^.next := f; end;
565- lastF := f;
566- Scan.next;
567- if Scan.tok # Scan.sComma then break; end;
568- Scan.next;
569- until false;
570- try expect(Scan.sColon);
571- ft := try parseType();
572- f := c^.fields;
573- while f^.typ # nil do f := f^.next; end;
574- while f # nil do
575- f^.typ := ft;
576- off := Sym.alignUp(off, ft^.align);
577- f^.val := off;
578- off := off + ft^.size;
579- f := f^.next;
580- end;
581- if ft^.align > t^.align then t^.align := ft^.align; end;
582- if Scan.tok # Scan.sSemicolon then break; end;
583- Scan.next;
584- until false;
585- try expect(Scan.sRparen);
586- end;
587- if off > maxSize then maxSize := off; end;
588- try expect(Scan.sSemicolon);
589- INC(tag);
590- end;
591- try expect(Scan.sEnd);
592- t^.len := tag;
593- t^.size := Sym.alignUp(maxSize, t^.align);
594- return t, nil;
595-end;
596-
597-(* Several results: a record of them, laid out as C would, and
598- returned in rax and rdx if they are two words (inTwoRegs), or else
599- through a hidden pointer. *)
600-proc results: (PType, ERROR);
601-var t, ft: PType; f, last: PObj; off: I64;
602-begin
603- Scan.next;
604- t := Sym.newType(Sym.fRecord, 0, 1);
605- t^.tuple := true;
606- off := 0; last := nil;
607- repeat
608- ft := try parseType();
609- off := Sym.alignUp(off, ft^.align);
610- f := Sym.newObj(Sym.oField, -1, ft);
611- f^.val := off;
612- off := off + ft^.size;
613- if ft^.align > t^.align then t^.align := ft^.align; end;
614- if last = nil then t^.fields := f; else last^.next := f; end;
615- last := f;
616- INC(t^.len);
617- if Scan.tok # Scan.sComma then break; end;
618- Scan.next;
619- until false;
620- try expect(Scan.sRparen);
621- t^.size := Sym.alignUp(off, t^.align);
622- if t^.len = 1 then return t^.fields^.typ, nil; end;
623- return t, nil;
624-end;
625-
626-proc signature: (PType, ERROR);
627-var
628- t, pt: PType; p, first, last: PObj; isVar: BOOL; n: INT;
629-begin
630- t := Sym.newType(Sym.fProc, 8, 8);
631- last := nil; n := 0;
632- if Scan.tok = Scan.sLparen then
633- Scan.next;
634- if Scan.tok # Scan.sRparen then
635- repeat
636- if Scan.tok = Scan.sEllipsis then
637- if not inExtern then return nil, Scan.mark("... is only for extern procedures"); end;
638- Scan.next; t^.variadic := true; break;
639- end;
640- isVar := Scan.tok = Scan.sVar;
641- if isVar then Scan.next; end;
642- first := nil;
643- repeat
644- if Scan.tok # Scan.sIdent then return nil, expected("a name"); end;
645- p := Sym.newObj(Sym.oVar, Scan.id, nil);
646- p^.isVar := isVar;
647- p^.lev := 1;
648- if last = nil then t^.fields := p; else last^.next := p; end;
649- last := p;
650- if first = nil then first := p; end;
651- INC(n);
652- Scan.next;
653- if Scan.tok # Scan.sComma then break; end;
654- Scan.next;
655- until false;
656- try expect(Scan.sColon);
657- pt := try parseType();
658- while first # nil do first^.typ := pt; first := first^.next; end;
659- if Scan.tok # Scan.sSemicolon then break; end;
660- Scan.next;
661- until false;
662- end;
663- try expect(Scan.sRparen);
664- end;
665- t^.len := n;
666- if Scan.tok = Scan.sColon then
667- Scan.next;
668- if Scan.tok = Scan.sLparen then t^.base := try results(); else t^.base := try parseType(); end;
669- end;
670- return t, nil;
671-end;
672-
673-proc enumType: (PType, ERROR);
674-var t: PType; o, last: PObj; start: Diag.Pos;
675-begin
676- start := Scan.tokPos();
677- t := Sym.newType(Sym.fEnum, 1, 1);
678- last := nil;
679- repeat
680- Scan.next;
681- if Scan.tok # Scan.sIdent then return nil, expected("a name"); end;
682- o := Sym.newObj(Sym.oConst, Scan.id, t);
683- o^.val := t^.len;
684- o^.exported := declExported;
685- o^.used := true; (* an enumeration's names are its type's, warned of with it *)
686- try declare(o);
687- if last = nil then t^.fields := o; else last^.next := o; end;
688- last := o;
689- INC(t^.len);
690- Scan.next;
691- until Scan.tok # Scan.sComma;
692- try expect(Scan.sRparen);
693- if t^.len > 256 then return nil, Scan.markAt(Scan.spanFrom(start), "an enumeration has at most 256 names"); end;
694- return t, nil;
695-end;
696-
697-proc setOf(e: PType; at: Diag.Pos): (PType, ERROR);
698-var t: PType;
699-begin
700- if (e^.form # Sym.fEnum) or (e^.len > 64) then
701- return nil, Scan.markAt(at, say1("a set needs an enumeration of at most 64 names, found {}", Sym.typeName(e)));
702- end;
703- t := Sym.newType(Sym.fSet, 8, 8);
704- if e^.len <= 8 then t^.size := 1;
705- elsif e^.len <= 16 then t^.size := 2;
706- elsif e^.len <= 32 then t^.size := 4;
707- end;
708- t^.align := t^.size;
709- t^.base := e;
710- t^.len := e^.len;
711- return t, nil;
712-end;
713-
714-proc parseType: (PType, ERROR);
715-var t: PType; o: PObj; n: I64; vol: BOOL; start: Diag.Pos;
716-begin
717- start := Scan.tokPos();
718- match Scan.tok of
719- | sIdent:
720- o := try qualIdent();
721- if o^.cls # Sym.oType then
722- return nil, Scan.markAt(Scan.spanFrom(start), say1("{} isn't a type", nameOf(o^.name)));
723- end;
724- t := o^.typ;
725- | sLbrak:
726- Scan.next;
727- if Scan.tok = Scan.sRbrak then
728- Scan.next;
729- t := Sym.newType(Sym.fSlice, 16, 8);
730- t^.base := try parseType();
731- else
732- start := Scan.tokPos();
733- n := try constExpr();
734- if (n <= 0) or (n > (I64(1) shl 40)) then
735- return nil, Scan.markAt(Scan.spanFrom(start), Diag.say("an array's length is from 1 to 2^40, found {}", [Fmt.int(n)]));
736- end;
737- try expect(Scan.sRbrak);
738- t := Sym.newType(Sym.fArray, 0, 1);
739- t^.len := n;
740- t^.base := try parseType();
741- t^.size := n * t^.base^.size;
742- t^.align := t^.base^.align;
743- end;
744- | sArrow:
745- Scan.next;
746- vol := Scan.tok = Scan.sVolatile;
747- if vol then Scan.next; end;
748- if inTypes and (Scan.tok = Scan.sIdent) and (Sym.lookup(Scan.id) = nil) then
749- (* a type declared later in this section *)
750- t := newPtr(nil, vol);
751- t^.fwd := Scan.id;
752- if numFwd >= MaxFwd then
753- return nil, Scan.mark(tooMany(MaxFwd, "pointers to types not yet declared"));
754- end;
755- fwdTypes[numFwd] := t;
756- fwdPos[numFwd] := Scan.tokPos();
757- INC(numFwd);
758- Scan.next;
759- else
760- t := newPtr(try parseType(), vol);
761- end;
762- | sPacked, sRecord: t := try recordType();
763- | sVariant: t := try variantType();
764- | sProc: Scan.next; t := try signature();
765- | sLparen: t := try enumType();
766- | sSet:
767- Scan.next;
768- try expect(Scan.sOf);
769- start := Scan.tokPos();
770- t := try setOf(try parseType(), start);
771- | else: return nil, expected("a type");
772- end;
773- return t, nil;
774-end;
775-
776-(* Expressions *)
777-
778-proc call(var x: TItem): ERROR;
779-var c: Gen.CallInfo; a: TItem; want: PType;
780-begin
781- try Item.beginCall(c, x);
782- try expect(Scan.sLparen);
783- if Scan.tok # Scan.sRparen then
784- repeat
785- if c.param # nil then want := c.param^.typ; else want := nil; end;
786- try expression(a, want);
787- try Item.passArg(c, a);
788- if Scan.tok # Scan.sComma then break; end;
789- Scan.next;
790- until false;
791- end;
792- try expect(Scan.sRparen);
793- return Item.endCall(c, x);
794-end;
795-
796-proc atomic(var x: TItem; which: INT): ERROR;
797-var p, a: TItem; t: PType; i, n: INT;
798-begin
799- try expression(p, nil);
800- if p.typ^.form # Sym.fPtr then
801- return Scan.markAt(p.pos, say1("expected a pointer, found {}", Item.what(p)));
802- end;
803- t := p.typ^.base;
804- if not (Item.isWord(t) or ((t^.form = Sym.fPtr) and (which # Sym.bXadd))) then
805- if which = Sym.bXadd then
806- return Scan.markAt(p.pos, say1("expected a pointer to an INT or a UINT, found {}", Sym.typeName(p.typ)));
807- end;
808- return Scan.markAt(p.pos, say1("expected a pointer to an INT, a UINT or a pointer, found {}", Sym.typeName(p.typ)));
809- end;
810- try Item.value(p);
811- if which = Sym.bCas then n := 2; else n := 1; end;
812- for i := 1 to n do
813- try expect(Scan.sComma);
814- try expression(a, t);
815- try Item.coerce(a, t);
816- try Item.value(a);
817- end;
818- Gen.atomic(which);
819- Item.makeConst(x, t, 0);
820- if which = Sym.bCas then x.typ := Sym.tBool; end;
821- x.mode := Item.mStack;
822- return nil;
823-end;
824-
825-(* NEW(p, a): p := a^.alloc(a, SIZE(T), alignment), zeroed if not nil.
826- a is a ^Mem.Allocator, the one interface the compiler knows. *)
827-proc new_(var x: TItem): ERROR;
828-var y, z: TItem; t: PType; f: PObj; s: I64; c: Gen.CallInfo;
829-begin
830- try expression(x, nil);
831- try Item.notReadOnly(x);
832- if (x.mode # Item.mVar) or not x.isVar or (x.typ^.form # Sym.fPtr) then
833- return Scan.markAt(x.pos, "NEW needs a pointer variable");
834- end;
835- t := x.typ^.base;
836- try expect(Scan.sComma);
837- try expression(y, nil);
838- if (y.typ^.form # Sym.fPtr) or (y.typ^.base^.obj = nil) or (y.typ^.base^.obj^.home = nil)
839- or (nameOf(y.typ^.base^.obj^.name) # "Allocator")
840- or (nameOf(y.typ^.base^.obj^.home^.name) # "Mem") then
841- return Scan.markAt(y.pos, say1("NEW needs a ^Mem.Allocator, found {}", Item.what(y)));
842- end;
843- f := Sym.find(y.typ^.base^.scope, internName("alloc"));
844- s := try Item.toSlot(y);
845- Gen.pushVar(Item.frameAdr(s), 8, false, Gen.kWord);
846- Item.makeConst(z, f^.typ, 0);
847- z.mode := Item.mVar; z.base := Gen.bStack; z.off := f^.val;
848- try Item.beginCall(c, z);
849- Gen.pushVar(Item.frameAdr(s), 8, false, Gen.kWord);
850- Item.makeConst(z, y.typ, 0);
851- z.mode := Item.mStack;
852- try Item.passArg(c, z);
853- Item.makeConst(z, Sym.tInt, t^.size);
854- try Item.passArg(c, z);
855- Item.makeConst(z, Sym.tInt, t^.align);
856- try Item.passArg(c, z);
857- try Item.endCall(c, z);
858- Gen.zeroNew(t^.size);
859- z.typ := x.typ;
860- try Item.assign(x, z);
861- Item.makeConst(x, Sym.tNone, 0);
862- x.mode := Item.mNone;
863- return nil;
864-end;
865-
866-proc incOrDec(which: INT): []U8;
867-begin
868- if which = Sym.bDec then return "DEC"; end;
869- return "INC";
870-end;
871-
872-proc builtin(var x: TItem): ERROR;
873-var which, n: INT; y: TItem; t: PType;
874-begin
875- which := INT(x.obj^.val);
876- if (which = Sym.bFence) or (which = Sym.bArgc) or (which = Sym.bArgv) then
877- if Scan.tok = Scan.sLparen then Scan.next; try expect(Scan.sRparen); end;
878- Item.makeConst(x, Sym.tNone, 0);
879- match which of
880- | Sym.bFence: Gen.fence(); x.mode := Item.mNone;
881- | Sym.bArgc:
882- Gen.pushVar(Item.globalAdr(Gen.argcChunk), 8, false, Gen.kWord);
883- x.typ := Sym.tInt; x.mode := Item.mStack;
884- | else:
885- Gen.pushVar(Item.globalAdr(Gen.argvChunk), 8, false, Gen.kWord);
886- x.typ := tArgv; x.mode := Item.mStack;
887- end;
888- return nil;
889- end;
890- try expect(Scan.sLparen);
891- match which of
892- | Sym.bSize:
893- t := try parseType();
894- Item.makeConst(x, Sym.tConst, t^.size);
895- | Sym.bAdr:
896- try expression(y, nil);
897- try Item.notReadOnly(y);
898- if (y.mode # Item.mVar) or not y.isVar then return Scan.markAt(y.pos, "ADR needs a variable"); end;
899- if y.odd then return Scan.markAt(y.pos, "a field of a packed record has no address"); end;
900- t := newPtr(y.typ, y.vol);
901- try Item.address(y);
902- Item.makeConst(x, t, 0);
903- x.mode := Item.mStack;
904- | Sym.bLen:
905- try expression(y, nil);
906- if y.mode = Item.mStr then
907- Item.makeConst(x, Sym.tConst, y.val);
908- elsif y.typ^.form = Sym.fArray then
909- try Item.discard(y);
910- Item.makeConst(x, Sym.tConst, y.typ^.len);
911- elsif (y.typ^.form = Sym.fSlice) and (y.mode = Item.mVar) then
912- (* its length, the word after its pointer *)
913- y.off := y.off + 8;
914- y.typ := Sym.tInt;
915- try Item.value(y);
916- x := y;
917- else
918- return Scan.markAt(y.pos, say1("LEN needs an array or a slice, found {}", Item.what(y)));
919- end;
920- | Sym.bSyscall:
921- n := 0;
922- repeat
923- if n > 0 then Scan.next; end;
924- try expression(y, nil);
925- if not (Sym.isScalar(y.typ) and (y.typ^.form # Sym.fReal)) then
926- return Scan.markAt(y.pos, say1("expected an integer or a pointer, found {}", Item.what(y)));
927- end;
928- if y.typ^.form = Sym.fConst then try Item.coerce(y, Sym.tInt); end;
929- try Item.value(y);
930- INC(n);
931- until (Scan.tok # Scan.sComma) or (n = 7);
932- Gen.sysCall(n);
933- Item.makeConst(x, Sym.tInt, 0);
934- x.mode := Item.mStack;
935- | Sym.bCas, Sym.bXchg, Sym.bXadd: try atomic(x, which);
936- | Sym.bMsg:
937- try expression(x, Sym.tError);
938- try Item.msg(x);
939- | Sym.bInc, Sym.bDec:
940- try expression(x, nil);
941- try Item.notReadOnly(x);
942- if (x.mode # Item.mVar) or not x.isVar or (x.typ^.form # Sym.fInt) then
943- return Scan.markAt(x.pos, say1("{} needs an integer variable", incOrDec(which)));
944- end;
945- if x.base # Gen.bReg then try Item.address(x); end;
946- if Scan.tok = Scan.sComma then
947- Scan.next;
948- try expression(y, x.typ);
949- else
950- Item.makeConst(y, x.typ, 1);
951- end;
952- try Item.incDec(x, y, which = Sym.bDec);
953- Item.makeConst(x, Sym.tNone, 0);
954- x.mode := Item.mNone;
955- | Sym.bNew: try new_(x);
956- | Sym.bCopy:
957- try expression(x, nil);
958- try Item.copyDest(x);
959- try expect(Scan.sComma);
960- try expression(y, nil);
961- try Item.copyFrom(x, y);
962- Item.makeConst(x, Sym.tNone, 0);
963- x.mode := Item.mNone;
964- | else:
965- end;
966- return expect(Scan.sRparen);
967-end;
968-
969-proc constructCase(var x: TItem; c: PObj; at: Diag.Pos): ERROR;
970-var f: PObj; a: TItem;
971-begin
972- Item.construct(x, c);
973- f := c^.fields;
974- if Scan.tok = Scan.sLparen then
975- Scan.next;
976- while f # nil do
977- try expression(a, f^.typ);
978- try Item.setField(x, f, a);
979- f := f^.next;
980- if f # nil then try expect(Scan.sComma); end;
981- end;
982- return expect(Scan.sRparen);
983- elsif f # nil then
984- return Scan.markAt(at, say1("{} needs its fields", nameOf(c^.name)));
985- end;
986- return nil;
987-end;
988-
989-(* x, before ".", has no fields; tok is what follows. Other languages
990- write p.f through a pointer and s.len for a length. *)
991-proc fieldOfWhat(x: TItem): ERROR;
992-var msg, f: []U8;
993-begin
994- msg := say1("expected a record, found {}", Item.what(x));
995- if Scan.tok = Scan.sIdent then f := nameOf(Scan.id); else f := ""; end;
996- if (x.typ^.form = Sym.fPtr) and (x.typ^.base^.form = Sym.fRecord) then
997- return Scan.markHelp(x.pos, msg, say2("through a pointer, write {}^.{}", Diag.source(x.pos), f));
998- elsif ((x.typ^.form = Sym.fArray) or (x.typ^.form = Sym.fSlice))
999- and ((f = "len") or (f = "length") or (f = "size") or (f = "count")) then
1000- return Scan.markHelp(x.pos, msg, say1("its length is LEN({})", Diag.source(x.pos)));
1001- end;
1002- return Scan.markAt(x.pos, msg);
1003-end;
1004-
1005-(* A designator, with any selectors and calls after it. called tells
1006- whether the last thing done was a call. *)
1007-proc designator(var x: TItem; var called: BOOL): ERROR;
1008-var o, f: PObj; y, z: TItem; t: PType; start: Diag.Pos;
1009-begin
1010- start := Scan.tokPos();
1011- o := try qualIdent();
1012- called := false;
1013- if o^.cls = Sym.oModule then
1014- return Scan.markAt(Scan.spanFrom(start), say1("{} is a module, not a value", nameOf(o^.name)));
1015- end;
1016- try Item.makeItem(x, o);
1017- if x.mode = Item.mBuiltin then
1018- try builtin(x);
1019- called := true;
1020- elsif x.mode = Item.mCase then
1021- try constructCase(x, o, Scan.spanFrom(start));
1022- end;
1023- repeat
1024- x.pos := Scan.spanFrom(start);
1025- match Scan.tok of
1026- | sPeriod:
1027- Scan.next;
1028- if (x.mode # Item.mVar) or (x.typ^.form # Sym.fRecord) then return fieldOfWhat(x); end;
1029- if Scan.tok # Scan.sIdent then return expected("a field"); end;
1030- f := try fieldOf(x.typ);
1031- Scan.next;
1032- try Item.field(x, f);
1033- called := false;
1034- | sArrow:
1035- Scan.next;
1036- try Item.deref(x);
1037- called := false;
1038- | sLbrak:
1039- Scan.next;
1040- try Item.indexPrep(x);
1041- try expression(y, nil);
1042- if Scan.tok = Scan.sUpto then
1043- Scan.next;
1044- try Item.sliceLo(y);
1045- try expression(z, nil);
1046- try Item.slice(x, y, z);
1047- else
1048- try Item.index(x, y);
1049- end;
1050- try expect(Scan.sRbrak);
1051- called := false;
1052- | sLparen:
1053- if x.mode = Item.mType then
1054- t := x.typ;
1055- Scan.next;
1056- try expression(x, nil);
1057- try expect(Scan.sRparen);
1058- try Item.convert(x, t);
1059- else
1060- if x.mode = Item.mProc then lastCalled := x.obj; else lastCalled := nil; end;
1061- try call(x);
1062- called := true;
1063- end;
1064- | else: break;
1065- end;
1066- until false;
1067- x.pos := Scan.spanFrom(start);
1068- Item.nilTest(x);
1069- return nil;
1070-end;
1071-
1072-proc arrayLiteral(var x: TItem; want: PType): ERROR;
1073-var
1074- et, at: PType; e: TItem; slots: [MaxElements]I64; n, i: INT;
1075- off, es: I64; start: Diag.Pos;
1076-begin
1077- start := Scan.tokPos();
1078- if (want = nil) or not ((want^.form = Sym.fArray) or (want^.form = Sym.fSlice)) then
1079- return Scan.mark("an array literal needs a known array or slice type");
1080- end;
1081- et := want^.base;
1082- es := et^.size;
1083- Scan.next;
1084- n := 0;
1085- if Scan.tok # Scan.sRbrak then
1086- repeat
1087- if n >= MaxElements then return Scan.mark(tooMany(MaxElements, "elements")); end;
1088- try expression(e, et);
1089- try Item.coerce(e, et);
1090- if Sym.isScalar(et) then
1091- slots[n] := try Item.toSlot(e);
1092- else
1093- if e.isVar or e.vol or (e.mode # Item.mVar) or (e.base # Gen.bFrame) then try Item.copyToTemp(e); end;
1094- slots[n] := e.off;
1095- end;
1096- INC(n);
1097- if Scan.tok # Scan.sComma then break; end;
1098- Scan.next;
1099- until false;
1100- end;
1101- try expect(Scan.sRbrak);
1102- if (want^.form = Sym.fArray) and (I64(n) # want^.len) then
1103- return Scan.markAt(Scan.spanFrom(start), Diag.say("expected {} elements, found {}", [Fmt.int(want^.len), Fmt.int(n)]));
1104- end;
1105- if n = 0 then
1106- Gen.pushConst(Gen.kWord, 0);
1107- Item.sliceOf(x, want, 0);
1108- return nil;
1109- end;
1110- if want^.form = Sym.fArray then
1111- at := want;
1112- off := Gen.allocTemp(at^.size, at^.align);
1113- else
1114- at := Sym.newType(Sym.fArray, I64(n) * es, et^.align);
1115- at^.len := n;
1116- at^.base := et;
1117- off := Gen.allocPerm(at^.size, at^.align); (* lives as long as the call *)
1118- end;
1119- for i := 0 to n - 1 do
1120- if Sym.isScalar(et) then
1121- Gen.pushVar(Item.frameAdr(slots[i]), 8, false, Gen.kindOf(et));
1122- Gen.popVar(Item.frameAdr(off + I64(i) * es), Item.scalarSize(et));
1123- else
1124- Gen.pushAdr(Item.frameAdr(slots[i]));
1125- Gen.copyTo(Item.frameAdr(off + I64(i) * es), es);
1126- end;
1127- end;
1128- Item.tempItem(x, at, off);
1129- return nil;
1130-end;
1131-
1132-(* A record literal: a zeroed temporary, with the fields named filled in. *)
1133-proc recordLiteral(var x: TItem; t: PType): ERROR;
1134-var f: PObj; a: TItem; seen: [MaxNames]INT; n, i: INT;
1135-begin
1136- Scan.next;
1137- Item.zeroTemp(x, t);
1138- n := 0;
1139- if Scan.tok # Scan.sRbrace then
1140- repeat
1141- if Scan.tok # Scan.sIdent then return expected("a field"); end;
1142- f := try fieldOf(t);
1143- for i := 0 to n - 1 do
1144- if seen[i] = Scan.id then
1145- return Scan.mark(say1("field {} is given twice", nameOf(Scan.id)));
1146- end;
1147- end;
1148- if n < MaxNames then seen[n] := Scan.id; INC(n); end;
1149- Scan.next;
1150- try expect(Scan.sColon);
1151- try expression(a, f^.typ);
1152- try Item.setField(x, f, a);
1153- if Scan.tok # Scan.sComma then break; end;
1154- Scan.next;
1155- until false;
1156- end;
1157- return expect(Scan.sRbrace);
1158-end;
1159-
1160-(* A set literal: the bits of the constant names, or'd at run time with
1161- those of the others. *)
1162-proc setLiteral(var x: TItem; t: PType): ERROR;
1163-var e: TItem; bits, slot: I64; start: Diag.Pos; s: []U8;
1164-begin
1165- start := Scan.tokPos();
1166- Scan.next;
1167- if (t # nil) and (t^.form # Sym.fSet) then
1168- return Scan.markAt(Scan.spanFrom(start), say1("expected a set type, found {}", Sym.typeName(t)));
1169- end;
1170- bits := 0;
1171- slot := 0;
1172- if Scan.tok # Scan.sRbrace then
1173- repeat
1174- if t = nil then try expression(e, nil); else try expression(e, t^.base); end;
1175- if t = nil then
1176- if e.typ^.form # Sym.fEnum then
1177- return Scan.markAt(e.pos, say1("a set holds names of an enumeration, found {}", Item.what(e)));
1178- end;
1179- t := try setOf(e.typ, e.pos);
1180- end;
1181- if not Sym.same(e.typ, t^.base) then
1182- if e.obj # nil then s := nameOf(e.obj^.name); else s := Item.what(e); end;
1183- return Scan.markAt(e.pos, say2("{} isn't a name of {}", s, Sym.typeName(t^.base)));
1184- end;
1185- if e.mode = Item.mConst then
1186- bits := bits | (I64(1) shl e.val);
1187- else
1188- if slot = 0 then
1189- slot := Gen.allocTemp(8, 8);
1190- Gen.pushConst(Gen.kWord, 0);
1191- Gen.popVar(Item.frameAdr(slot), 8);
1192- end;
1193- try Item.value(e);
1194- Gen.pushConst(Gen.kWord, 1);
1195- Gen.swap();
1196- Gen.op(Scan.sShl, Gen.kWord, 8, false);
1197- Gen.pushVar(Item.frameAdr(slot), 8, false, Gen.kWord);
1198- Gen.op(Scan.sBar, Gen.kWord, 8, false);
1199- Gen.popVar(Item.frameAdr(slot), 8);
1200- end;
1201- if Scan.tok # Scan.sComma then break; end;
1202- Scan.next;
1203- until false;
1204- end;
1205- try expect(Scan.sRbrace);
1206- if t = nil then return Scan.markAt(Scan.spanFrom(start), "{} needs a known set type"); end;
1207- Item.makeConst(x, t, bits);
1208- if slot # 0 then
1209- Gen.pushVar(Item.frameAdr(slot), 8, false, Gen.kWord);
1210- Gen.pushConst(Gen.kWord, bits);
1211- Gen.op(Scan.sBar, Gen.kWord, 8, false);
1212- x.mode := Item.mStack;
1213- end;
1214- return nil;
1215-end;
1216-
1217-proc runDefers(base: INT); forward;
1218-
1219-(* The type of the last result of t, the results of a procedure: t if
1220- it has one, else the last of its several. *)
1221-proc lastResult(t: PType): PType;
1222-var f: PObj;
1223-begin
1224- if not t^.tuple then return t; end;
1225- f := t^.fields;
1226- while f^.next # nil do f := f^.next; end;
1227- return f^.typ;
1228-end;
1229-
1230-(* The results of the tuple t but the last: the same fields, one fewer *)
1231-proc withoutLast(t: PType): PType;
1232-var r: PType;
1233-begin
1234- r := Sym.newType(Sym.fRecord, t^.size, t^.align);
1235- r^.tuple := true;
1236- r^.fields := t^.fields;
1237- r^.len := t^.len - 1;
1238- return r;
1239-end;
1240-
1241-(* try c (the report, 7.8): the call c, then the error it returned, its
1242- last result: if that isn't nil, the procedure returns it, and a zero
1243- for each of its other results, after running the deferred statements
1244- in force. x is left c's other results: none (mNone), one (a value) or
1245- several (a tuple, for a multiple assignment). The error is kept in a
1246- slot of the frame, and tested there; the code for it, out of line,
1247- is made with the stack of values as it stands, and leaves it so,
1248- since what follows is the code for an error that is nil. *)
1249-proc tryCall(var x: TItem): ERROR;
1250-var
1251- called: BOOL; c: Gen.CallInfo; start, at: Diag.Pos; res: PType; last: PObj; slot: I64; ok: INT;
1252-begin
1253- start := Scan.tokPos();
1254- Scan.next;
1255- if deferring then return Scan.markAt(Scan.spanFrom(start), "try can't leave a deferred statement"); end;
1256- if curResult = nil then
1257- return Scan.markAt(Scan.spanFrom(start), "try needs a procedure that ends in an ERROR result, and this returns nothing");
1258- elsif lastResult(curResult) # Sym.tError then
1259- return Scan.markAt(Scan.spanFrom(start),
1260- say1("try needs a procedure that ends in an ERROR result, and this returns {}", Sym.typeName(curResult)));
1261- end;
1262- try designator(x, called);
1263- if not called and ((x.mode = Item.mProc)
1264- or (((x.mode = Item.mVar) or (x.mode = Item.mStack)) and (x.typ^.form = Sym.fProc))) then
1265- (* a procedure without parameters, written without parentheses *)
1266- at := x.pos;
1267- try Item.beginCall(c, x);
1268- try Item.endCall(c, x);
1269- x.pos := at;
1270- called := true;
1271- end;
1272- if not called then return Scan.markAt(x.pos, say1("try needs a call, found {}", Item.what(x))); end;
1273- if x.mode = Item.mNone then
1274- return Scan.markAt(x.pos, "try needs a call that returns an ERROR last, and this returns nothing");
1275- end;
1276- if lastResult(x.typ) # Sym.tError then
1277- return Scan.markAt(x.pos, say1("try needs a call that returns an ERROR last, and this returns {}", Sym.typeName(x.typ)));
1278- end;
1279- res := x.typ;
1280- if x.mode = Item.mStack then
1281- (* an ERROR alone *)
1282- slot := Gen.allocTemp(8, 8);
1283- Gen.popVar(Item.frameAdr(slot), 8);
1284- x.mode := Item.mNone; x.typ := Sym.tNone;
1285- elsif x.mode = Item.mWords then
1286- (* two words, the error on top *)
1287- slot := Gen.allocTemp(8, 8);
1288- Gen.popVar(Item.frameAdr(slot), 8);
1289- x.mode := Item.mStack; x.typ := res^.fields^.typ;
1290- else
1291- (* several, in a temporary: the error is where it is *)
1292- last := res^.fields;
1293- while last^.next # nil do last := last^.next; end;
1294- slot := x.off + last^.val;
1295- if res^.len = 2 then try Item.field(x, res^.fields); else x.typ := withoutLast(res); end;
1296- end;
1297- 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);
1303- Gen.fix(ok);
1304- x.pos := Scan.spanFrom(start);
1305- return nil;
1306-end;
1307-
1308-proc factor(var x: TItem; want: PType): ERROR;
1309-var called, vol, several: BOOL; t: PType; start: Diag.Pos; s: []U8;
1310-begin
1311- several := passOn;
1312- passOn := false;
1313- start := Scan.tokPos();
1314- match Scan.tok of
1315- | sInt, sChar:
1316- (* only a hex number can be above high(I64), and it is a U64 *)
1317- if Scan.ival < 0 then Item.makeConst(x, Sym.tU64, Scan.ival); else Item.makeConst(x, Sym.tConst, Scan.ival); end;
1318- Scan.next;
1319- | sReal:
1320- Item.makeReal(x, Scan.rval);
1321- Item.usesReals(Scan.tokPos());
1322- Scan.next;
1323- | sString:
1324- Item.makeStr(x);
1325- Scan.next;
1326- | sIdent:
1327- try designator(x, called);
1328- if x.mode = Item.mNone then
1329- if lastCalled # nil then s := nameOf(lastCalled^.name); else s := "this procedure"; end;
1330- return Scan.markAt(x.pos, say1("{} returns nothing", s));
1331- end;
1332- if x.typ^.tuple and not several then
1333- if lastCalled # nil then s := nameOf(lastCalled^.name); else s := "this procedure"; end;
1334- return Scan.markHelp(x.pos, say1("{} returns several results", s),
1335- say1("they go to variables: a, b := {}(...)", s));
1336- end;
1337- | sLparen:
1338- Scan.next;
1339- try expression(x, want);
1340- try expect(Scan.sRparen);
1341- | sTry:
1342- try tryCall(x);
1343- if x.mode = Item.mNone then return Scan.markAt(x.pos, "this try has no value"); end;
1344- if x.typ^.tuple then
1345- return Scan.markHelp(x.pos, "this try has several values", "they go to variables: a, b := try f(...)");
1346- end;
1347- | sNot:
1348- Scan.next;
1349- try factor(x, nil);
1350- try Item.notOp(x);
1351- | sTilde:
1352- Scan.next;
1353- try factor(x, nil);
1354- try Item.complement(x);
1355- | sLbrak: try arrayLiteral(x, want);
1356- | sLbrace:
1357- if (want # nil) and (want^.form = Sym.fRecord) then try recordLiteral(x, want);
1358- else try setLiteral(x, want);
1359- end;
1360- | sArrow:
1361- Scan.next;
1362- vol := Scan.tok = Scan.sVolatile;
1363- if vol then Scan.next; end;
1364- t := try parseType();
1365- t := newPtr(t, vol);
1366- try expect(Scan.sLparen);
1367- try expression(x, nil);
1368- try expect(Scan.sRparen);
1369- try Item.convert(x, t);
1370- (* a conversion is a factor, not a designator: nothing selects from it *)
1371- if Scan.tok = Scan.sArrow then
1372- return Scan.markHelp(Scan.tokPos(), "a conversion can't be dereferenced",
1373- "convert into a pointer variable, then dereference that");
1374- end;
1375- | else: return expected("an expression");
1376- end;
1377- x.pos := Scan.spanFrom(start);
1378- return nil;
1379-end;
1380-
1381-proc isMulOp: BOOL;
1382-begin
1383- match Scan.tok of
1384- | sTimes, sSlash, sDiv, sMod, sAmp, sShl, sShr: return true;
1385- | else: return false;
1386- end;
1387-end;
1388-
1389-proc isAddOp: BOOL;
1390-begin
1391- match Scan.tok of
1392- | sPlus, sMinus, sBar, sXor: return true;
1393- | else: return false;
1394- end;
1395-end;
1396-
1397-proc isRelOp: BOOL;
1398-begin
1399- match Scan.tok of
1400- | sEql, sNeq, sLss, sLeq, sGtr, sGeq, sIn: return true;
1401- | else: return false;
1402- end;
1403-end;
1404-
1405-proc term(var x: TItem; want: PType): ERROR;
1406-var op: Scan.Sym; y: TItem; L: INT; start: Diag.Pos;
1407-begin
1408- start := Scan.tokPos();
1409- try factor(x, want);
1410- while isMulOp() do
1411- op := Scan.tok;
1412- Scan.next;
1413- try Item.op1(op, x, L);
1414- try factor(y, nil);
1415- try Item.op2(op, x, y, L);
1416- x.pos := Scan.spanFrom(start);
1417- end;
1418- return nil;
1419-end;
1420-
1421-proc simpleExpr(var x: TItem; want: PType): ERROR;
1422-var op: Scan.Sym; y: TItem; L: INT; start: Diag.Pos;
1423-begin
1424- start := Scan.tokPos();
1425- if Scan.tok = Scan.sMinus then
1426- Scan.next;
1427- try term(x, nil);
1428- x.pos := Scan.spanFrom(start);
1429- try Item.neg(x);
1430- else
1431- try term(x, want);
1432- end;
1433- while isAddOp() do
1434- op := Scan.tok;
1435- Scan.next;
1436- try Item.op1(op, x, L);
1437- try term(y, nil);
1438- try Item.op2(op, x, y, L);
1439- x.pos := Scan.spanFrom(start);
1440- end;
1441- return nil;
1442-end;
1443-
1444-proc relation(var x: TItem; want: PType): ERROR;
1445-var op: Scan.Sym; y: TItem; L: INT;
1446-begin
1447- try simpleExpr(x, want);
1448- if isRelOp() then
1449- op := Scan.tok;
1450- Scan.next;
1451- try Item.op1(op, x, L);
1452- if op = Scan.sIn then try simpleExpr(y, nil); else try simpleExpr(y, x.typ); end;
1453- try Item.op2(op, x, y, L);
1454- x.pos := Diag.join(x.pos, y.pos);
1455- end;
1456- return nil;
1457-end;
1458-
1459-(* and binds tighter than or, and both below the relations *)
1460-proc conjunct(var x: TItem; want: PType): ERROR;
1461-var y: TItem; L: INT; start: Diag.Pos;
1462-begin
1463- start := Scan.tokPos();
1464- try relation(x, want);
1465- while Scan.tok = Scan.sAnd do
1466- Scan.next;
1467- try Item.op1(Scan.sAnd, x, L);
1468- try relation(y, nil);
1469- try Item.op2(Scan.sAnd, x, y, L);
1470- x.pos := Scan.spanFrom(start);
1471- end;
1472- return nil;
1473-end;
1474-
1475-proc expression(var x: TItem; want: PType): ERROR;
1476-var y: TItem; L: INT; start: Diag.Pos;
1477-begin
1478- start := Scan.tokPos();
1479- try conjunct(x, want);
1480- while Scan.tok = Scan.sOr do
1481- Scan.next;
1482- try Item.op1(Scan.sOr, x, L);
1483- try conjunct(y, nil);
1484- try Item.op2(Scan.sOr, x, y, L);
1485- x.pos := Scan.spanFrom(start);
1486- end;
1487- return nil;
1488-end;
1489-
1490-(* Statements *)
1491-
1492-proc enterLoop(var lp: Loop; var old: PLoop);
1493-begin
1494- lp.brk := Gen.NoLabel;
1495- lp.base := numDefers;
1496- old := curLoop;
1497- curLoop := ADR(lp);
1498-end;
1499-
1500-(* Runs the deferred statements in force above base, newest first. *)
1501-proc runDefers(base: INT);
1502-var i: INT;
1503-begin
1504- for i := numDefers - 1 to base by -1 do Gen.runDefer(defers[i]); end;
1505-end;
1506-
1507-(* Whether what follows "then" is a lone "break;", with no deferred
1508- statement to run on the way out of the loop: the break must be the
1509- branch's last statement, so ";" and then end, elsif or else follow. *)
1510-proc loneBreak: BOOL;
1511-var st: Scan.State; lone: BOOL;
1512-begin
1513- if (Scan.tok # Scan.sBreak) or (curLoop = nil) or (numDefers # curLoop^.base) then return false; end;
1514- Scan.saveScan(st);
1515- lone := false;
1516- Scan.next;
1517- if Scan.tok = Scan.sSemicolon then
1518- Scan.next;
1519- lone := (Scan.tok = Scan.sEnd) or (Scan.tok = Scan.sElsif) or (Scan.tok = Scan.sElse);
1520- end;
1521- Scan.restoreScan(st);
1522- return lone;
1523-end;
1524-
1525-(* The condition x of if or elsif, and the statements it guards, which
1526- L skips when it is false. "if c then break; end" is one jump out of
1527- the loop when c holds, not one past a jump out. *)
1528-proc thenPart(var x: TItem; var L: INT): ERROR;
1529-begin
1530- try expect(Scan.sThen);
1531- L := Gen.NoLabel; (* stays so with a lone break: there is nothing to skip *)
1532- if loneBreak() then
1533- Chunk.noteLine(Scan.curLine(), Scan.curCol()); (* the jump gets the break's line *)
1534- try Item.condJumpTrue(x, curLoop^.brk);
1535- Scan.next; Scan.next; (* skip "break" and ";" *)
1536- ends := true;
1537- else
1538- try Item.condJump(x, L);
1539- try statements();
1540- end;
1541- return nil;
1542-end;
1543-
1544-(* if, elsif and else: each condition's jump skips its branch to the
1545- next; each branch that doesn't end jumps to the end. A branch that
1546- ends, in return or break, needs no jump past the others, and all of
1547- them ending is told to the caller in the global ends. *)
1548-proc ifStatement(start: Diag.Pos; ind: INT): ERROR;
1549-var x: TItem; L, endL: INT; all: BOOL;
1550-begin
1551- Scan.next;
1552- try expression(x, nil);
1553- try thenPart(x, L);
1554- all := ends;
1555- endL := Gen.NoLabel;
1556- while Scan.tok = Scan.sElsif do
1557- if not ends then Gen.jump(endL); end;
1558- Gen.fix(L);
1559- Scan.next;
1560- try expression(x, nil);
1561- try thenPart(x, L);
1562- all := all and ends;
1563- end;
1564- if Scan.tok = Scan.sElse then
1565- if not ends then Gen.jump(endL); end;
1566- Gen.fix(L);
1567- Scan.next;
1568- if Scan.tok = Scan.sIf then elseIf := true; end;
1569- try statements();
1570- all := all and ends;
1571- else
1572- Gen.fix(L);
1573- all := false;
1574- end;
1575- try closeEnd(start, ind);
1576- Gen.fix(endL);
1577- ends := all;
1578- return nil;
1579-end;
1580-
1581-(* while c do s end: the test comes after the body, and the loop jumps to
1582- it first, so that a round takes one jump, back to the top if c holds:
1583-
1584- jmp test rather than top: c, jump to out if false
1585- top: s s
1586- test: c, jump to top if true jmp top
1587- out:
1588-
1589- One pass reads c before s: so c is compiled where it is written, for
1590- its messages, and its code taken back (rewind); then read again, and
1591- compiled, after s (saveScan, restoreScan). *)
1592-proc whileStatement(start: Diag.Pos; ind: INT): ERROR;
1593-var
1594- x: TItem; top, L, test: INT; lp: Loop; old: PLoop; cond, after: Scan.State; m: Gen.CodeMark;
1595-begin
1596- Scan.next;
1597- Scan.saveScan(cond);
1598- Gen.markCode(m);
1599- try expression(x, nil);
1600- try Item.discard(x);
1601- Gen.rewind(m);
1602- try expect(Scan.sDo);
1603- test := Gen.NoLabel;
1604- Gen.jump(test);
1605- Gen.alignLoop();
1606- top := Chunk.pc;
1607- enterLoop(lp, old);
1608- try statements();
1609- curLoop := old;
1610- Scan.saveScan(after);
1611- Scan.restoreScan(cond);
1612- Gen.fix(test);
1613- Chunk.noteLine(Scan.curLine(), Scan.curCol());
1614- try expression(x, nil);
1615- ends := (x.mode = Item.mConst) and (x.val # 0) and (lp.brk = Gen.NoLabel); (* while true *)
1616- if (x.mode = Item.mConst) and (x.typ^.form = Sym.fBool) then
1617- if x.val # 0 then Gen.jumpBack(top); end;
1618- else
1619- L := Gen.NoLabel;
1620- try Item.condJumpTrue(x, L);
1621- Gen.fixTo(L, top);
1622- end;
1623- Scan.restoreScan(after);
1624- try closeEnd(start, ind);
1625- Gen.fix(lp.brk);
1626- return nil;
1627-end;
1628-
1629-proc repeatStatement: ERROR;
1630-var x: TItem; top, L: INT; lp: Loop; old: PLoop;
1631-begin
1632- Scan.next;
1633- top := Chunk.pc;
1634- enterLoop(lp, old);
1635- try statements();
1636- curLoop := old;
1637- try expect(Scan.sUntil);
1638- try expression(x, nil);
1639- ends := (x.mode = Item.mConst) and (x.val = 0) and (lp.brk = Gen.NoLabel); (* until false *)
1640- L := Gen.NoLabel;
1641- try Item.condJump(x, L);
1642- Gen.fixTo(L, top);
1643- Gen.fix(lp.brk);
1644- return nil;
1645-end;
1646-
1647-(* for v := a to b by s do ... end, laid out as
1648- v := a; the limit b, in a slot unless it is a constant
1649- if v is past b then goto exit
1650- goto body
1651- top: v := v + s
1652- body: the statements
1653- the end of a round: goto top, or exit (forNext)
1654- exit:
1655- so that a round of a loop by 1 takes one compare and one jump. *)
1656-proc forStatement(start: Diag.Pos; ind: INT): ERROR;
1657-var
1658- o: PObj; v, a, b, s: TItem; step: I64; top, body, bodyL, exitL: INT;
1659- lp: Loop; old: PLoop; f: Sym.Form; slot: I64;
1660-begin
1661- Scan.next;
1662- if Scan.tok # Scan.sIdent then return expected("a name"); end;
1663- o := Sym.lookup(Scan.id);
1664- if o = nil then
1665- notDeclared(Scan.tokPos(), Scan.id);
1666- return Scan.Failed;
1667- end;
1668- named(o);
1669- if o^.cls # Sym.oVar then return Scan.mark(say1("{} isn't a variable", nameOf(Scan.id))); end;
1670- f := o^.typ^.form;
1671- if (f # Sym.fInt) and (f # Sym.fEnum) then
1672- return Scan.mark(say1("a for loop needs an integer or enumeration variable, found {}", Sym.typeName(o^.typ)));
1673- end;
1674- Scan.next;
1675- try expect(Scan.sBecomes);
1676- try Item.makeItem(v, o);
1677- try expression(a, o^.typ);
1678- try Item.coerceExact(a, o^.typ, "");
1679- try Item.assign(v, a);
1680- try expect(Scan.sTo);
1681- try expression(b, o^.typ);
1682- try Item.coerceExact(b, o^.typ, "");
1683- (* the limit, evaluated once: a constant as it is, else in a slot *)
1684- if b.mode # Item.mConst then
1685- slot := try Item.toSlot(b);
1686- Item.tempItem(b, b.typ, slot);
1687- end;
1688- step := 1;
1689- if Scan.tok = Scan.sBy then
1690- Scan.next;
1691- try expression(s, nil);
1692- step := try constValue(s);
1693- if step = 0 then return Scan.markAt(s.pos, "the step can't be zero"); end;
1694- end;
1695- try expect(Scan.sDo);
1696- exitL := Gen.NoLabel;
1697- if step > 0 then try Item.forCmp(o, b, Scan.sGtr, exitL); else try Item.forCmp(o, b, Scan.sLss, exitL); end;
1698- bodyL := Gen.NoLabel;
1699- Gen.jump(bodyL);
1700- Gen.alignLoop();
1701- top := Chunk.pc;
1702- try Item.forStep(o, step);
1703- Gen.fix(bodyL);
1704- body := Chunk.pc;
1705- enterLoop(lp, old);
1706- try statements();
1707- curLoop := old;
1708- try closeEnd(start, ind);
1709- try Item.forNext(o, b, step, exitL, top, body);
1710- Gen.fix(exitL);
1711- Gen.fix(lp.brk);
1712- return nil;
1713-end;
1714-
1715-type
1716- Labels = record
1717- lo, hi: [MaxLabels]I64; (* the ranges of the labels so far *)
1718- at: [MaxLabels]INT; (* where the arm of each starts *)
1719- n: INT;
1720- end;
1721-
1722-(* a < b, for values of an integer type, unsigned or not *)
1723-proc below(a, b: I64; unsign: BOOL): BOOL;
1724-begin
1725- if unsign then return U64(a) < U64(b); end;
1726- return a < b;
1727-end;
1728-
1729-(* An arm of a match on an integer of type t: its labels, each a
1730- constant or a range, none overlapping another (report section 7.4),
1731- then its statements. No code tests the labels here; dispatch does,
1732- after the last arm, for which each label notes where its arm starts. *)
1733-proc intArm(t: PType; var ls: Labels; var endL: INT): ERROR;
1734-var lo, hi: TItem; first, i: INT; u: BOOL; start: Diag.Pos;
1735-begin
1736- u := not t^.signed;
1737- first := ls.n;
1738- repeat
1739- start := Scan.tokPos();
1740- try expression(lo, t);
1741- try Item.coerce(lo, t);
1742- _ := try constValue(lo);
1743- hi := lo;
1744- if Scan.tok = Scan.sUpto then
1745- Scan.next;
1746- try expression(hi, t);
1747- try Item.coerce(hi, t);
1748- _ := try constValue(hi);
1749- if below(hi.val, lo.val, u) then return Scan.markAt(Scan.spanFrom(start), "the range is empty"); end;
1750- end;
1751- for i := 0 to ls.n - 1 do
1752- if not below(hi.val, ls.lo[i], u) and not below(ls.hi[i], lo.val, u) then
1753- if lo.val = hi.val then
1754- return Scan.markAt(Scan.spanFrom(start), say1("{} is in another label too", Diag.source(Scan.spanFrom(start))));
1755- end;
1756- return Scan.markAt(Scan.spanFrom(start), say1("{} overlaps another label", Diag.source(Scan.spanFrom(start))));
1757- end;
1758- end;
1759- if ls.n >= MaxLabels then
1760- return Scan.markAt(Scan.spanFrom(start), tooMany(MaxLabels, "labels in one match"));
1761- end;
1762- ls.lo[ls.n] := lo.val; ls.hi[ls.n] := hi.val;
1763- INC(ls.n);
1764- if Scan.tok # Scan.sComma then break; end;
1765- Scan.next;
1766- until false;
1767- try expect(Scan.sColon);
1768- for i := first to ls.n - 1 do ls.at[i] := Chunk.pc; end;
1769- try statements();
1770- Gen.jump(endL);
1771- return nil;
1772-end;
1773-
1774-const
1775- MinTable = 4; (* fewer labels are tested one by one *)
1776- TableDensity = 8; (* a table has at most this many entries to a label *)
1777-
1778-(* The code that picks the arm, after the last one, which the match's
1779- start jumped to: label by label, as a chain of compares each to its
1780- arm; or, for four or more labels not far apart, a jump table (jumpTable),
1781- which takes the same few instructions for any of them. It is here and
1782- not before the arms, since a table can only be made once every arm's
1783- place is known; an arm is entered by a jump back to it. elseAt is where
1784- the else arm starts, or NoLabel. *)
1785-proc dispatch(t: PType; p: I64; var ls: Labels; elseAt: INT; var endL: INT);
1786-var
1787- lo, hi: I64; i, start, v, body: INT; u: BOOL;
1788- entry: [MaxLabels]INT;
1789-begin
1790- u := (t^.form = Sym.fInt) and not t^.signed;
1791- lo := 0; hi := 0;
1792- if ls.n > 0 then
1793- lo := ls.lo[0]; hi := ls.hi[0];
1794- for i := 1 to ls.n - 1 do
1795- if below(ls.lo[i], lo, u) then lo := ls.lo[i]; end;
1796- if below(hi, ls.hi[i], u) then hi := ls.hi[i]; end;
1797- end;
1798- end;
1799- if (ls.n >= MinTable) and (lo >= -2147483648) and (lo <= 2147483647)
1800- and (U64(hi - lo) < U64(TableDensity * ls.n)) and (hi - lo < MaxLabels) then
1801- start := Gen.jumpTable(p, lo, INT(hi - lo) + 1, elseAt, endL);
1802- for v := 0 to INT(hi - lo) do
1803- if elseAt # Gen.NoLabel then entry[v] := elseAt; else entry[v] := start; end;
1804- end;
1805- for i := 0 to ls.n - 1 do
1806- for v := INT(ls.lo[i] - lo) to INT(ls.hi[i] - lo) do entry[v] := ls.at[i]; end;
1807- end;
1808- for v := 0 to INT(hi - lo) do Gen.tableEntry(start, entry[v]); end;
1809- return;
1810- end;
1811- for i := 0 to ls.n - 1 do
1812- body := Gen.NoLabel;
1813- Item.matchRange(p, ls.lo[i], ls.hi[i], body);
1814- Gen.fixTo(body, ls.at[i]);
1815- end;
1816- if elseAt # Gen.NoLabel then Gen.jumpBack(elseAt); end;
1817-end;
1818-
1819-proc matchStatement(start: Diag.Pos; ind: INT): ERROR;
1820-var
1821- x: TItem; t: PType; c, f, o: PObj; p: I64; L, endL, n, first, disp, elseAt: INT;
1822- seen: [256]BOOL; hasElse, all, byValue: BOOL; endAt: Diag.Pos; ls: Labels;
1823-begin
1824- Scan.next;
1825- try expression(x, nil);
1826- if x.typ^.form = Sym.fConst then try Item.coerce(x, Sym.tI64); end;
1827- p := try Item.matchBegin(x);
1828- t := x.typ;
1829- try expect(Scan.sOf);
1830- hasElse := false;
1831- all := true;
1832- endL := Gen.NoLabel;
1833- ls.n := 0;
1834- (* an integer or an enumeration is matched by its value, and the arms
1835- are picked by dispatch, after them; a variant by its tag, arm by arm *)
1836- byValue := (t^.form = Sym.fInt) or (t^.form = Sym.fEnum);
1837- disp := Gen.NoLabel;
1838- elseAt := Gen.NoLabel;
1839- if byValue then Gen.jump(disp); end;
1840- while Scan.tok = Scan.sBar do
1841- Scan.next;
1842- if hasElse then return Scan.mark("else must be the last arm"); end;
1843- if Scan.tok = Scan.sElse then
1844- Scan.next;
1845- try expect(Scan.sColon);
1846- elseAt := Chunk.pc;
1847- try statements();
1848- if byValue then Gen.jump(endL); end;
1849- hasElse := true;
1850- elsif t^.form = Sym.fInt then
1851- try intArm(t, ls, endL);
1852- else
1853- first := ls.n;
1854- L := Gen.NoLabel;
1855- repeat
1856- if Scan.tok # Scan.sIdent then return expected("a case"); end;
1857- c := t^.fields;
1858- while (c # nil) and (c^.name # Scan.id) do c := c^.next; end;
1859- if c = nil then
1860- return Scan.mark(say2("{} isn't a case of {}", nameOf(Scan.id), Sym.typeName(t)));
1861- end;
1862- if (c^.val <= 255) and seen[c^.val] then
1863- return Scan.mark(say1("{} has two arms", nameOf(c^.name)));
1864- end;
1865- if c^.val <= 255 then seen[c^.val] := true; end;
1866- Scan.next;
1867- if t^.form # Sym.fEnum then
1868- Item.matchTag(p, c^.val, L);
1869- break;
1870- end;
1871- (* an enumeration's arm may name several, which share its place *)
1872- ls.lo[ls.n] := c^.val; ls.hi[ls.n] := c^.val;
1873- INC(ls.n);
1874- if Scan.tok # Scan.sComma then break; end;
1875- Scan.next;
1876- until false;
1877- try Sym.openScope(Sym.newScope());
1878- if Scan.tok = Scan.sLparen then
1879- Scan.next;
1880- f := c^.fields;
1881- n := 0;
1882- repeat
1883- if Scan.tok # Scan.sIdent then return expected("a name"); end;
1884- if f = nil then
1885- return Scan.mark(say1("more names than {} has fields", nameOf(c^.name)));
1886- end;
1887- o := Sym.newObj(Sym.oVar, Scan.id, f^.typ);
1888- o^.lev := 1; o^.ind := true; o^.isVar := true;
1889- o^.val := p; o^.off := f^.val;
1890- try declare(o);
1891- f := f^.next;
1892- INC(n);
1893- Scan.next;
1894- if Scan.tok # Scan.sComma then break; end;
1895- Scan.next;
1896- until false;
1897- if f # nil then
1898- return Scan.mark(say1("name all the fields of {}, or none", nameOf(c^.name)));
1899- end;
1900- try expect(Scan.sRparen);
1901- end;
1902- try expect(Scan.sColon);
1903- for n := first to ls.n - 1 do ls.at[n] := Chunk.pc; end;
1904- try statements();
1905- Sym.closeScope();
1906- Gen.jump(endL);
1907- if t^.form # Sym.fEnum then Gen.fix(L); end;
1908- end;
1909- all := all and ends;
1910- end;
1911- endAt := Scan.tokPos();
1912- try closeEnd(start, ind);
1913- ends := all;
1914- if (t^.form = Sym.fInt) and not hasElse then
1915- return Scan.markHelp(endAt, "a match on an integer needs an else arm", "it may be empty: | else:");
1916- end;
1917- if not hasElse then
1918- c := t^.fields;
1919- while c # nil do
1920- if (c^.val > 255) or not seen[c^.val] then
1921- return Scan.markAt(endAt, say1("no arm for {}", nameOf(c^.name)));
1922- end;
1923- c := c^.next;
1924- end;
1925- end;
1926- if byValue then
1927- Gen.fix(disp);
1928- dispatch(t, p, ls, elseAt, endL);
1929- end;
1930- Gen.fix(endL);
1931- return nil;
1932-end;
1933-
1934-(* What a message calls x: its name n when x is just that name, else what
1935- it is. *)
1936-proc subject(x: TItem; n: INT): []U8;
1937-begin
1938- if x.pos.b - x.pos.a = LEN(nameOf(n)) then return nameOf(n); end;
1939- if x.mode = Item.mConst then return "a constant"; end;
1940- return "a value";
1941-end;
1942-
1943-(* x, named first n, is a variable the program may assign: not an
1944- array constant, nor any part of one. *)
1945-proc assignable(x: TItem; n: INT): ERROR;
1946-begin
1947- if (x.mode = Item.mConst) and (subject(x, n) = nameOf(n)) then
1948- return Scan.markAt(x.pos, say1("{} is a constant, and can't be changed", nameOf(n)));
1949- end;
1950- if (x.mode = Item.mVar) and (x.obj # nil) and (x.obj^.cls = Sym.oConst) then
1951- return Scan.markAt(x.pos, say1("{} is a constant, and can't be changed", nameOf(x.obj^.name)));
1952- end;
1953- if (x.mode # Item.mVar) or not x.isVar then
1954- return Scan.markAt(x.pos, say1("can't assign to {}", subject(x, n)));
1955- end;
1956- return nil;
1957-end;
1958-
1959-(* The designator a statement starts with. A variable named whole
1960- before := is assigned, not read: naming it there leaves it as unread
1961- as it was. *)
1962-proc leftSide(var x: TItem; var called: BOOL): ERROR;
1963-var o: PObj; wasRead: BOOL; n: INT;
1964-begin
1965- n := Scan.id;
1966- o := Sym.lookup(n);
1967- wasRead := (o # nil) and o^.read;
1968- try designator(x, called);
1969- if ((Scan.tok = Scan.sBecomes) or (Scan.tok = Scan.sComma)) and (x.pos.b - x.pos.a = LEN(nameOf(n))) then
1970- o^.read := wasRead;
1971- end;
1972- return nil;
1973-end;
1974-
1975-(* a, b := f(x): the variables first, left to right, then the call;
1976- then each result to its variable, in order. x is the first variable,
1977- first its name, blank whether it is _. *)
1978-proc multiAssign(var x: TItem; first: INT; blank: BOOL): ERROR;
1979-var
1980- d: [16]TItem; dn: [16]INT; blanks: [16]BOOL;
1981- y, z: TItem; n, i: INT; called: BOOL; f: PObj;
1982-begin
1983- n := 0;
1984- d[0] := x;
1985- dn[0] := first;
1986- blanks[0] := blank;
1987- repeat
1988- if not blanks[n] then
1989- try Item.notReadOnly(d[n]);
1990- try assignable(d[n], dn[n]);
1991- try Item.pin(d[n]); (* works out the address now, so that the call can't change it *)
1992- end;
1993- INC(n);
1994- if Scan.tok # Scan.sComma then break; end;
1995- if n > 15 then return Scan.mark(tooMany(16, "variables in one assignment")); end;
1996- Scan.next;
1997- blanks[n] := Scan.tok = Scan.sBlank;
1998- if blanks[n] then
1999- Scan.next;
2000- else
2001- dn[n] := Scan.id;
2002- try leftSide(d[n], called);
2003- end;
2004- until false;
2005- try expect(Scan.sBecomes);
2006- if Scan.tok = Scan.sTry then
2007- try tryCall(y);
2008- called := true;
2009- else
2010- try designator(y, called);
2011- end;
2012- if not called or not y.typ^.tuple or (y.typ^.len # I64(n)) then
2013- return Scan.markAt(y.pos, Diag.say("expected a call with {} results", [Fmt.int(n)]));
2014- end;
2015- (* two results on the stack: the first is brought to the top, and each
2016- is popped into its variable in turn, as one value; else each is
2017- read from the temporary they came back in *)
2018- if y.mode = Item.mWords then Gen.swap(); end;
2019- f := y.typ^.fields;
2020- for i := 0 to n - 1 do
2021- z := y;
2022- if y.mode = Item.mWords then
2023- z.mode := Item.mStack; z.typ := f^.typ;
2024- else
2025- try Item.field(z, f);
2026- end;
2027- if blanks[i] then
2028- try Item.discard(z);
2029- else
2030- try Item.coerceExact(z, d[i].typ, "several results go to variables of just their types");
2031- try Item.assign(d[i], z);
2032- end;
2033- f := f^.next;
2034- end;
2035- return nil;
2036-end;
2037-
2038-(* return a, b; or return f(x); with f's several results passed on *)
2039-proc returnResults: ERROR;
2040-var f: PObj; x: TItem;
2041-begin
2042- f := curResult^.fields;
2043- passOn := true;
2044- while f # nil do
2045- try expression(x, f^.typ);
2046- if x.typ^.tuple then
2047- if not Sym.same(x.typ, curResult) then
2048- return Scan.markAt(x.pos, say2("expected the results {}, found {}", Sym.typeName(curResult), Sym.typeName(x.typ)));
2049- end;
2050- return Item.returnAll(x);
2051- end;
2052- try Item.returnField(f, x);
2053- f := f^.next;
2054- if f # nil then try expect(Scan.sComma); end;
2055- end;
2056- return nil;
2057-end;
2058-
2059-(* defer s: s is compiled where it stands, as a little subroutine of the
2060- procedure, jumped over; each way out of the statement list calls it. *)
2061-proc deferStatement: ERROR;
2062-var L, pos, saved: INT; oldLoop: PLoop; oldDeferring: BOOL; start: Diag.Pos;
2063-begin
2064- start := Scan.tokPos();
2065- Scan.next;
2066- if directDefer then return Scan.markAt(Scan.spanFrom(start), "defer can't be deferred"); end;
2067- if numDefers >= MaxDefers then
2068- return Scan.markAt(Scan.spanFrom(start), tooMany(MaxDefers, "deferred statements in one procedure"));
2069- end;
2070- L := Gen.NoLabel;
2071- pos, saved := Gen.deferBegin(L);
2072- oldLoop := curLoop; oldDeferring := deferring;
2073- curLoop := nil;
2074- deferring := true;
2075- directDefer := true;
2076- try statement();
2077- directDefer := false;
2078- curLoop := oldLoop; deferring := oldDeferring;
2079- Gen.deferEnd(L, saved);
2080- defers[numDefers] := pos;
2081- INC(numDefers);
2082- return nil;
2083-end;
2084-
2085-(* Whether the expression of x := ..., which starts at the current
2086- symbol, is x changed by adding to it, taking from it or its bits:
2087- x + e, x - e, x | e or x xor e, with x nowhere in e, so that it can be
2088- worked out in x's own register, if x is in one (Gen's inPlace). *)
2089-proc changesItself(x: TItem): BOOL;
2090-var st: Scan.State; wasSkipping, changes: BOOL; d: INT;
2091-begin
2092- if (x.mode # Item.mVar) or (x.base # Gen.bReg) or (x.typ^.form = Sym.fSlice)
2093- or (Scan.tok # Scan.sIdent) or (Scan.id # x.obj^.name) then
2094- return false;
2095- end;
2096- changes := false;
2097- Scan.saveScan(st);
2098- wasSkipping := Scan.skipping;
2099- Scan.setSkipping(true); (* its slips are told when it is compiled *)
2100- Scan.next;
2101- if isAddOp() then
2102- changes := true;
2103- d := 0;
2104- while not ((d = 0) and ((Scan.tok = Scan.sSemicolon) or (Scan.tok = Scan.sEnd))) and (Scan.tok # Scan.sEof) do
2105- if (Scan.tok = Scan.sIdent) and (Scan.id = x.obj^.name) then changes := false; end;
2106- match Scan.tok of
2107- | sLparen, sLbrak, sLbrace: INC(d);
2108- | sRparen, sRbrak, sRbrace: DEC(d);
2109- | else:
2110- end;
2111- Scan.next;
2112- end;
2113- end;
2114- Scan.restoreScan(st);
2115- Scan.setSkipping(wasSkipping);
2116- return changes;
2117-end;
2118-
2119-(* A call standing on its own, which drops the results x holds, if any,
2120- to be warned of *)
2121-proc noteDrop(x: TItem);
2122-begin
2123- if (x.mode # Item.mNone) and (numDrops < MaxDrops) then
2124- drops[numDrops].at := x.pos;
2125- if x.typ^.tuple then drops[numDrops].n := INT(x.typ^.len); else drops[numDrops].n := 1; end;
2126- INC(numDrops);
2127- end;
2128-end;
2129-
2130-proc oneStatement: ERROR;
2131-var
2132- x, y: TItem; called: BOOL; m: I64; c: Gen.CallInfo; start: Diag.Pos; first, n, i: INT; k: Gen.Kind;
2133-begin
2134- start := Scan.tokPos();
2135- first := Scan.id;
2136- Chunk.noteLine(Scan.curLine(), Scan.curCol());
2137- m := Gen.tempMark();
2138- ends := false;
2139- match Scan.tok of
2140- | sIdent:
2141- try leftSide(x, called);
2142- if Scan.tok = Scan.sBecomes then
2143- try Item.notReadOnly(x);
2144- try assignable(x, first);
2145- Scan.next;
2146- if changesItself(x) then Gen.setInPlace(x.chunk); end;
2147- try expression(y, x.typ);
2148- Gen.setInPlace(-1);
2149- try Item.assign(x, y);
2150- elsif Scan.tok = Scan.sComma then
2151- try multiAssign(x, first, false);
2152- elsif not called then
2153- if (x.mode = Item.mProc)
2154- or (((x.mode = Item.mVar) or (x.mode = Item.mStack)) and (x.typ^.form = Sym.fProc)) then
2155- try Item.beginCall(c, x);
2156- try Item.endCall(c, x);
2157- try Item.discard(x);
2158- elsif Scan.tok = Scan.sEql then
2159- return Scan.markHelp(x.pos, say1("{} isn't a statement", subject(x, first)), "assignment is written :=");
2160- else
2161- return Scan.markAt(x.pos, say1("{} isn't a statement", subject(x, first)));
2162- end;
2163- else
2164- noteDrop(x);
2165- try Item.discard(x);
2166- end;
2167- | sBlank:
2168- Scan.next;
2169- if Scan.tok = Scan.sComma then
2170- try multiAssign(x, 0, true);
2171- else
2172- try expect(Scan.sBecomes);
2173- try expression(x, nil);
2174- (* evaluated and dropped: a single value is loaded, so that a
2175- volatile one is read *)
2176- if (x.mode = Item.mType) or (x.mode = Item.mBuiltin) or (x.mode = Item.mNone) or (x.mode = Item.mCase)
2177- or ((x.mode # Item.mStr) and not Sym.isAggregate(x.typ)) then
2178- try Item.value(x);
2179- end;
2180- try Item.discard(x);
2181- end;
2182- | sIf: try ifStatement(start, Scan.indent());
2183- | sWhile: try whileStatement(start, Scan.indent());
2184- | sRepeat: try repeatStatement();
2185- | sFor: try forStatement(start, Scan.indent());
2186- | sMatch: try matchStatement(start, Scan.indent());
2187- | sReturn:
2188- Scan.next;
2189- if deferring then return Scan.markAt(Scan.spanFrom(start), "return can't leave a deferred statement"); end;
2190- if Scan.tok = Scan.sSemicolon then
2191- runDefers(0);
2192- try Item.returnNone();
2193- else
2194- if (curResult # nil) and curResult^.tuple then
2195- try returnResults();
2196- else
2197- try expression(x, curResult);
2198- try Item.returnValue(x);
2199- end;
2200- (* the result, one value or two words on top, waits in the frame
2201- while the deferred statements run *)
2202- if (numDefers > 0) and (curResult # nil) and not Sym.behindPointer(curResult) then
2203- n := 1; k := Gen.kindOf(curResult);
2204- if Sym.inTwoRegs(curResult) then n := 2; k := Gen.kWord; end;
2205- if deferSlot = 0 then deferSlot := Gen.allocPerm(16, 8); end;
2206- for i := n - 1 to 0 by -1 do Gen.popVar(Item.frameAdr(deferSlot + I64(8 * i)), 8); end;
2207- runDefers(0);
2208- for i := 0 to n - 1 do Gen.pushVar(Item.frameAdr(deferSlot + I64(8 * i)), 8, false, k); end;
2209- else
2210- runDefers(0);
2211- end;
2212- Gen.returnJump();
2213- ends := true;
2214- end;
2215- | sBreak:
2216- Scan.next;
2217- if curLoop = nil then return Scan.markAt(Scan.spanFrom(start), "break outside a loop"); end;
2218- runDefers(curLoop^.base);
2219- Gen.jump(curLoop^.brk);
2220- | sDefer: try deferStatement();
2221- | sTry:
2222- try tryCall(x);
2223- noteDrop(x);
2224- try Item.discard(x);
2225- | sArrow:
2226- return Scan.markHelp(Scan.tokPos(), "a statement starts with a name",
2227- "convert into a pointer variable, then assign through that");
2228- | else:
2229- if Scan.atLineStart() then
2230- return endMissing(Scan.missingPos(), say1("expected \"end\", found {}", Scan.found()));
2231- end;
2232- return expected("a statement");
2233- end;
2234- Gen.releaseTemps(m);
2235- return nil;
2236-end;
2237-
2238-proc statement: ERROR;
2239-var r: Recover; m: I64; err: ERROR;
2240-begin
2241- m := Gen.tempMark();
2242- guard(r);
2243- err := oneStatement();
2244- if err = nil then
2245- skipped := false;
2246- else
2247- restore(r);
2248- (* a statement never starts a line: this is the next declaration *)
2249- if Scan.atLineStart() or not skipConstruct() then return giveUp(r); end;
2250- Gen.releaseTemps(m);
2251- skipped := true;
2252- end;
2253- unguard(r);
2254- return nil;
2255-end;
2256-
2257-proc endsStatements: BOOL;
2258-begin
2259- match Scan.tok of
2260- | sEnd, sElse, sElsif, sUntil, sBar, sEof: return true;
2261- | else: return false;
2262- end;
2263-end;
2264-
2265-proc statements: ERROR;
2266-var base: INT; old: BOOL;
2267-begin
2268- base := numDefers;
2269- old := directDefer;
2270- directDefer := false;
2271- ends := false;
2272- while not endsStatements() do
2273- try statement();
2274- if not skipped or (Scan.tok = Scan.sSemicolon) then try expect(Scan.sSemicolon); end;
2275- end;
2276- runDefers(base);
2277- numDefers := base;
2278- directDefer := old;
2279- return nil;
2280-end;
2281-
2282-(* Declarations *)
2283-
2284-(* In a file read for its interface only: skip a procedure's body, from
2285- its local declarations to the end that closes it. *)
2286-proc skipBody: ERROR;
2287-var d: INT; sawBegin: BOOL;
2288-begin
2289- d := 0;
2290- sawBegin := false;
2291- repeat
2292- match Scan.tok of
2293- | sBegin:
2294- if d = 0 then sawBegin := true; end;
2295- INC(d);
2296- | sIf, sWhile, sFor, sMatch, sRecord, sVariant: INC(d);
2297- | sEnd:
2298- DEC(d);
2299- if (d = 0) and sawBegin then
2300- Scan.next;
2301- return nil;
2302- end;
2303- | sEof: return expected("\"end\"");
2304- | else:
2305- end;
2306- Scan.next;
2307- until false;
2308- return nil;
2309-end;
2310-
2311-proc declarations(top: BOOL); forward;
2312-
2313-(* How Rt shows a variable of o's type in the trap report: 1 a signed
2314- integer, 2 an unsigned one, 3 a BOOL, 4 an address, 5 a real; plus
2315- its size times 16, and 256 if the frame holds its address, or 512
2316- times 1 + i if it is in register ShownRegs[i]; 0 if it isn't shown. *)
2317-proc varKind(o: PObj): INT;
2318-var k, i, v: INT;
2319-begin
2320- match o^.typ^.form of
2321- | fInt: if o^.typ^.signed then k := 1; else k := 2; end;
2322- | fEnum, fSet: k := 2;
2323- | fBool: k := 3;
2324- | fPtr, fProc, fError: k := 4;
2325- | fReal: k := 5;
2326- | else: return 0;
2327- end;
2328- v := k + INT(o^.typ^.size) * 16;
2329- if o^.ind then v := v + 256; end;
2330- for i := 0 to LEN(Gen.ShownRegs) - 1 do
2331- if o^.reg = Gen.ShownRegs[i] then v := k + INT(o^.typ^.size) * 16 + (i + 1) * 512; end;
2332- end;
2333- return v;
2334-end;
2335-
2336-(* Whether variable o could live in registers: a single value, a real
2337- in an xmm register, or a slice, in two, that isn't C's *)
2338-proc regFit(o: PObj): BOOL;
2339-var f: Sym.Form;
2340-begin
2341- if (o^.cls # Sym.oVar) or o^.ind or o^.ext then return false; end;
2342- f := o^.typ^.form;
2343- return (f = Sym.fInt) or (f = Sym.fBool) or (f = Sym.fEnum) or (f = Sym.fPtr) or (f = Sym.fProc)
2344- or (f = Sym.fError) or (f = Sym.fSlice) or (f = Sym.fReal)
2345- or ((f = Sym.fSet) and (o^.typ^.size <= 8));
2346-end;
2347-
2348-(* The first local of the procedure being compiled. Locals are chained
2349- by chain in the order declared, the module's own first; before is the
2350- last one declared before the procedure's, or nil if there was none. *)
2351-proc firstLocal(before: PObj): PObj;
2352-begin
2353- if before = nil then return Sym.curModule^.locals; end;
2354- return before^.chain;
2355-end;
2356-
2357-const MaxCand = 64; (* variables of a procedure that may go in registers *)
2358-
2359-var
2360- cand: [MaxCand]PObj; (* chooseRegs's candidates and their weights *)
2361- weight: [MaxCand]INT;
2362- numCand: INT;
2363-
2364-proc candidate(n: INT): INT;
2365-var j: INT;
2366-begin
2367- for j := 0 to numCand - 1 do
2368- if cand[j]^.name = n then return j; end;
2369- end;
2370- return -1;
2371-end;
2372-
2373-proc addCandidate(o: PObj);
2374-begin
2375- if regFit(o) and (numCand < MaxCand) then
2376- cand[numCand] := o;
2377- weight[numCand] := 0;
2378- INC(numCand);
2379- end;
2380-end;
2381-
2382-(* Whether naming o may make a call: a procedure, a procedure variable,
2383- or NEW, SYSCALL or COPY, which use the registers a call would *)
2384-proc calls(o: PObj): BOOL;
2385-begin
2386- if o = nil then return false; end;
2387- return (o^.cls = Sym.oProc) or ((o^.cls = Sym.oVar) and (o^.typ^.form = Sym.fProc))
2388- or ((o^.cls = Sym.oBuiltin) and ((o^.val = Sym.bNew) or (o^.val = Sym.bSyscall) or (o^.val = Sym.bCopy)));
2389-end;
2390-
2391-(* Puts the busiest variables of the procedure, whose parameters are
2392- params and whose locals follow before, in registers: read ahead from
2393- its "begin" to its end, a use counts 1, in a loop 4, in two 16, in
2394- three or more 64, and a variable ADR is taken of can't have one. A register costs a save
2395- and a restore, so a variable used less than three times keeps its
2396- place in memory. A slice takes two, its pointer's and its length's;
2397- a real one of the xmm registers, stored and loaded again around each
2398- call, as System V keeps none through one. In a procedure that names no procedure, so calls nothing, the
2399- parameters that arrive in the registers no call needs stay there
2400- (keepArrived), at no cost. *)
2401-proc chooseRegs(params, before: PObj);
2402-var
2403- isLoop: [256]BOOL;
2404- i, k, kx, d, loops, best, need: INT; o, q, qual: PObj; st: Scan.State;
2405- afterDot, wasSkipping, leaf: BOOL;
2406-begin
2407- numCand := 0;
2408- o := params;
2409- while o # nil do addCandidate(o); o := o^.next; end;
2410- o := firstLocal(before);
2411- while o # nil do addCandidate(o); o := o^.chain; end;
2412- if numCand = 0 then return; end;
2413- Scan.saveScan(st);
2414- wasSkipping := Scan.skipping;
2415- Scan.setSkipping(true); (* its slips are told when it is compiled *)
2416- d := 0; loops := 0; afterDot := false; leaf := true; qual := nil;
2417- 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;
2427- end;
2428- match Scan.tok of
2429- | sBegin, sIf, sMatch, sWhile, sFor, sRepeat:
2430- if d < 255 then
2431- INC(d);
2432- isLoop[d] := (Scan.tok = Scan.sWhile) or (Scan.tok = Scan.sFor) or (Scan.tok = Scan.sRepeat);
2433- if isLoop[d] then INC(loops); end;
2434- end;
2435- | sEnd, sUntil:
2436- if isLoop[d] then DEC(loops); end;
2437- DEC(d);
2438- | sIdent:
2439- if Scan.id = nameAdr then
2440- Scan.next;
2441- if Scan.tok = Scan.sLparen then Scan.next; end;
2442- (* a hugely negative weight bars it from a register, whatever
2443- its uses add *)
2444- if (Scan.tok = Scan.sIdent) and (candidate(Scan.id) >= 0) then weight[candidate(Scan.id)] := -1073741824; end;
2445- elsif not afterDot and (candidate(Scan.id) >= 0) then
2446- k := candidate(Scan.id);
2447- if loops > 2 then INC(weight[k], 64); else INC(weight[k], 1 shl (2 * loops)); end;
2448- end;
2449- | else:
2450- end;
2451- afterDot := Scan.tok = Scan.sPeriod; (* a name after a dot is a field, not a variable *)
2452- if (d > 0) and (Scan.tok # Scan.sEof) then Scan.next; end;
2453- until (d = 0) or (Scan.tok = Scan.sEof);
2454- Scan.restoreScan(st);
2455- Scan.setSkipping(wasSkipping);
2456- if leaf then
2457- o := params;
2458- while o # nil do
2459- k := candidate(o^.name);
2460- if (k >= 0) and (weight[k] >= 0) then Gen.keepArrived(o); end; (* a candidate whose ADR isn't taken *)
2461- o := o^.next;
2462- end;
2463- end;
2464- (* a slice's weight is shared by its two registers *)
2465- for i := 0 to numCand - 1 do
2466- if cand[i]^.typ^.form = Sym.fSlice then weight[i] := weight[i] div 2; end;
2467- end;
2468- (* the heaviest, each used at least three times a register, take the
2469- five registers in turn, while there are enough for each, and the
2470- reals the four xmm registers of XVarRegs *)
2471- k := 0; kx := 0;
2472- repeat
2473- best := -1;
2474- for i := 0 to numCand - 1 do
2475- if (cand[i]^.reg = 0) and (weight[i] >= 3) and ((best < 0) or (weight[i] > weight[best])) then best := i; end;
2476- end;
2477- if best < 0 then break; end;
2478- need := 1;
2479- if cand[best]^.typ^.form = Sym.fSlice then need := 2; end;
2480- if cand[best]^.typ^.form = Sym.fReal then
2481- if kx < 4 then
2482- cand[best]^.reg := Gen.XVarRegs[kx];
2483- INC(kx);
2484- else
2485- weight[best] := 0;
2486- end;
2487- elsif k + need <= 5 then
2488- cand[best]^.reg := Gen.VarRegs[k];
2489- if need = 2 then cand[best]^.reg2 := Gen.VarRegs[k + 1]; end;
2490- INC(k, need);
2491- else
2492- weight[best] := 0; (* too big for what is left *)
2493- end;
2494- until false;
2495-end;
2496-
2497-(* The registers the variables of the procedure are in, as bits: bit i
2498- is VarRegs[i], bit XBit + i XVarRegs[i] *)
2499-proc regBits(o: PObj): INT;
2500-var m, k: INT;
2501-begin
2502- m := 0;
2503- for k := 0 to 4 do
2504- if (o^.reg = Gen.VarRegs[k]) or (o^.reg2 = Gen.VarRegs[k]) then m := m | (1 shl k); end;
2505- end;
2506- for k := 0 to 3 do
2507- if o^.reg = Gen.XVarRegs[k] then m := m | (1 shl (Gen.XBit + k)); end;
2508- end;
2509- return m;
2510-end;
2511-
2512-proc regsOf(params, before: PObj): INT;
2513-var o: PObj; m: INT;
2514-begin
2515- m := 0;
2516- o := params;
2517- while o # nil do
2518- m := m | regBits(o);
2519- o := o^.next;
2520- end;
2521- o := firstLocal(before);
2522- while o # nil do
2523- if o^.cls = Sym.oVar then m := m | regBits(o); end;
2524- o := o^.chain;
2525- end;
2526- return m;
2527-end;
2528-
2529-(* Gives each local not in a register its slot in the frame, the slots
2530- the prologue zeroes, and then tells Gen which registers the
2531- variables are in. A variable in a register has no slot: it starts at
2532- zero in its register, and the trap report finds it there. *)
2533-proc placeLocals(params, before: PObj);
2534-var o: PObj;
2535-begin
2536- Gen.resetLocals();
2537- o := firstLocal(before);
2538- while o # nil do
2539- if (o^.cls = Sym.oVar) and (o^.reg = 0) then
2540- o^.val := Gen.allocPerm(o^.typ^.size, o^.typ^.align);
2541- elsif (o^.cls = Sym.oVar) and (o^.reg >= Gen.XmmVar) then
2542- o^.val := Gen.allocPerm(8, 8);
2543- Gen.xHome(o^.reg, o^.val);
2544- end;
2545- o := o^.chain;
2546- end;
2547- o := params;
2548- while o # nil do
2549- if o^.reg >= Gen.XmmVar then Gen.xHome(o^.reg, o^.val); end;
2550- o := o^.next;
2551- end;
2552- Gen.useRegs(regsOf(params, before));
2553-end;
2554-
2555-proc body(p: PObj; sig: PType; line: INT): ERROR;
2556-var
2557- q, params, last, o, before: PObj; old: PType; st: Scan.State;
2558- mark: Gen.CodeMark; drops0, errs: INT;
2559-begin
2560- try Sym.openScope(Sym.newScope());
2561- params := nil; last := nil;
2562- q := sig^.fields;
2563- while q # nil do
2564- o := Sym.newObj(Sym.oVar, q^.name, q^.typ);
2565- o^.pos := q^.pos;
2566- o^.lev := 1;
2567- o^.isVar := q^.isVar;
2568- o^.param := true;
2569- if last = nil then params := o; else last^.next := o; end;
2570- last := o;
2571- q := q^.next;
2572- end;
2573- Item.beginProc(sig, params);
2574- deferSlot := 0;
2575- o := params;
2576- while o # nil do
2577- q := o^.next;
2578- try declare(o);
2579- o := q;
2580- end;
2581- curProc := p;
2582- before := Sym.curModule^.lastLocal;
2583- declarations(false);
2584- chooseRegs(params, before);
2585- placeLocals(params, before);
2586- (* the body, made again if a variable in a register must be in memory *)
2587- Scan.saveScan(st);
2588- Gen.markCode(mark); drops0 := numDrops; errs := Diag.errors;
2589- old := curResult;
2590- repeat
2591- Item.setDemoted(false);
2592- try expect(Scan.sBegin);
2593- curResult := sig^.base;
2594- Gen.enterBody(p^.chunk, line);
2595- stray := false; elseIf := false; deferSlot := 0;
2596- try statements();
2597- p^.openEnd := (curResult # nil) and not ends;
2598- Chunk.noteLine(Scan.curLine(), Scan.curCol());
2599- try expect(Scan.sEnd);
2600- if not (Item.demoted or Gen.lost) or (Diag.errors # errs) then break; end;
2601- (* a parameter kept where it arrived goes to memory: a call or a copy
2602- wanted its register *)
2603- if Gen.lost then
2604- o := params;
2605- while o # nil do
2606- if Gen.keptIn(o) then o^.reg := 0; o^.reg2 := 0; end;
2607- o := o^.next;
2608- end;
2609- end;
2610- numDrops := drops0;
2611- Gen.redo(mark);
2612- placeLocals(params, before);
2613- Scan.restoreScan(st);
2614- until false;
2615- try Gen.endProc(p^.chunk, p^.openEnd);
2616- (* its parameters and variables, for the trap report *)
2617- o := firstLocal(before);
2618- q := params;
2619- while q # nil do
2620- if varKind(q) # 0 then Chunk.noteVar(p^.chunk, q^.name, INT(q^.val), varKind(q)); end;
2621- q := q^.next;
2622- end;
2623- while o # nil do
2624- if (o^.cls = Sym.oVar) and (varKind(o) # 0) then Chunk.noteVar(p^.chunk, o^.name, INT(o^.val), varKind(o)); end;
2625- o := o^.chain;
2626- end;
2627- curResult := old;
2628- curProc := nil;
2629- Sym.closeScope();
2630- return nil;
2631-end;
2632-
2633-(* An integer constant in a code procedure, for the assembler: a whole
2634- expression, or a single factor where an expression would read on
2635- too far *)
2636-proc asmConst(whole: BOOL): (I64, ERROR);
2637-var x: TItem;
2638-begin
2639- if whole then return constExpr(); end;
2640- try factor(x, nil);
2641- if not Sym.isInt(x.typ) then
2642- return 0, Scan.markAt(x.pos, say1("expected an integer constant, found {}", Item.what(x)));
2643- end;
2644- return constValue(x);
2645-end;
2646-
2647-proc codeBody(p: PObj; sig: PType; at: Diag.Pos): ERROR;
2648-var q: PObj; ni, nf: INT;
2649-begin
2650- ni := 0; nf := 0;
2651- q := sig^.fields;
2652- while q # nil do
2653- if not q^.isVar and (q^.typ^.form = Sym.fSlice) then
2654- INC(ni, 2); (* address, then length *)
2655- else
2656- if not q^.isVar and not Sym.isScalar(q^.typ) then
2657- return Scan.markAt(at, "a code procedure takes integers, BOOL, reals, pointers, procedures and slices");
2658- end;
2659- if (q^.typ^.form = Sym.fReal) and not q^.isVar then INC(nf); else INC(ni); end;
2660- end;
2661- q := q^.next;
2662- end;
2663- if (ni > 6) or (nf > 8) or sig^.variadic then
2664- return Scan.markAt(at, "too many parameters for a code procedure");
2665- end;
2666- if sig^.base # nil then
2667- if sig^.base^.tuple then
2668- q := sig^.base^.fields;
2669- if (sig^.base^.len # 2) or (q^.typ^.size # 8) or (q^.next^.typ^.size # 8)
2670- or not Sym.isScalar(q^.typ) or not Sym.isScalar(q^.next^.typ)
2671- or (q^.typ^.form = Sym.fReal) or (q^.next^.typ^.form = Sym.fReal) then
2672- return Scan.markAt(at, "a code procedure returns two results only in rax and rdx");
2673- end;
2674- elsif not Sym.isScalar(sig^.base) and (sig^.base^.form # Sym.fSlice) then
2675- return Scan.markAt(at, "a code procedure returns a single value");
2676- end;
2677- end;
2678- try Gen.codeProc(p^.chunk, asmConst);
2679- return expect(Scan.sEnd);
2680-end;
2681-
2682-proc procDecl: ERROR;
2683-var n, line: INT; exp: BOOL; sig: PType; p: PObj; at: Diag.Pos;
2684-begin
2685- try instancesFor(false);
2686- line := Scan.curLine();
2687- Scan.next;
2688- try identDef(n, exp, at);
2689- sig := try signature();
2690- try expect(Scan.sSemicolon);
2691- p := Sym.find(Sym.topScope(), n);
2692- if (p # nil) and (p^.cls = Sym.oProc) and p^.fwd then
2693- if not Sym.same(p^.typ, sig) then
2694- Diag.error(at, say1("{} doesn't have the signature it was declared forward with", nameOf(n)));
2695- Diag.note(p^.pos, "the signature is here");
2696- return Scan.Failed;
2697- end;
2698- if Scan.tok = Scan.sForward then return Scan.mark(say1("{} is declared forward twice", nameOf(n))); end;
2699- p^.exported := p^.exported or exp;
2700- else
2701- p := Sym.newObj(Sym.oProc, n, sig);
2702- p^.pos := at;
2703- p^.exported := exp;
2704- if (Sym.curModule^.name = nameRt) and not checkMode and (n = nameFail) then
2705- p^.chunk := Gen.rtFail;
2706- else
2707- p^.chunk := Chunk.newChunk(Chunk.secText, Sym.curModule^.sname, n);
2708- end;
2709- try declare(p);
2710- end;
2711- if Scan.tok = Scan.sForward then
2712- Scan.next;
2713- p^.fwd := true;
2714- return nil;
2715- end;
2716- p^.fwd := false;
2717- if Scan.tok = Scan.sCode then
2718- Scan.next;
2719- p^.isCode := true;
2720- try codeBody(p, sig, at);
2721- elsif checkMode then
2722- try skipBody();
2723- else
2724- try body(p, sig, line);
2725- end;
2726- if Scan.tok = Scan.sIdent then
2727- if Scan.id = Sym.curModule^.name then
2728- return endMissing(Scan.tokPos(), say1("{} has no \"end\": this one closes the module", nameOf(n)));
2729- elsif Scan.id # n then
2730- return endMissing(Scan.tokPos(), say2("expected {}, found {}", nameOf(n), nameOf(Scan.id)));
2731- end;
2732- Scan.next;
2733- end;
2734- return nil;
2735-end;
2736-
2737-(* An extern procedure or variable: C's, reached through the quadword
2738- that holds its address. *)
2739-proc externDecl: ERROR;
2740-var n: INT; exp: BOOL; o, q: PObj; t: PType; at: Diag.Pos;
2741-begin
2742- Scan.next;
2743- Sym.curModule^.usesC := true;
2744- if Scan.tok = Scan.sProc then
2745- Scan.next;
2746- try identDef(n, exp, at);
2747- willDeclare(n);
2748- inExtern := true;
2749- t := try signature();
2750- inExtern := false;
2751- q := t^.fields;
2752- while q # nil do
2753- if q^.isVar or not Sym.isScalar(q^.typ) then
2754- return Scan.markAt(at, "C takes integers, BOOL, reals, pointers and procedures");
2755- end;
2756- q := q^.next;
2757- end;
2758- if (t^.base # nil) and not Sym.isScalar(t^.base) then
2759- return Scan.markAt(at, "C returns a single value");
2760- end;
2761- o := Sym.newObj(Sym.oProc, n, t);
2762- else
2763- if Scan.tok # Scan.sVar then return expected("\"proc\" or \"var\""); end;
2764- Scan.next;
2765- try identDef(n, exp, at);
2766- willDeclare(n);
2767- try expect(Scan.sColon);
2768- declExported := exp;
2769- t := try parseType();
2770- declExported := false;
2771- o := Sym.newObj(Sym.oVar, n, t);
2772- end;
2773- o^.pos := at;
2774- o^.exported := exp;
2775- o^.ext := true;
2776- o^.chunk := Chunk.externChunk(n);
2777- return declare(o);
2778-end;
2779-
2780-(* An array or record constant: a literal of constants, which become
2781- the bytes of a read-only chunk, as a string constant's do (report
2782- section 4). An address in it, of a string, an array constant, a
2783- procedure or an ERROR, waits in fixes until the chunk is made, then
2784- is a fixup the linker patches. The bytes are the compiler's own
2785- machine's, little-endian, as the target's are. *)
2786-var
2787- constBytes: ^U8;
2788- fixes: [MaxFixes]record off, chunk: INT; end;
2789- numFixes: INT;
2790-
2791-proc constFix(off, chunk: INT): ERROR;
2792-begin
2793- if numFixes >= MaxFixes then
2794- return Scan.mark(tooMany(MaxFixes, "addresses in one constant"));
2795- end;
2796- fixes[numFixes].off := off;
2797- fixes[numFixes].chunk := chunk;
2798- INC(numFixes);
2799- return nil;
2800-end;
2801-
2802-(* The n bytes of v, at off in the constant: little-endian, as the machine is *)
2803-proc putBytes(off, n: INT; v: I64);
2804-var src: ^U8;
2805-begin
2806- src := ^U8(ADR(v));
2807- COPY(constBytes[off..off + n], src[0..n]);
2808-end;
2809-
2810-(* The part of type t at offset off of the constant *)
2811-proc constPart(t: PType; off: INT): ERROR;
2812-var e: TItem; f: PObj; k: INT; r: F32; start: Diag.Pos; src: ^U8; st: INT;
2813-begin
2814- start := Scan.tokPos();
2815- if (t^.form = Sym.fArray) and (Scan.tok = Scan.sLbrak) then
2816- Scan.next;
2817- k := 0;
2818- if Scan.tok # Scan.sRbrak then
2819- repeat
2820- if I64(k) < t^.len then
2821- try constPart(t^.base, off + k * INT(t^.base^.size));
2822- else
2823- try constPart(t^.base, off);
2824- end;
2825- INC(k);
2826- if Scan.tok # Scan.sComma then break; end;
2827- Scan.next;
2828- until false;
2829- end;
2830- try expect(Scan.sRbrak);
2831- if I64(k) # t^.len then
2832- return Scan.markAt(Scan.spanFrom(start), Diag.say("expected {} elements, found {}", [Fmt.int(t^.len), Fmt.int(k)]));
2833- end;
2834- return nil;
2835- end;
2836- if (t^.form = Sym.fRecord) and not t^.tuple and (Scan.tok = Scan.sLbrace) then
2837- Scan.next;
2838- if Scan.tok # Scan.sRbrace then
2839- repeat
2840- if Scan.tok # Scan.sIdent then return expected("a field"); end;
2841- f := try fieldOf(t);
2842- Scan.next;
2843- try expect(Scan.sColon);
2844- try constPart(f^.typ, off + INT(f^.val));
2845- if Scan.tok # Scan.sComma then break; end;
2846- Scan.next;
2847- until false;
2848- end;
2849- return expect(Scan.sRbrace);
2850- end;
2851- try expression(e, t);
2852- if (e.mode = Item.mStr) and ((t^.form = Sym.fSlice) or (t^.form = Sym.fArray)) and (t^.base = Sym.tU8) then
2853- if t^.form = Sym.fSlice then
2854- try constFix(off, e.chunk);
2855- putBytes(off + 8, 8, e.val);
2856- elsif e.val > t^.len then
2857- return Scan.markAt(e.pos, say1("the string is longer than {}", Sym.typeName(t)));
2858- else
2859- st := Chunk.chunks[e.chunk].start;
2860- COPY(constBytes[off..off + INT(e.val)], Chunk.rodata[st..st + INT(e.val)]);
2861- end;
2862- elsif t^.form = Sym.fSlice then
2863- if (e.mode # Item.mVar) or (e.obj = nil) or (e.obj^.cls # Sym.oConst) or (e.typ^.form # Sym.fArray)
2864- or (e.pos.b - e.pos.a # LEN(nameOf(e.obj^.name))) or not Sym.same(e.typ^.base, t^.base) then
2865- return Scan.markAt(e.pos, say1("a constant slice is a string or an array constant of its elements, found {}", Item.what(e)));
2866- end;
2867- try constFix(off, e.chunk);
2868- putBytes(off + 8, 8, e.typ^.len);
2869- elsif t^.form = Sym.fVariant then
2870- return Scan.markAt(e.pos, "a constant holds no variant");
2871- elsif (t^.form = Sym.fArray) or (t^.form = Sym.fRecord) then
2872- return Scan.markAt(e.pos, say1("expected a literal of {}", Sym.typeName(t)));
2873- else
2874- try Item.coerce(e, t);
2875- if (e.mode = Item.mProc) and not e.obj^.ext then
2876- try constFix(off, e.obj^.chunk);
2877- elsif e.mode # Item.mConst then
2878- return Scan.markAt(e.pos, say1("expected a constant, found {}", Item.what(e)));
2879- elsif (t^.form = Sym.fError) and (e.val > 0) then
2880- try constFix(off, INT(e.val) - 1);
2881- elsif (t^.form = Sym.fPtr) and (e.val # 0) then
2882- return Scan.markAt(e.pos, "a constant pointer is nil");
2883- elsif (t^.form = Sym.fReal) and (t^.size = 4) then
2884- r := F32(Item.realOf(e));
2885- src := ^U8(ADR(r));
2886- COPY(constBytes[off..off + 4], src[0..4]);
2887- else
2888- putBytes(off, INT(t^.size), e.val);
2889- end;
2890- end;
2891- return nil;
2892-end;
2893-
2894-(* The chunk of n, a constant of type t whose literal is next *)
2895-proc aggregateConst(t: PType; n: INT): (INT, ERROR);
2896-var c, i, size: INT;
2897-begin
2898- size := INT(t^.size);
2899- constBytes := Scan.grab(size + 8);
2900- for i := 0 to size + 7 do constBytes[i] := 0; end;
2901- numFixes := 0;
2902- try constPart(t, 0);
2903- c := Chunk.newChunk(Chunk.secRodata, Sym.curModule^.sname, n);
2904- Chunk.setData(c, constBytes, size, INT(t^.align));
2905- for i := 0 to numFixes - 1 do Chunk.addDataFixup(c, fixes[i].off, fixes[i].chunk, 0); end;
2906- return c, nil;
2907-end;
2908-
2909-proc constDecl(top: BOOL): ERROR;
2910-var n, c: INT; exp: BOOL; x: TItem; o: PObj; t: PType; start, at: Diag.Pos;
2911-begin
2912- try identDef(n, exp, at);
2913- willDeclare(n);
2914- t := nil;
2915- if Scan.tok = Scan.sColon then
2916- Scan.next;
2917- start := Scan.tokPos();
2918- t := try parseType();
2919- if (t # Sym.tError) and not ((t^.form = Sym.fArray) or ((t^.form = Sym.fRecord) and not t^.tuple)) then
2920- return Scan.markAt(Scan.spanFrom(start), "only an ERROR, an array or a record constant has a type");
2921- end;
2922- end;
2923- try expect(Scan.sEql);
2924- if (t # nil) and ((t^.form = Sym.fArray) or (t^.form = Sym.fRecord)) then
2925- o := Sym.newObj(Sym.oConst, n, t);
2926- o^.chunk := try aggregateConst(t, n);
2927- o^.pos := at;
2928- o^.exported := exp and top;
2929- try declare(o);
2930- return expect(Scan.sSemicolon);
2931- end;
2932- try expression(x, nil);
2933- o := Sym.newObj(Sym.oConst, n, x.typ);
2934- o^.pos := at;
2935- o^.exported := exp and top;
2936- if t = Sym.tError then
2937- o^.typ := Sym.tError;
2938- c := try Item.errorChunk(x, Sym.curModule^.sname, n);
2939- o^.val := c + 1;
2940- elsif x.mode = Item.mStr then
2941- o^.val := x.val;
2942- o^.chunk := x.chunk;
2943- else
2944- o^.val := try constValue(x);
2945- end;
2946- try declare(o);
2947- return expect(Scan.sSemicolon);
2948-end;
2949-
2950-proc typeDecl(top: BOOL): ERROR;
2951-var n: INT; exp: BOOL; o: PObj; t: PType; at: Diag.Pos;
2952-begin
2953- try identDef(n, exp, at);
2954- willDeclare(n);
2955- try expect(Scan.sEql);
2956- declExported := exp and top;
2957- inTypes := true;
2958- t := try parseType();
2959- o := Sym.newObj(Sym.oType, n, t);
2960- o^.pos := at;
2961- o^.exported := exp and top;
2962- if t^.obj = nil then t^.obj := o; end;
2963- try declare(o);
2964- return expect(Scan.sSemicolon);
2965-end;
2966-
2967-proc varDecl(top: BOOL): ERROR;
2968-var
2969- i, k: INT; o: PObj; t: PType;
2970- names: [MaxNames]INT; exps: [MaxNames]BOOL; poss: [MaxNames]Diag.Pos;
2971-begin
2972- k := 0;
2973- repeat
2974- if k >= MaxNames then return Scan.mark(tooMany(MaxNames, "names in one declaration")); end;
2975- try identDef(names[k], exps[k], poss[k]);
2976- willDeclare(names[k]);
2977- INC(k);
2978- if Scan.tok # Scan.sComma then break; end;
2979- Scan.next;
2980- until false;
2981- try expect(Scan.sColon);
2982- declExported := top and exps[0];
2983- t := try parseType();
2984- declExported := false;
2985- for i := 0 to k - 1 do
2986- o := Sym.newObj(Sym.oVar, names[i], t);
2987- o^.pos := poss[i];
2988- o^.exported := exps[i] and top;
2989- o^.isVar := false;
2990- if top then
2991- o^.lev := 0;
2992- o^.chunk := Chunk.newChunk(Chunk.secBss, Sym.curModule^.sname, names[i]);
2993- Chunk.setBss(o^.chunk, INT(t^.size), INT(t^.align));
2994- else
2995- o^.lev := 1; (* its slot comes from placeLocals, if it needs one *)
2996- end;
2997- try declare(o);
2998- end;
2999- return expect(Scan.sSemicolon);
3000-end;
3001-
3002-(* After a procedure had an error: its name is poison if it wasn't
3003- declared, and reading goes on after the "end Name;" that closes it,
3004- or at the next procedure if that is missing *)
3005-proc skipProc;
3006-var st: Scan.State;
3007-begin
3008- Scan.next;
3009- if (Scan.tok = Scan.sIdent) and (Sym.find(Sym.topScope(), Scan.id) = nil) then poison(Scan.id); end;
3010- repeat
3011- repeat Scan.next; until Scan.atLineStart() or (Scan.tok = Scan.sEof);
3012- match Scan.tok of
3013- | sProc, sExtern, sEof: return;
3014- | sEnd:
3015- Scan.saveScan(st);
3016- Scan.next;
3017- if Scan.tok = Scan.sIdent then Scan.next; end;
3018- if Scan.tok = Scan.sSemicolon then
3019- Scan.next;
3020- return;
3021- end;
3022- Scan.restoreScan(st);
3023- return;
3024- | else:
3025- end;
3026- until false;
3027-end;
3028-
3029-(* What one declaration, of the kind k, reads *)
3030-proc declarationOf(k: Scan.Sym; top: BOOL): ERROR;
3031-begin
3032- match k of
3033- | sConst: return constDecl(top);
3034- | sType: return typeDecl(top);
3035- | sVar: return varDecl(top);
3036- | sProc:
3037- if not top then return Scan.mark("procedures don't nest"); end;
3038- try procDecl();
3039- return expect(Scan.sSemicolon);
3040- | sExtern:
3041- if not top then return Scan.mark("extern is only for the top of a module"); end;
3042- try externDecl();
3043- return expect(Scan.sSemicolon);
3044- | else: return nil;
3045- end;
3046-end;
3047-
3048-(* One declaration, as a recovery point: an error is reported, the
3049- declaration skipped, and reading goes on after it *)
3050-proc declaration(k: Scan.Sym; top: BOOL);
3051-var r: Recover;
3052-begin
3053- guard(r);
3054- numDeclaring := 0;
3055- if declarationOf(k, top) # nil then
3056- restore(r);
3057- if k = Scan.sProc then skipProc(); else skipDeclaration(); end;
3058- end;
3059- unguard(r);
3060-end;
3061-
3062-proc declarations(top: BOOL);
3063-var i: INT; o: PObj; k: Scan.Sym;
3064-begin
3065- repeat
3066- k := Scan.tok;
3067- match k of
3068- | sConst, sVar:
3069- Scan.next;
3070- while Scan.tok = Scan.sIdent do declaration(k, top); end;
3071- | sType:
3072- Scan.next;
3073- numFwd := 0;
3074- while Scan.tok = Scan.sIdent do declaration(Scan.sType, top); end;
3075- inTypes := false;
3076- for i := 0 to numFwd - 1 do
3077- o := Sym.lookup(fwdTypes[i]^.fwd);
3078- if (o = nil) or (o^.cls # Sym.oType) then
3079- notDeclared(fwdPos[i], fwdTypes[i]^.fwd);
3080- fwdTypes[i]^.base := Sym.tPoison;
3081- else
3082- fwdTypes[i]^.base := o^.typ;
3083- named(o);
3084- end;
3085- fwdTypes[i]^.fwd := -1;
3086- end;
3087- | sProc, sExtern: declaration(k, top);
3088- | else: return;
3089- end;
3090- until false;
3091-end;
3092-
3093-(* Modules *)
3094-
3095-(* Whether m is module n with these arguments. *)
3096-proc isModule(m: PModule; n: INT; args: Sym.Args): BOOL;
3097-var i: INT;
3098-begin
3099- if (m^.name # n) or (m^.args.n # args.n) then return false; end;
3100- for i := 0 to args.n - 1 do
3101- if (m^.args.o[i] # args.o[i]) or not Sym.same(m^.args.t[i], args.t[i]) then return false; end;
3102- end;
3103- return true;
3104-end;
3105-
3106-proc findModule(n: INT; args: Sym.Args): PModule;
3107-var m: PModule;
3108-begin
3109- m := firstModule;
3110- while (m # nil) and not isModule(m, n, args) do m := m^.next; end;
3111- return m;
3112-end;
3113-
3114-(* The arguments of an instance: types, or procedures named. *)
3115-proc parseArgs(var args: Sym.Args; mname: []U8): ERROR;
3116-var o: PObj; start: Diag.Pos;
3117-begin
3118- Scan.next;
3119- repeat
3120- if args.n >= 8 then return Scan.mark(say1("too many type arguments for {}", mname)); end;
3121- args.o[args.n] := nil;
3122- start := Scan.tokPos();
3123- if Scan.tok = Scan.sIdent then
3124- o := try qualIdent();
3125- if o^.cls = Sym.oProc then
3126- args.o[args.n] := o;
3127- elsif o^.cls # Sym.oType then
3128- return Scan.markAt(Scan.spanFrom(start), say1("{} isn't a type or a procedure", nameOf(o^.name)));
3129- end;
3130- args.t[args.n] := o^.typ;
3131- else
3132- args.t[args.n] := try parseType();
3133- end;
3134- args.pos[args.n] := Scan.spanFrom(start);
3135- INC(args.n);
3136- if Scan.tok # Scan.sComma then break; end;
3137- Scan.next;
3138- until false;
3139- return expect(Scan.sRparen);
3140-end;
3141-
3142-(* Past an instance's arguments, to be read when it is made *)
3143-proc skipArgs: ERROR;
3144-var p: INT;
3145-begin
3146- p := 0;
3147- repeat
3148- if Scan.tok = Scan.sLparen then
3149- INC(p);
3150- elsif Scan.tok = Scan.sRparen then
3151- DEC(p);
3152- elsif (Scan.tok = Scan.sSemicolon) or (Scan.tok = Scan.sEof) then
3153- return expected("\")\"");
3154- end;
3155- Scan.next;
3156- until p = 0;
3157- return nil;
3158-end;
3159-
3160-(* A generic module's parameters, bound to the instance's arguments: a
3161- type parameter names its type, a procedure parameter its procedure.
3162- The instance's name is the module's with its arguments, List(I64). *)
3163-proc moduleParams(m: PModule): ERROR;
3164-var i: INT; o, a: PObj; sig: PType; s: Buf.Buf; at: Diag.Pos; text: []U8;
3165-begin
3166- Buf.init(ADR(s), Heap.heap);
3167- i := 0;
3168- Buf.str(ADR(s), nameOf(m^.name));
3169- Buf.add(ADR(s), '(');
3170- Scan.next;
3171- repeat
3172- if Scan.tok # Scan.sIdent then return expected("a name"); end;
3173- if i >= m^.args.n then
3174- return Scan.markAt(m^.args.at, say2("{} needs a type for {}", nameOf(m^.name), nameOf(Scan.id)));
3175- end;
3176- if m^.args.o[i] # nil then
3177- return Scan.markAt(m^.args.pos[i], say2("{} needs a type for {}", nameOf(m^.name), nameOf(Scan.id)));
3178- end;
3179- o := Sym.newObj(Sym.oType, Scan.id, m^.args.t[i]);
3180- o^.used := true; (* a parameter of the module, not a declaration *)
3181- try declare(o);
3182- Buf.str(ADR(s), Sym.typeName(m^.args.t[i]));
3183- Buf.add(ADR(s), ',');
3184- INC(i);
3185- Scan.next;
3186- if Scan.tok # Scan.sComma then break; end;
3187- Scan.next;
3188- until false;
3189- while Scan.tok = Scan.sSemicolon do
3190- Scan.next;
3191- if Scan.tok # Scan.sIdent then return expected("a name"); end;
3192- at := Scan.tokPos();
3193- o := Sym.newObj(Sym.oProc, Scan.id, nil);
3194- Scan.next;
3195- try expect(Scan.sColon);
3196- try expect(Scan.sProc);
3197- sig := try signature();
3198- if i >= m^.args.n then
3199- return Scan.markAt(m^.args.at, say2("{} needs a procedure for {}", nameOf(m^.name), nameOf(o^.name)));
3200- end;
3201- a := m^.args.o[i];
3202- if a = nil then
3203- return Scan.markAt(m^.args.pos[i], say2("{} needs a procedure for {}", nameOf(m^.name), nameOf(o^.name)));
3204- end;
3205- if not Sym.same(a^.typ, sig) then
3206- Diag.error(m^.args.pos[i], say2("{} doesn't have the signature of {}", nameOf(a^.name), nameOf(o^.name)));
3207- Diag.note(at, "the signature is here");
3208- Diag.finish();
3209- end;
3210- o^.typ := a^.typ; o^.chunk := a^.chunk; o^.isCode := a^.isCode; o^.ext := a^.ext;
3211- o^.used := true;
3212- try declare(o);
3213- Buf.str(ADR(s), nameOf(a^.home^.name));
3214- Buf.add(ADR(s), '.');
3215- Buf.str(ADR(s), nameOf(a^.name));
3216- Buf.add(ADR(s), ',');
3217- INC(i);
3218- end;
3219- try expect(Scan.sRparen);
3220- if i # m^.args.n then
3221- return Scan.markAt(m^.args.at, say1("too many type arguments for {}", nameOf(m^.name)));
3222- end;
3223- text := Buf.bytes(ADR(s));
3224- text[LEN(text) - 1] := ')';
3225- m^.sname := internName(text);
3226- Buf.done(ADR(s));
3227- return nil;
3228-end;
3229-
3230-(* Warns of o if it is never used, or a variable only assigned. What
3231- is exported may be used elsewhere, and a name that starts with _ says
3232- it is meant to go unused. Writing a var parameter, a match's name for
3233- a field or C's variable is what it is for. *)
3234-proc warn(o: PObj);
3235-var s, t: []U8;
3236-begin
3237- s := nameOf(o^.name);
3238- if (o^.cls = Sym.oProc) and o^.openEnd then
3239- Diag.warning(o^.pos, say1("{} may reach its end without return, and then returns zero", s));
3240- end;
3241- if o^.exported or (s[0] = '_') then return; end;
3242- if o^.used and (o^.read or (o^.cls # Sym.oVar) or o^.isVar or o^.ext) then return; end;
3243- match o^.cls of
3244- | oConst: t := say1("constant {}", s);
3245- | oType: t := say1("type {}", s);
3246- | oVar:
3247- if o^.param then t := say1("parameter {}", s); else t := say1("variable {}", s); end;
3248- | oProc: t := say1("procedure {}", s);
3249- | oModule: t := say1("module {}", s);
3250- | else: return;
3251- end;
3252- if o^.used then
3253- Diag.warning(o^.pos, say1("{} is assigned but never read", t));
3254- elsif o^.cls = Sym.oModule then
3255- Diag.warning(o^.pos, say1("{} is imported but never used", t));
3256- else
3257- Diag.warning(o^.pos, say1("{} is never used", t));
3258- end;
3259- if not o^.used and (o^.param or o^.ind) then
3260- Diag.help(say1("if it must be there, call it _{}", s));
3261- end;
3262-end;
3263-
3264-(* Warns of the call at p, which drops its n results *)
3265-proc dropped(p: Diag.Pos; n: INT);
3266-var s, blanks: []U8; i: INT;
3267-begin
3268- s := Diag.source(p);
3269- i := 0;
3270- while (i < LEN(s)) and (s[i] # '(') do INC(i); end;
3271- if i < LEN(s) then s := s[0..i]; end;
3272- blanks := "_";
3273- for i := 2 to n do blanks := say1("{}, _", blanks); end;
3274- if n = 1 then
3275- Diag.warning(p, say1("the result of {} is dropped", s));
3276- else
3277- Diag.warning(p, say1("the results of {} are dropped", s));
3278- end;
3279- Diag.help(say2("if that is meant, write {} := {}(...)", blanks, s));
3280-end;
3281-
3282-(* The warnings of module m, by where each declaration is: its own
3283- declarations and its procedures' are two lists, each in order, and
3284- firstDrop on are the calls that drop results. The
3285- instances of a generic module share its text, and so its warnings:
3286- only the first is warned of. *)
3287-proc warnings(m: PModule; firstDrop: INT);
3288-var a, b: PObj; n: PModule; i: INT;
3289-begin
3290- n := firstModule;
3291- while (n # nil) and (n^.name # m^.name) do n := n^.next; end;
3292- if n # nil then return; end;
3293- a := m^.first; b := m^.locals;
3294- i := firstDrop;
3295- while (a # nil) or (b # nil) or (i < numDrops) do
3296- if (i < numDrops) and ((a = nil) or (drops[i].at.a < a^.pos.a)) and ((b = nil) or (drops[i].at.a < b^.pos.a)) then
3297- dropped(drops[i].at, drops[i].n);
3298- INC(i);
3299- elsif (b = nil) or ((a # nil) and (a^.pos.a < b^.pos.a)) then
3300- warn(a);
3301- a := a^.chain;
3302- else
3303- warn(b);
3304- b := b^.chain;
3305- end;
3306- end;
3307-end;
3308-
3309-(* Modules being compiled, not yet finished: for finding a cycle. *)
3310-var
3311- pending: [MaxPending]PModule;
3312- numPending: INT;
3313-
3314-proc exists(path: []U8): BOOL;
3315-var info: Sys.Info; err: INT;
3316-begin
3317- info, err := Sys.info(path);
3318- return (err = 0) and info.file;
3319-end;
3320-
3321-(* Which file path is, as its device and inode: two names of one file
3322- have the same. Zero for a file that can't be asked about. *)
3323-proc identity(path: []U8): (INT, INT);
3324-var a: [4096]U8; st: [18]INT; (* struct stat: st_dev, then st_ino *)
3325-begin
3326- if LEN(path) >= 4096 then return 0, 0; end;
3327- COPY(a[0..LEN(path)], path);
3328- a[LEN(path)] := 0;
3329- if SYSCALL(4, ADR(a[0]), ADR(st)) < 0 then return 0, 0; end;
3330- return st[0], st[1];
3331-end;
3332-
3333-(* s, in memory that is never freed, for what must outlast the buffer it is in *)
3334-proc keep(s: []U8): []U8;
3335-var p: ^U8;
3336-begin
3337- if LEN(s) = 0 then return ""; end;
3338- p := Scan.grab(LEN(s));
3339- COPY(p[0..LEN(s)], s);
3340- return p[0..LEN(s)];
3341-end;
3342-
3343-proc importModule(name: INT; args: Sym.Args): (PModule, ERROR); forward;
3344-
3345-(* Compiles module n from path, an instance if args are given, or only
3346- reads its interface if checkOnly; returns it. An import calls this in
3347- the middle of reading another file, so it is re-entrant: it saves the
3348- scanner's state, the open scopes, the current module and file and
3349- whether checks are on, and puts them back at the end. *)
3350-proc compileFile(path: []U8; n: INT; args: Sym.Args; checkOnly: BOOL): (PModule, ERROR);
3351-var
3352- st: Scan.State; saved: [Sym.MaxDepth]INT; d: INT;
3353- oldMod: PModule; oldCheck, oldChecks: BOOL; m: PModule;
3354- lib: ^Sym.Lib; start: Diag.Pos; alias, mname, line, oldPath: INT; o: PObj; bodyChunk: INT; iargs: Sym.Args;
3355- generic: BOOL; argsAt: Scan.State; why: []U8; firstDrop: INT;
3356-begin
3357- firstDrop := numDrops;
3358- Scan.saveScan(st);
3359- d := Sym.saveScopes(saved[0..Sym.MaxDepth]);
3360- oldMod := Sym.curModule; oldCheck := checkMode; oldPath := Chunk.curFilePath(); oldChecks := Item.checks;
3361- Item.setChecks(true);
3362- Chunk.setCurFile(internName(path));
3363- why := Scan.open(path);
3364- if LEN(why) # 0 then Diag.fatal(say2("can't read {}: {}", path, why)); end;
3365- NEW(m, Heap.heap);
3366- m^.name := n;
3367- m^.sname := n;
3368- m^.args := args;
3369- m^.scope := Sym.newScope();
3370- m^.path := path;
3371- m^.body := -1;
3372- m^.checkOnly := checkOnly;
3373- Sym.setCurModule(m);
3374- checkMode := checkOnly;
3375- if not checkOnly then
3376- if numPending >= MaxPending then
3377- return nil, Scan.mark(tooMany(MaxPending, "imports nested deep"));
3378- end;
3379- pending[numPending] := m;
3380- INC(numPending);
3381- end;
3382- try Sym.openScope(m^.scope);
3383- Scan.next;
3384- try expect(Scan.sModule);
3385- if (Scan.tok # Scan.sIdent) or (Scan.id # n) then
3386- return nil, Scan.mark(say2("expected module {}, found {}", nameOf(n), Scan.found()));
3387- end;
3388- Scan.next;
3389- (* the module first pending is the one named on the command line,
3390- which nothing imports, so no arguments come with it *)
3391- if (Scan.tok = Scan.sLparen) and not checkOnly and (numPending = 1) then
3392- return nil, Scan.mark(say1("{} is generic: it is compiled where a module imports it", nameOf(n)));
3393- elsif Scan.tok = Scan.sLparen then
3394- try moduleParams(m);
3395- elsif args.n > 0 then
3396- return nil, Scan.markAt(args.at, say1("{} isn't generic", nameOf(n)));
3397- end;
3398- try expect(Scan.sSemicolon);
3399- while Scan.tok = Scan.sImport do
3400- Scan.next;
3401- repeat
3402- if Scan.tok # Scan.sIdent then return nil, expected("a module name"); end;
3403- start := Scan.tokPos();
3404- alias := Scan.id;
3405- mname := Scan.id;
3406- iargs.n := 0;
3407- generic := false;
3408- Scan.next;
3409- if Scan.tok = Scan.sBecomes then
3410- Scan.next;
3411- if Scan.tok # Scan.sIdent then return nil, expected("a module name"); end;
3412- mname := Scan.id;
3413- Scan.next;
3414- if Scan.tok = Scan.sLparen then
3415- generic := true;
3416- Scan.saveScan(argsAt);
3417- try skipArgs();
3418- end;
3419- end;
3420- iargs.at := Scan.spanFrom(start);
3421- o := Sym.newObj(Sym.oModule, alias, nil);
3422- o^.pos := start;
3423- try declare(o);
3424- if not generic then
3425- o^.home := try importModule(mname, iargs);
3426- addImport(m, o^.home);
3427- else
3428- o^.home := nil; (* until the instance is made, at its first use *)
3429- if numDeferred >= MaxDeferred then
3430- return nil, Scan.mark(tooMany(MaxDeferred, "generic imports"));
3431- end;
3432- deferred[numDeferred].o := o;
3433- deferred[numDeferred].home := m;
3434- deferred[numDeferred].mname := mname;
3435- deferred[numDeferred].args := argsAt;
3436- deferred[numDeferred].at := iargs.at;
3437- INC(numDeferred);
3438- end;
3439- if Scan.tok # Scan.sComma then break; end;
3440- Scan.next;
3441- until false;
3442- try expect(Scan.sSemicolon);
3443- end;
3444- while Scan.tok = Scan.sLink do
3445- Scan.next;
3446- if (Scan.tok = Scan.sIdent) and (Scan.id = nameStatic) then
3447- m^.linkStatic := true;
3448- elsif Scan.tok = Scan.sString then
3449- NEW(lib, Heap.heap);
3450- lib^.name := internName(Scan.strBytes());
3451- lib^.next := m^.libs;
3452- m^.libs := lib;
3453- m^.usesC := true;
3454- else
3455- return nil, expected("a library or \"static\"");
3456- end;
3457- Scan.next;
3458- try expect(Scan.sSemicolon);
3459- end;
3460- (* check off;: the module's index and slice checks left out; neither
3461- word is reserved *)
3462- if (Scan.tok = Scan.sIdent) and (Scan.id = nameCheck) then
3463- Scan.next;
3464- if (Scan.tok # Scan.sIdent) or (Scan.id # nameOff) then return nil, expected("\"off\""); end;
3465- Scan.next;
3466- try expect(Scan.sSemicolon);
3467- Item.setChecks(false);
3468- end;
3469- declarations(true);
3470- if Scan.tok = Scan.sBegin then
3471- if checkMode then
3472- try skipBody();
3473- else
3474- try instancesFor(true);
3475- line := Scan.curLine();
3476- Scan.next;
3477- bodyChunk := Chunk.newChunk(Chunk.secText, m^.sname, nameBody);
3478- m^.body := bodyChunk;
3479- Item.beginProc(tBodySig, nil);
3480- deferSlot := 0;
3481- curResult := nil;
3482- Gen.enterBody(bodyChunk, line);
3483- stray := false; elseIf := false;
3484- try statements();
3485- Chunk.noteLine(Scan.curLine(), Scan.curCol());
3486- try expect(Scan.sEnd);
3487- try Gen.endProc(bodyChunk, false);
3488- end;
3489- else
3490- try expect(Scan.sEnd);
3491- end;
3492- if (Scan.tok # Scan.sIdent) or (Scan.id # n) then
3493- return nil, endMissing(Scan.missingPos(), say2("expected {}, found {}", nameOf(n), Scan.found()));
3494- end;
3495- Scan.next;
3496- if Scan.tok # Scan.sPeriod then return nil, expected("\".\""); end;
3497- o := m^.first;
3498- while o # nil do
3499- if (o^.cls = Sym.oProc) and o^.fwd then
3500- Diag.error(Scan.tokPos(), say1("{} is declared forward but never defined", nameOf(o^.name)));
3501- end;
3502- o := o^.chain;
3503- end;
3504- if (Diag.errors = 0) and not checkOnly then warnings(m, firstDrop); end;
3505- numDrops := firstDrop;
3506- if Diag.errors > 0 then Diag.finish(); end; (* a module with errors stops the compiler after it *)
3507- Sym.closeScope();
3508- m^.done := true;
3509- if not checkOnly then
3510- DEC(numPending);
3511- if lastModule = nil then firstModule := m; else lastModule^.next := m; end;
3512- lastModule := m;
3513- end;
3514- Sym.setCurModule(oldMod); checkMode := oldCheck; Chunk.setCurFile(oldPath); Item.setChecks(oldChecks);
3515- Sym.restoreScopes(d, saved[0..Sym.MaxDepth]);
3516- Scan.restoreScan(st);
3517- return m, nil;
3518-end;
3519-
3520-(* The interface check: b must export just what a does. *)
3521-proc compareIface(a, b: PModule);
3522-var o, q: PObj;
3523-begin
3524- o := a^.first;
3525- while o # nil do
3526- if o^.exported then
3527- q := Sym.find(b^.scope, o^.name);
3528- if (q = nil) or not q^.exported or (Sym.fingerprint(o) # Sym.fingerprint(q)) then
3529- Diag.fatal(Diag.say("{}: {} isn't exported as in {}", [Fmt.str(b^.path), Fmt.str(nameOf(o^.name)), Fmt.str(a^.path)]));
3530- end;
3531- end;
3532- o := o^.chain;
3533- end;
3534- q := b^.first;
3535- while q # nil do
3536- o := Sym.find(a^.scope, q^.name);
3537- if q^.exported and ((o = nil) or not o^.exported) then
3538- Diag.fatal(Diag.say("{}: {} isn't exported by {}", [Fmt.str(b^.path), Fmt.str(nameOf(q^.name)), Fmt.str(a^.path)]));
3539- end;
3540- q := q^.chain;
3541- end;
3542-end;
3543-
3544-(* Reads every other file of module n in dir, and checks its interface
3545- against m, compiled from the file named chosen. *)
3546-proc checkSiblings(dir, chosen: []U8; n: INT; m: PModule; args: Sym.Args): ERROR;
3547-var
3548- dp: Sys.Dir; e, prefix: []U8; i, numOthers: INT; more: BOOL; sib: PModule;
3549- others: [32][]U8;
3550-begin
3551- prefix := say1("{}.", nameOf(n));
3552- numOthers := 0;
3553- if Sys.openDir(ADR(dp), dir) # 0 then return nil; end;
3554- repeat
3555- e, more := Sys.nextEntry(ADR(dp));
3556- if not more then break; end;
3557- if (LEN(e) > 4) and Str.hasPrefix(e, prefix) and (e[LEN(e) - 4..LEN(e)] = ".raz")
3558- and (e # chosen) and (numOthers < 32) then
3559- others[numOthers] := keep(e);
3560- INC(numOthers);
3561- end;
3562- until false;
3563- Sys.closeDir(ADR(dp));
3564- for i := 0 to numOthers - 1 do
3565- sib := try compileFile(say2("{}/{}", dir, others[i]), n, args, true);
3566- compareIface(m, sib);
3567- end;
3568- return nil;
3569-end;
3570-
3571-(* The directories searched for modules, in order, from -1 to numInc *)
3572-proc searchDir(i: INT): []U8;
3573-begin
3574- if i = -1 then return mainDir; end;
3575- if i = numInc then return libDir; end;
3576- return incDirs[i];
3577-end;
3578-
3579-(* The file of module n in dir that suffix j says: Name.linux-x86_64.raz
3580- for a file of this target alone, and so on to Name.raz *)
3581-proc fileName(n, j: INT): []U8;
3582-begin
3583- return Diag.say("{}{}.raz", [Fmt.str(nameOf(n)), Fmt.str(Suffixes[j])]);
3584-end;
3585-
3586-proc moduleFile(n: INT): ([]U8, []U8, BOOL);
3587-var i, j: INT; dir, f: []U8;
3588-begin
3589- for i := -1 to numInc do
3590- dir := searchDir(i);
3591- for j := 0 to 3 do
3592- f := fileName(n, j);
3593- if exists(say2("{}/{}", dir, f)) then return dir, f, true; end;
3594- end;
3595- end;
3596- return "", "", false;
3597-end;
3598-
3599-(* A program has one module of each name: module n, found as dir/f,
3600- must have no files in a later directory, unless dir/f is a link to
3601- one of them, which chooses it (report, section 3) *)
3602-proc checkOneModule(n: INT; dir, f: []U8; at: Diag.Pos): ERROR;
3603-var
3604- i, j, dev, ino, mineDev, mineIno: INT; past, chosen: BOOL; g, files, others: []U8;
3605-begin
3606- mineDev, mineIno := identity(say2("{}/{}", dir, f));
3607- others := "";
3608- past := false;
3609- for i := -1 to numInc do
3610- if past then
3611- files := "";
3612- chosen := false;
3613- for j := 0 to 3 do
3614- g := say2("{}/{}", searchDir(i), fileName(n, j));
3615- if exists(g) then
3616- files := say2("{} and {}", files, Diag.shownPath(g));
3617- dev, ino := identity(g);
3618- chosen := chosen or ((dev = mineDev) and (ino = mineIno));
3619- end;
3620- end;
3621- if not chosen then others := say2("{}{}", others, files); end;
3622- end;
3623- past := past or (searchDir(i) = dir);
3624- end;
3625- if LEN(others) = 0 then return nil; end;
3626- Diag.error(at, say3("module {} is in {}{}", nameOf(n), Diag.shownPath(say2("{}/{}", dir, f)), others));
3627- Diag.help("a program has one module of each name; a symbolic link to one of these files chooses it");
3628- return Scan.Failed;
3629-end;
3630-
3631-proc importModule(name: INT; args: Sym.Args): (PModule, ERROR);
3632-var m: PModule; i: INT; dir, f, where: []U8; found: BOOL;
3633-begin
3634- m := findModule(name, args);
3635- if m # nil then return m, nil; end;
3636- for i := 0 to numPending - 1 do
3637- if isModule(pending[i], name, args) then
3638- return nil, Scan.markAt(args.at, say1("{} imports itself", nameOf(name)));
3639- end;
3640- end;
3641- dir, f, found := moduleFile(name);
3642- if not found then
3643- Diag.error(args.at, say1("can't find module {}", nameOf(name)));
3644- where := Diag.shownPath(searchDir(-1));
3645- for i := 0 to numInc do where := say2("{}, {}", where, Diag.shownPath(searchDir(i))); end;
3646- Diag.help(say2("looked for {}.raz in {}", nameOf(name), where));
3647- return nil, Scan.Failed;
3648- end;
3649- try checkOneModule(name, dir, f, args.at);
3650- m := try compileFile(say2("{}/{}", dir, f), name, args, false);
3651- try checkSiblings(dir, f, name, m, args);
3652- return m, nil;
3653-end;
3654-
3655-proc addImport(m, im: PModule);
3656-var imp: ^Sym.Import;
3657-begin
3658- NEW(imp, Heap.heap);
3659- imp^.home := im;
3660- imp^.next := m^.imports;
3661- m^.imports := imp;
3662-end;
3663-
3664-(* Makes the instance that deferred[i] imports: its arguments are read
3665- where the import wrote them, and must be declared by now. Compiling
3666- the instance comes in the middle of a declaration, so what that
3667- declaration has under way is kept aside meanwhile. *)
3668-proc makeInstance(i: INT; at: Diag.Pos): ERROR;
3669-var
3670- d: Deferred; st: Scan.State; args: Sym.Args; types, exported, ext, wasQuiet: BOOL; nf, nd: INT;
3671- ft: [MaxFwd]PType; fp: [MaxFwd]Diag.Pos; decl: [MaxNames]INT;
3672-begin
3673- d := deferred[i];
3674- DEC(numDeferred);
3675- deferred[i] := deferred[numDeferred];
3676- Scan.saveScan(st);
3677- Scan.restoreScan(d.args);
3678- args.n := 0;
3679- making := true; useAt := at;
3680- try parseArgs(args, nameOf(d.mname));
3681- making := false;
3682- Scan.restoreScan(st);
3683- args.at := d.at;
3684- types := inTypes; exported := declExported; ext := inExtern; wasQuiet := Diag.quiet;
3685- nf := numFwd; ft := fwdTypes; fp := fwdPos; nd := numDeclaring; decl := declaring;
3686- d.o^.home := try importModule(d.mname, args);
3687- inTypes := types; declExported := exported; inExtern := ext; Diag.setQuiet(wasQuiet);
3688- numFwd := nf; fwdTypes := ft; fwdPos := fp; numDeclaring := nd; declaring := decl;
3689- addImport(Sym.curModule, d.o^.home);
3690- return nil;
3691-end;
3692-
3693-proc firstUse(o: PObj; at: Diag.Pos): ERROR;
3694-var i: INT;
3695-begin
3696- for i := 0 to numDeferred - 1 do
3697- if deferred[i].o = o then return makeInstance(i, at); end;
3698- end;
3699- return Scan.Failed; (* its arguments had an error, already reported *)
3700-end;
3701-
3702-(* An instance can't be compiled in the middle of another procedure's
3703- code, so before a procedure's code begins, from its "proc" on, or
3704- the module body's, from its "begin" to the end of the file, this
3705- reads ahead for the names of imports not yet made, and makes those. *)
3706-proc instancesFor(wholeRest: BOOL): ERROR;
3707-var st: Scan.State; d, i: INT; begun: BOOL;
3708-begin
3709- if checkMode then return nil; end;
3710- i := numDeferred - 1;
3711- while (i >= 0) and (deferred[i].home # Sym.curModule) do DEC(i); end;
3712- if i < 0 then return nil; end;
3713- (* The procedure ends at the "end" that closes its first "begin": d
3714- counts the words still open that "end" or "until" closes, and begun
3715- says that begin was met, so that a record's end in its declarations
3716- doesn't stop it. A forward or code procedure has no raz body to
3717- read, so it stops at that word. The body reads to the end of the
3718- file, as wholeRest says. *)
3719- Scan.saveScan(st);
3720- d := 0; begun := false;
3721- repeat
3722- match Scan.tok of
3723- | sIdent:
3724- for i := numDeferred - 1 to 0 by -1 do
3725- if (deferred[i].home = Sym.curModule) and (deferred[i].o^.name = Scan.id) then
3726- try makeInstance(i, Scan.tokPos());
3727- end;
3728- end;
3729- | sBegin:
3730- begun := begun or (d = 0);
3731- INC(d);
3732- | sIf, sWhile, sFor, sMatch, sRepeat, sRecord, sVariant: INC(d);
3733- | sEnd, sUntil: DEC(d);
3734- | else:
3735- end;
3736- if not wholeRest and (d = 0) and (begun or (Scan.tok = Scan.sForward) or (Scan.tok = Scan.sCode)) then break; end;
3737- Scan.next;
3738- until Scan.tok = Scan.sEof;
3739- Scan.restoreScan(st);
3740- return nil;
3741-end;
3742-
3743-(* The main module, from the file at path, and Rt, which every program
3744- needs, first *)
3745-proc compileMain*(path: []U8): (PModule, ERROR);
3746-var base: []U8; i, n: INT; none: Sym.Args; m: PModule;
3747-begin
3748- none.n := 0;
3749- i := LEN(path);
3750- while (i > 0) and (path[i - 1] # '/') do DEC(i); end;
3751- if i = 0 then mainDir := "."; else mainDir := path[0..i - 1]; end;
3752- base := path[i..LEN(path)];
3753- i := 0;
3754- while (i < LEN(base)) and (base[i] # '.') do INC(i); end;
3755- base := base[0..i];
3756- if LEN(base) = 0 then Diag.fatal(say1("no module in {}", path)); end;
3757- n := internName(base);
3758- none.at := Scan.tokPos();
3759- if n # nameRt then _ := try importModule(nameRt, none); end;
3760- m := findModule(n, none);
3761- if m # nil then return m, nil; end;
3762- return compileFile(path, n, none, false);
3763-end;
3764-
3765-begin
3766- nameRt := internName("Rt");
3767- nameFail := internName("fail");
3768- nameAdr := internName("ADR");
3769- nameBody := internName("body");
3770- nameStatic := internName("static");
3771- nameCheck := internName("check");
3772- nameOff := internName("off");
3773- tArgv := newPtr(newPtr(Sym.tU8, false), false);
3774- tBodySig := Sym.newType(Sym.fProc, 8, 8);
3775-end Parse.

self/README.md deleted +0 -195

@@ -1,195 +0,0 @@
1-# self: the compiler in raz
2-
3-The port of the Pascal compiler, the **seed** in `../src/`, to raz.
4-`../PLAN.md`, "Self", says what it is for and the order of its units.
5-
6-One module to a seed unit, with the seed's name, written to the same
7-rules: plain code, each module opening with what it is, what it
8-depends on and what it leaves out. The seed is never edited from here.
9-
10- make self # each unit against the seed's, on the same files
11- make self-bench # the scanner's speed against the seed's
12- make fixpoint # the seed builds self, that builds self, that builds it again
13-
14-`Chunk` and `Sym` have no input files to read, so each has a dumper
15-pair, `test/ChunkDump` and `test/SymDump`, that runs one fixed
16-pseudo-random script of calls on its side and prints all it made or
17-answered (`Sym` also ends, as an argument says, in the error of a name
18-declared twice or of too many scopes): the output, the messages and
19-the status must be the same. `Link` and `Elf` are tested by
20-`test/LinkDump`, which makes a program of chunks by a script and writes
21-it as a static, a dynamic and a stripped executable, which must be the
22-same file; `X64` by `test/X64Dump`, every encoder with operands from a
23-script, bytes, fixups and listing, and by `test/AsmDump` on the files
24-`test/genasm.py` makes: a long run of every instruction the assembler
25-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`.
42-
43-`Parse` and `Raz`, the last two units, are tested whole: the seed builds
44-`self/Raz.raz` into `build/self/raz.self`, and each compiler, run as
45-`build/cmp/raz` (a program holds the paths it was made from, and the
46-library is found beside the compiler), compiles the library, the
47-examples, the tools, `self/` itself, every test of `test/` and
48-`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.
51-`make self-bench` gives the speed of both.
52-
53-`make fixpoint` (`fixpoint.sh`) is the proof that the port is whole:
54-the seed builds `Raz.raz` (stage 1), stage 1 builds it (stage 2), and
55-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
58-`make bench` run on it. Each stage is built by the same command in the
59-same place, since a program holds the paths it was made from.
60-
61-`check.sh` builds a dumper for each side, `test/ScanDump.pas` over the
62-seed's units and `test/ScanDump.raz` over these, and has both read the
63-library, the examples, every test of the compiler and a file for each
64-message the scanner makes (`test/genlex.py`) and for hundreds of reals
65-that are hard to read exactly (`test/genreals.py`): the output, the
66-messages and the status must be the same.
67-
68-## What the port found
69-
70-Not the seed's to mend; for the owner to choose.
71-
72-- **Names.** An exported variable is read-only outside its module, so
73- what the parser sets in the seed's `diag` and `scan` (`quiet`,
74- `werror`, `recovery`, `skipping`) have setters. The `sbuf` array,
75- which can't be sliced outside, is `strBytes`.
76-- **Going on after an error.** raz has no `setjmp`, and the seed's parser
77- ends its errors in a jump back to the statement or declaration being
78- read, which is how it reports up to 20 errors in a run. The language
79- gained `try` (report 2026-10.20) for this: `Scan.mark` and the others
80- show the error and return `Scan.Failed`, which the parser passes up
81- with `try` to where it reads on. `test/Recover.raz` is the pattern.
82-- **`NO_COLOR` set to nothing.** `Sys.env` gives "" for a variable that
83- is unset and for one that is empty, so the port reads the second as
84- the first. no-color.org says a variable that is empty doesn't turn
85- colour off, so the port is the one that follows it and the seed
86- differs; no test depends on either.
87-- **Strings are slices.** A message is a `[]U8` made by `Diag.say`,
88- which keeps what it makes: messages are made only to be shown. A name
89- from `nameOf` stays valid, since names are kept in chunks that are
90- never moved; the seed's was a copy.
91-- **Reserved words as names.** The seed's `code` (the text buffer of
92- `Chunk`) is `text`; `module` (a record's, an import's) is `home`; an
93- object's `link` is `chain`. A seed type `TName` is `Name`, and the
94- procedures begin in lower case, as `Scan`'s do.
95-- **Errors in `Sym`.** `insert` (a name declared twice) and `openScope`
96- (too many scopes) show the error and return `Scan.Failed`, as `mark`
97- does, for the parser to pass up with `try`. `saveScopes` returns what
98- the seed's `var d` gave.
99-- **Setters.** What other units set in `Chunk` has one each (`setLive`,
100- `setAdr`, `setReals`, `setSaves`, `setCurFile`, and `rewindTo` for
101- gen's `Redo` and `Rewind`), and `Sym` has `setCurModule`. `Scan.grab`
102- is exported for the memory they all take.
103-- **No `continue`.** The seed's loops that skip to the next round
104- (`MarkLive`, the line program, the assembler's statements) have the
105- rest of the body in an `else`, or in a procedure of its own.
106-- **`X64`.** `code` of `Chunk` being reserved, its text is `Chunk.text`;
107- `Say` and the rest of the encoder keep their names, in lower case.
108- `ConstFn`, the parser's reader of a constant, returns an `ERROR` too,
109- and `assemble` returns what it passes up. `mem` marks an offset beyond
110- 32 bits and goes on, since an operand has nowhere to return an error
111- to; the compile ends with the message shown. The listing's text is
112- made by `Diag.say`, which keeps it, and only when `-S` asks for it.
113-- **`Link` and `Elf`.** What `raz.pas` set there has a setter each:
114- `Link.setPlaces`, `Elf.needLib`, `noLibs`, `setMainPath`,
115- `setStripped` and `X64.setListing`. The file is written by
116- `Files.write` and made executable by `Sys.chmod`, in place of one
117- `open` with mode 755 (which the umask would trim).
118-- **`Gen`.** The seed's `Mark` in the middle of a push or a check
119- can't give an error back: `newEntry` (the stack's 256 places) and
120- `check` (4,096 checks a procedure) show it and go on without doing
121- what they couldn't, and the parser's `resetStack` makes the stack
122- right again; `endProc` returns its error ("frame too big") and
123- `codeProc` the assembler's. A `var` out of the seed became a result
124- (`topConst`, `operands`, `deferBegin`); the labels, which are chains
125- that a call extends, stay `var`. `inPlace` has a setter. The seed's
126- `Call` record is `CallInfo` (the procedure is `call`) and `TLink` is
127- `Link`. A `match` on an enumeration takes one name to an arm, and a
128- set holds at most 64 names, so `Scan.Sym` (over 64) has none: the
129- seed's sets of its names are chains of `=`.
130-- **`Item`.** The seed's `Mark` ended in a jump, so here every
131- routine that can find an error returns an `ERROR` as its last result
132- and the ones that call it pass it up with `try`; `Item` shows the
133- message and returns what the seed jumped out of, so a script that
134- goes on after an error sees the same state. The seed's `Mismatch` of
135- two operands is `mismatchOps`, `demoted` and `checks` have setters,
136- and `matchBegin`, `toSlot` and `errorChunk` return their value and
137- the error. `op2` has a parameter it never read, now `_L`. A message
138- is made by `Diag.say` from strings, with no `shortstring` to add up.
139- A `Mark` with no place is at the scanner's, as in the seed.
140-- **No `const` parameter.** The seed's `const x: TItem` is a value
141- parameter here, so an item of about 130 bytes is copied at each call
142- of `what`, `adrOf`, `notValue` and the others. The result is the
143- same; whether the compiler built from this is slower for it is for
144- the speed test of step 4 to say. A `const` parameter (a hint that
145- the callee won't change it, so that the caller may pass its address)
146- would be a language change: it goes on the wish list.
147-- **`Parse` and the seed's jumps.** The seed's `Guard`, `setjmp` and
148- `longjmp` are `guard`, a record of what to put back, and the `ERROR`
149- that comes up through `try` to the statement or declaration that is
150- the recovery point (`statement`, `declaration`), which looks at it,
151- puts the state back (`restore`) and skips ahead, as the seed does.
152- `giveUp`, the seed's `GiveUp`, returns the error on to the next one,
153- or ends the compile if there is none (`guards` counts them). A routine
154- that can't fail has no `ERROR` (`declarations`, `declaration`). The
155- seed's nested procedures (`ChooseRegs`'s three) are procedures of the
156- module with its candidates in variables. `defer` and `module` being
157- words, the seed's `Defer` is `deferStatement`. A message is made
158- from strings with `Diag.say`, which has no shortstring to add up to.
159- `Scan.skipping` is exported to be read, and `Scan.strWithZero` gives
160- `Item.makeStr` a pointer to a string that may be empty: the seed's
161- `@sbuf` indexed nothing, and `ADR(Scan.strBytes()[0])`, which the
162- port of `Item` had, stopped on `""`.
163-- **`Raz`.** The program is `proc main*: INT`. Where it is, for the
164- library beside it, it reads from `/proc/self/exe` as FPC's `ParamStr(0)`
165- does: `Files.arg(0)` is what the shell was typed, and `./raz` made the
166- library `./lib`, so the same program held other paths in its file.
167- `raz run` writes the memfd with `Elf.writeElf` and executes it with
168- the system call, `execve`, which `Sys` has no procedure for. The
169- version is the module `Version`, which `check.sh` makes in
170- `build/self/` from `build/version.inc`, as the seed's `{$I}` is.
171- Two names of a file, for a module found in two places, are told by
172- the device and inode `SYSCALL` `stat` gives, which `Sys.info` lacks.
173-- **Sets of `Scan.Sym`.** It has 76 names and a set holds 64, so the
174- operators a rule names are chains of `=` or the helpers `oneOf` and
175- `isRel`. (A `match` arm with several names, which the seed's `case`
176- has, was added to the report for this: 2026-10.21.)
177-- **Strings made by the compiler.** A joined string (`"a" + "b"`) and
178- an error's text are built in memory from `Scan.grab`, which is never
179- freed, in place of `GetMem` and `FreeMem`; the compiler runs once.
180-- **No bit cast.** A real's bits and back go through a pointer.
181-- **Speed.** On the 348,025 lines of `test/genbench.py`, 7.6 MB, the
182- seed's scanner takes 75 ms and this one 74. It took 121 at first.
183- What closed the gap, in the source: a byte loop in place of the slice
184- comparison `a[0..n] = b[0..n]` (97 ms), a 256-entry table for the
185- bytes of a name (84), and one for the symbols that are a byte each
186- (75). What is left for the code generator, which would help every
187- module: the slice comparison is slower than the loop it stands for.
188- On the whole compiler, the same 348,025 lines take 427 ms with the
189- seed's and 770 with this one (452,000 lines a second, over the 400,000
190- the budget wants): `Scan.tokPos`, a record of three words returned
191- through a pointer, is 9% of it, and the rest is spread thin; the
192- `const` parameter of `Item` isn't what stands out.
193- (The seed's `match` on an integer was a chain of compares, each
194- loading the selector from the frame and jumping over a `jmp`, where
195- FPC makes a jump table; now it makes one too.)

self/Raz.raz deleted +0 -273

@@ -1,273 +0,0 @@
1-(* Raz: the command line.
2-
3- raz [-I dir]... [-o file] [-Werror] [-S] Main.raz
4- raz run [-I dir]... Main.raz [arg]...
5- raz --version
6-
7- Compiles the main module and every module it imports, writes the
8- entry point, links what it reaches, and writes the executable: by
9- default the main module's file without its .raz; with -S, it lists
10- the main module's code instead. raz run writes it to a memfd
11- instead, a file that lives only in memory, and executes it in raz's
12- place with the arguments after Main.raz, so its status is the
13- program's; its argv[0] is Main.raz.
14-
15- The program starts by saving argc and argv, runs every module's body
16- (those of the modules the program imports, imported modules first),
17- then the main module's main, and ends with Rt.exit and main's
18- status. A static program does this from its entry point. One that
19- uses C starts through the C library, __libc_start_main, which sets
20- C up and calls this as C's main; first it gives Rt C's exit, which
21- Rt.exit then ends the program with.
22-
23- Depends on: everything else, and Version, a module the build makes
24- (build/self/Version.raz) from what git describe says, as the seed's
25- build/version.inc is.
26- Leaves out: the work itself; the other units compile, link and
27- write, and this only reads the command line and runs them in order. *)
28-module Raz;
29-import Sys, Out, Version, Files, Fmt, Diag, Scan, Sym, Chunk, X64, Gen, Parse, Link, Elf;
30-
31-const
32- Report = "2026-10.21"; (* the version of doc/raz.md it follows *)
33- MemfdCreate = 319; (* the system call *)
34- MfdCloexec = 1; (* an ELF still executes: the kernel opens it first *)
35- Execve = 59;
36-
37-var
38- links: [4]Gen.Link;
39- numLinks: INT;
40-
41-proc say1(f, a: []U8): []U8;
42-begin
43- return Diag.say(f, [Fmt.str(a)]);
44-end;
45-
46-(* The number of the name s *)
47-proc internStr(s: []U8): INT;
48-begin
49- return Scan.intern(ADR(s[0]), LEN(s));
50-end;
51-
52-(* The modules the program uses: the main module, Rt, and every module
53- they import. A module read only for the interface check is not. *)
54-proc use(m: ^Sym.Module);
55-var i: ^Sym.Import;
56-begin
57- if m^.used then return; end;
58- m^.used := true;
59- i := m^.imports;
60- while i # nil do
61- use(i^.home);
62- i := i^.next;
63- end;
64-end;
65-
66-(* Whether the program uses C: if so, the libraries it needs go to
67- Elf, the C library first. *)
68-proc usesC: BOOL;
69-var m, st, c: ^Sym.Module; l: ^Sym.Lib;
70-begin
71- st := nil; c := nil;
72- Elf.noLibs();
73- _ := Elf.needLib(internStr("libc.so.6"));
74- m := Parse.firstModule;
75- while m # nil do
76- if m^.used and m^.linkStatic then st := m; end;
77- if m^.used and m^.usesC then c := m; end;
78- l := m^.libs;
79- while m^.used and (l # nil) do
80- if not Elf.needLib(l^.name) then Diag.fatal("more than 32 libraries"); end;
81- l := l^.next;
82- end;
83- m := m^.next;
84- end;
85- if (st # nil) and (c # nil) then
86- Diag.fatal(Diag.say("{} says link static, but {} uses C", [Fmt.str(Scan.nameOf(st^.name)), Fmt.str(Scan.nameOf(c^.name))]));
87- end;
88- if c = nil then Elf.noLibs(); end;
89- return c # nil;
90-end;
91-
92-(* What raz -h says *)
93-proc usage;
94-begin
95- Out.str("usage: raz [option]... Main.raz compiles Main.raz and the modules it imports\n");
96- Out.str(" raz run [option]... Main.raz [arg]... compiles it and runs it, with the args\n");
97- Out.str("options:\n");
98- Out.str(" -o file the program's file, Main without .raz if left out\n");
99- Out.str(" -I dir looks for imported modules in dir too, after Main.raz's own\n");
100- Out.str(" -Werror a warning counts as an error\n");
101- Out.str(" -S lists the main module's code, under each line of source\n");
102- Out.str(" -s strips symbols, line numbers, the places a failure is told\n");
103- Out.str(" by and the profiler: a failure says only its address\n");
104- Out.str(" -noprofile leaves out the profiler, which RAZ_PROFILE turns on\n");
105- Out.str(" -h, --help says this\n");
106- Out.str(" --version says the version, and the report it follows\n");
107- Out.str("see raz(1), and the report, doc/raz.md\n");
108- Out.flush();
109-end;
110-
111-proc rtObj(rt: ^Sym.Module; n: []U8): ^Sym.Obj;
112-var o: ^Sym.Obj;
113-begin
114- o := Sym.find(rt^.scope, internStr(n));
115- if o = nil then Diag.fatal(say1("Rt has no {}", n)); end;
116- return o;
117-end;
118-
119-(* Rt is given the address of chunk, in its variable v *)
120-proc addLink(chunk: INT; v: ^Sym.Obj);
121-begin
122- links[numLinks].chunk := chunk;
123- links[numLinks].into := v^.chunk;
124- INC(numLinks);
125-end;
126-
127-(* s as a C string, in memory that is never freed *)
128-proc cstr(s: []U8): ^U8;
129-var p: ^U8;
130-begin
131- p := Scan.grab(LEN(s) + 1);
132- if LEN(s) > 0 then COPY(p[0..LEN(s)], s); end;
133- p[LEN(s)] := 0;
134- return p;
135-end;
136-
137-proc main*: INT;
138-var
139- path, outPath, s: []U8; dir: []U8;
140- i, first, entry, fd, last, errno: INT;
141- m, rt: ^Sym.Module; mainObj: ^Sym.Obj;
142- run, noProfile, listing: BOOL; err: ERROR;
143-begin
144- path := "";
145- outPath := "";
146- noProfile := false;
147- listing := false;
148- run := (ARGC() >= 2) and (Files.arg(1) = "run");
149- if run then i := 2; else i := 1; end;
150- while i < ARGC() do
151- s := Files.arg(i);
152- if s = "-I" then
153- INC(i);
154- if Parse.numInc > 15 then Diag.fatal("more than 16 -I directories"); end;
155- Parse.addIncDir(Files.arg(i));
156- elsif s = "-o" then
157- INC(i);
158- outPath := Files.arg(i);
159- elsif s = "-Werror" then
160- Diag.setWerror(true);
161- elsif s = "-S" then
162- listing := true;
163- X64.setListing(true);
164- elsif s = "-s" then
165- Elf.setStripped(true);
166- elsif s = "-noprofile" then
167- noProfile := true;
168- elsif (s = "-h") or (s = "--help") then
169- usage();
170- return 0;
171- elsif s = "--version" then
172- Out.str(Diag.say("raz {}, report {}\n", [Fmt.str(Version.Text), Fmt.str(Report)]));
173- Out.flush();
174- return 0;
175- elsif (LEN(s) > 0) and (s[0] = '-') then
176- Diag.fatal(say1("unknown option {}", s));
177- else
178- path := s;
179- first := i;
180- if run then break; end; (* the rest are the program's *)
181- end;
182- INC(i);
183- end;
184- if LEN(path) = 0 then
185- usage();
186- return 1;
187- end;
188- if run and (LEN(outPath) > 0) then Diag.fatal("raz run takes no -o"); end;
189- (* where raz is, as the system says, for the library beside it *)
190- dir, errno := Sys.readLink("/proc/self/exe");
191- if errno # 0 then dir := Files.arg(0); end;
192- i := LEN(dir);
193- while (i > 0) and (dir[i - 1] # '/') do DEC(i); end;
194- if i = 0 then Parse.setLibDir("lib"); else Parse.setLibDir(say1("{}lib", dir[0..i])); end;
195- if LEN(outPath) = 0 then
196- outPath := path;
197- last := LEN(outPath);
198- if (last >= 4) and (outPath[last - 4..last] = ".raz") then
199- outPath := outPath[0..last - 4];
200- else
201- outPath := say1("{}.out", outPath);
202- end;
203- end;
204-
205- m, err := Parse.compileMain(path);
206- if err # nil then
207- Diag.finish();
208- return 1;
209- end;
210- if Diag.errors > 0 then Diag.finish(); end;
211-
212- use(m);
213- rt := Parse.firstModule;
214- while (rt # nil) and (Scan.nameOf(rt^.name) # "Rt") do rt := rt^.next; end;
215- if rt # nil then use(rt); end;
216-
217- mainObj := Sym.find(m^.scope, internStr("main"));
218- if mainObj # nil then
219- if (mainObj^.cls # Sym.oProc) or not mainObj^.exported then
220- Diag.error(mainObj^.pos, "main must be an exported procedure");
221- elsif (mainObj^.typ^.len # 0) or ((mainObj^.typ^.base # nil) and (mainObj^.typ^.base # Sym.tInt)) then
222- Diag.error(mainObj^.pos, "main must be proc main* or proc main*: INT");
223- end;
224- if Diag.errors > 0 then Diag.finish(); end;
225- end;
226- Diag.finish();
227-
228- if rt = nil then Diag.fatal("can't find module Rt"); end;
229- (* what Rt is given: the places, which the linker makes, for Rt to say
230- where a failed check or a signal was (place), and the calls under
231- way then (calls); and the profiler, which needs them too. raz -s
232- gives none, -noprofile no profiler. *)
233- numLinks := 0;
234- if not Elf.stripped then
235- Link.setPlaces(Chunk.newChunk(Chunk.secRodata, -1, -1));
236- Chunk.setData(Link.placesChunk, nil, 0, 8);
237- addLink(Link.placesChunk, rtObj(rt, "places"));
238- addLink(rtObj(rt, "calls")^.chunk, rtObj(rt, "teller"));
239- addLink(rtObj(rt, "place")^.chunk, rtObj(rt, "placer"));
240- if not noProfile then addLink(rtObj(rt, "startProfile")^.chunk, rtObj(rt, "profiler")); end;
241- end;
242- entry := Gen.entryPoint(usesC(), Parse.firstModule, mainObj, rtObj(rt, "cExit")^.chunk,
243- rtObj(rt, "exit")^.chunk, links[0..numLinks], numLinks);
244-
245- Link.markLive(entry);
246- if not Parse.HasReals then
247- for i := 0 to Chunk.numChunks - 1 do
248- if Chunk.chunks[i].live and Chunk.chunks[i].reals then
249- Diag.error(Chunk.chunks[i].realsAt, "this target has no reals");
250- end;
251- end;
252- end;
253- if Diag.errors > 0 then Diag.finish(); end;
254- if listing then
255- X64.list(m^.sname);
256- return 0;
257- end;
258-
259- Elf.setMainPath(path);
260- if run then
261- (* argv from Main.raz on is the program's, ending in nil as it must *)
262- fd := SYSCALL(MemfdCreate, cstr("raz"), MfdCloexec);
263- if fd < 0 then Diag.fatal("can't create a memfd"); end;
264- outPath := Diag.say("/proc/self/fd/{}", [Fmt.int(fd)]);
265- Elf.writeElf(outPath, entry);
266- _ := SYSCALL(Execve, cstr(outPath), ARGV() + first, ARGV() + (ARGC() + 1));
267- Diag.fatal(say1("can't run {}", path));
268- end;
269- Elf.writeElf(outPath, entry);
270- return 0;
271-end;
272-
273-end Raz.

self/Scan.raz deleted +0 -1002

@@ -1,1002 +0,0 @@
1-(* Scan: the scanner.
2-
3- Reads a raz source file and hands the parser one symbol at a time:
4- reserved words, identifiers, numbers, characters, strings and
5- operators. Identifiers are interned, so that the rest of the compiler
6- compares names as small integers. The scanner also says where the
7- current symbol is, for messages.
8-
9- Depends on: Sys, to read files; Diag, to report errors.
10- Leaves out: recovery from errors in the text itself, such as a string
11- not closed: the first such error stops the compiler. The parser goes
12- on after its own errors: mark and the others report one and give
13- back Failed, which it passes up with try to where it can read on. *)
14-module Scan;
15-import Sys, Heap, Mem, Fmt, Str, Diag;
16-
17-type
18- NamePtr = ^U8;
19-
20- Sym* = (sNull, sIdent, sInt, sReal, sChar, sString,
21- sPlus, sMinus, sTimes, sSlash, sEql, sNeq, sLss, sLeq, sGtr, sGeq,
22- sBecomes, sColon, sSemicolon, sComma, sPeriod, sUpto, sEllipsis,
23- sLparen, sRparen, sLbrak, sRbrak, sLbrace, sRbrace, sArrow, sAmp, sTilde, sBar,
24- sBlank,
25- (* the reserved words, in the order of words below *)
26- sAnd, sBegin, sBreak, sBy, sCode, sConst, sDefer, sDiv, sDo, sElse,
27- sElsif, sEnd, sExtern, sFor, sForward, sIf, sImport, sIn, sLink,
28- sMatch, sMod, sModule, sNot, sOf, sOr, sPacked, sProc, sRecord,
29- sRepeat, sReturn, sSet, sShl, sShr, sThen, sTo, sTry, sType, sUntil, sVar,
30- sVariant, sVolatile, sWhile, sXor,
31- sEof);
32-
33- (* Where the scanner is. Importing a module compiles it in the middle
34- of another, so the parser saves this and restores it afterwards. *)
35- State* = record
36- buf: ^U8;
37- len, pos, line, lineStart: INT;
38- tokPos, tokLine, tokLineStart: INT;
39- prevEnd: INT; (* where the symbol before this one ends *)
40- tok: Sym;
41- ival: I64;
42- rval: F64;
43- id: INT;
44- f: INT; (* the file, as Diag knows it *)
45- end;
46-
47-const
48- Failed*: ERROR = "reported"; (* an error has been shown: the parser returns it *)
49- MaxIdent* = 63;
50- MaxStr* = 65536;
51- NumWords = 43;
52- NumOps = 28;
53- words: [NumWords][]U8 = [
54- "and", "begin", "break", "by", "code", "const", "defer", "div", "do",
55- "else", "elsif", "end", "extern", "for", "forward", "if", "import",
56- "in", "link", "match", "mod", "module", "not", "of", "or", "packed",
57- "proc", "record", "repeat", "return", "set", "shl", "shr", "then",
58- "to", "try", "type", "until", "var", "variant", "VOLATILE", "while",
59- "xor"];
60- (* sPlus to sBlank *)
61- ops: [NumOps][]U8 = [
62- "+", "-", "*", "/", "=", "#", "<", "<=", ">", ">=",
63- ":=", ":", ";", ",", ".", "..", "...",
64- "(", ")", "[", "]", "{", "}", "^", "&", "~", "|", "_"];
65- (* the operators that no longer one starts, so that one byte is the symbol *)
66- alone = "+-*/#;,()[]{}^~";
67- PoolChunk = 65536;
68-
69-var
70- tok*: Sym; (* the current symbol *)
71- ival*: I64; (* sInt, sChar: its value *)
72- rval*: F64; (* sReal: its value *)
73- id*: INT; (* sIdent: its name *)
74- slen*: INT; (* sString: how many bytes *)
75- sbuf: [MaxStr + 1]U8; (* sString: its bytes, then a zero *)
76-
77- (* The parser is skipping what it has read once already, after an
78- error, so slips in it aren't reported again. *)
79- skipping*: BOOL;
80-
81- (* Whether a byte may be in a name: a letter, a digit or _. A table,
82- since the loop that reads a name asks it of every byte. *)
83- nameChar: [256]BOOL;
84-
85- (* The symbol a byte is by itself, as + is, or sNull: a table, since
86- most symbols are of this kind and a match would test them one by one. *)
87- single: [256]Sym;
88-
89- cur: State; (* buf .. f; tok, ival, rval and id live above *)
90-
91- (* The name table: every distinct identifier once, found through an
92- open-addressed hash table. A name's bytes are in a chunk of memory
93- that is never moved, so that nameOf can hand out a slice of them. *)
94- chunk: ^U8; (* where names are put; chunkLeft bytes are left *)
95- chunkLeft: INT;
96- namePtr: ^NamePtr;
97- nameLen, nameHash: ^INT;
98- numNames, nameCap: INT;
99- table: ^INT; (* name + 1, or 0 for an empty slot *)
100- tableMask: INT;
101-
102-(* Exported variables can't be set from outside, so these do it. *)
103-proc setSkipping*(yes: BOOL);
104-begin
105- skipping := yes;
106-end;
107-
108-(* The bytes of the string just read, without the zero after them *)
109-proc strBytes*: []U8;
110-begin
111- return sbuf[0..slen];
112-end;
113-
114-(* The string just read and the zero after it, for the code that makes a
115- chunk of it: an empty string has bytes to point at, though none to index *)
116-proc strWithZero*: ^U8;
117-begin
118- return ADR(sbuf[0]);
119-end;
120-
121-(* Memory, or the end of the compile when there is none *)
122-proc grab*(size: INT): ^U8;
123-var p: ^U8;
124-begin
125- p := Mem.alloc(Heap.heap, size, 8);
126- if p = nil then Diag.fatal("out of memory"); end;
127- return p;
128-end;
129-
130-(* p, which holds used bytes, moved to a block of size bytes *)
131-proc regrab*(p: ^U8; used, size: INT): ^U8;
132-var q: ^U8;
133-begin
134- q := grab(size);
135- COPY(q[0..used], p[0..used]);
136- Mem.free(Heap.heap, p);
137- return q;
138-end;
139-
140-(* n zeroed words *)
141-proc words64(n: INT): ^INT;
142-var p: ^INT; i: INT;
143-begin
144- p := ^INT(grab(n * SIZE(INT)));
145- for i := 0 to n - 1 do p[i] := 0; end;
146- return p;
147-end;
148-
149-(* Names *)
150-
151-proc hash(p: ^U8; n: INT): INT;
152-var h: U32; i: INT;
153-begin
154- h := 2166136261;
155- for i := 0 to n - 1 do h := (h xor U32(p[i])) * 16777619; end;
156- return INT(h & 7FFFFFFFH);
157-end;
158-
159-(* A table twice the size, and room for twice the names *)
160-proc grow;
161-var i, n, j: INT; ptrs: ^NamePtr; lens, hashes: ^INT;
162-begin
163- Mem.free(Heap.heap, ^U8(table));
164- tableMask := tableMask * 2 + 1;
165- table := words64(tableMask + 1);
166- for n := 0 to numNames - 1 do
167- i := nameHash[n] & tableMask;
168- while table[i] # 0 do i := (i + 1) & tableMask; end;
169- table[i] := n + 1;
170- end;
171- j := nameCap * 2;
172- ptrs := ^NamePtr(grab(j * SIZE(NamePtr)));
173- lens := ^INT(grab(j * SIZE(INT)));
174- hashes := ^INT(grab(j * SIZE(INT)));
175- for n := 0 to numNames - 1 do
176- ptrs[n] := namePtr[n];
177- lens[n] := nameLen[n];
178- hashes[n] := nameHash[n];
179- end;
180- Mem.free(Heap.heap, ^U8(namePtr));
181- Mem.free(Heap.heap, ^U8(nameLen));
182- Mem.free(Heap.heap, ^U8(nameHash));
183- namePtr := ptrs;
184- nameLen := lens;
185- nameHash := hashes;
186- nameCap := j;
187-end;
188-
189-(* Whether the n bytes at p and at q are the same *)
190-proc same(p, q: ^U8; n: INT): BOOL;
191-var i: INT;
192-begin
193- for i := 0 to n - 1 do
194- if p[i] # q[i] then return false; end;
195- end;
196- return true;
197-end;
198-
199-(* The number of the name of the n bytes at p; a new name gets the next *)
200-proc intern*(p: ^U8; n: INT): INT;
201-var h, i, k: INT;
202-begin
203- h := hash(p, n);
204- i := h & tableMask;
205- while table[i] # 0 do
206- k := table[i] - 1;
207- if (nameHash[k] = h) and (nameLen[k] = n) and same(namePtr[k], p, n) then
208- return k;
209- end;
210- i := (i + 1) & tableMask;
211- end;
212- if n > chunkLeft then
213- chunk := grab(PoolChunk);
214- chunkLeft := PoolChunk;
215- end;
216- COPY(chunk[0..n], p[0..n]);
217- k := numNames;
218- namePtr[k] := chunk;
219- nameLen[k] := n;
220- nameHash[k] := h;
221- chunk := chunk + n;
222- chunkLeft := chunkLeft - n;
223- INC(numNames);
224- table[i] := k + 1;
225- if numNames * 2 > tableMask then grow; end;
226- return k;
227-end;
228-
229-(* The name n, which stays as it is *)
230-proc nameOf*(n: INT): []U8;
231-begin
232- return namePtr[n][0..nameLen[n]];
233-end;
234-
235-(* Errors *)
236-
237-(* The current symbol *)
238-proc tokPos*: Diag.Pos;
239-begin
240- return {f: cur.f, a: cur.tokPos, b: cur.pos};
241-end;
242-
243-(* The place just after the symbol before the current one, where a
244- missing symbol belongs *)
245-proc afterPrev*: Diag.Pos;
246-begin
247- return {f: cur.f, a: cur.prevEnd, b: cur.prevEnd};
248-end;
249-
250-(* Where to say a symbol is missing: at the current symbol, unless it
251- starts a later line than the symbol before it, which is more likely
252- where the missing one belongs *)
253-proc missingPos*: Diag.Pos;
254-var i: INT; p: Diag.Pos;
255-begin
256- p := tokPos();
257- for i := cur.prevEnd to cur.tokPos - 1 do
258- if cur.buf[i] = '\n' then p := afterPrev(); end;
259- end;
260- return p;
261-end;
262-
263-(* From the start of p to the end of the symbol before the current one:
264- the whole of a construct that has just been read *)
265-proc spanFrom*(p: Diag.Pos): Diag.Pos;
266-begin
267- p.b := cur.prevEnd;
268- return p;
269-end;
270-
271-proc curLine*: INT;
272-begin
273- return cur.tokLine;
274-end;
275-
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
278- the distance. A column counts characters, as Diag's do. *)
279-proc lineCol*(a: INT): (INT, INT);
280-var i, line, start, col: INT;
281-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;
288- end;
289- col := 1;
290- for i := start to a - 1 do
291- if (cur.buf[i] & 0C0H) # 80H then INC(col); end;
292- end;
293- return line, col;
294-end;
295-
296-proc curCol*: INT;
297-var col: INT;
298-begin
299- _, col := lineCol(cur.tokPos);
300- return col;
301-end;
302-
303-(* An error at p, shown: the parser returns Failed, which try passes up
304- to where it goes on. *)
305-proc markAt*(p: Diag.Pos; msg: []U8): ERROR;
306-begin
307- Diag.error(p, msg);
308- return Failed;
309-end;
310-
311-proc mark*(msg: []U8): ERROR;
312-begin
313- return markAt(tokPos(), msg);
314-end;
315-
316-(* markAt, with a line of help after the message. *)
317-proc markHelp*(p: Diag.Pos; msg, hint: []U8): ERROR;
318-begin
319- Diag.error(p, msg);
320- Diag.help(hint);
321- return Failed;
322-end;
323-
324-(* An error in the text at bytes a to b of the file being read, which
325- stops the compiler: past it, the symbols can't be trusted. *)
326-proc markBytes(a, b: INT; msg: []U8);
327-begin
328- Diag.setQuiet(false);
329- Diag.error({f: cur.f, a: a, b: b}, msg);
330- Diag.finish;
331-end;
332-
333-proc lexError(msg: []U8);
334-begin
335- markBytes(cur.tokPos, cur.pos, msg);
336-end;
337-
338-(* The n characters at the scanner are how another language writes t:
339- an error, but reading goes on as if t were written. *)
340-proc slip(n: INT; t: Sym; msg: []U8);
341-begin
342- if not skipping then Diag.error({f: cur.f, a: cur.pos, b: cur.pos + n}, msg); end;
343- INC(cur.pos, n);
344- tok := t;
345-end;
346-
347-(* How an operator or reserved word is written, quoted, for messages. *)
348-proc symText*(s: Sym): []U8;
349-begin
350- if (s >= sPlus) and (s <= sBlank) then
351- return Diag.say("\"{}\"", [Fmt.str(ops[INT(s) - INT(sPlus)])]);
352- end;
353- return Diag.say("\"{}\"", [Fmt.str(words[INT(s) - INT(sAnd)])]);
354-end;
355-
356-(* The current symbol, for "expected ..., found ...": a name as it is,
357- a literal by its kind, an operator or reserved word quoted. *)
358-proc found*: []U8;
359-begin
360- match tok of
361- | sIdent: return nameOf(id);
362- | sInt: return "a number";
363- | sReal: return "a number";
364- | sChar: return "a character";
365- | sString: return "a string";
366- | sEof: return "the end of the file";
367- | else: return symText(tok);
368- end;
369-end;
370-
371-(* The current symbol is the first on its line: at the top level of a
372- module, by the usual layout, so where reading can start again. *)
373-proc atLineStart*: BOOL;
374-begin
375- return cur.tokPos = cur.tokLineStart;
376-end;
377-
378-(* The column the current symbol's line is indented to *)
379-proc indent*: INT;
380-var i: INT;
381-begin
382- i := cur.tokLineStart;
383- while (cur.buf[i] = ' ') or (cur.buf[i] = '\t') do INC(i); end;
384- return i - cur.tokLineStart + 1;
385-end;
386-
387-(* Files *)
388-
389-(* Name n is a reserved word *)
390-proc reserved*(n: INT): BOOL;
391-begin
392- return n < NumWords;
393-end;
394-
395-(* Reads the file at path to scan it; "" if it can, else why not *)
396-proc open*(path: []U8): []U8;
397-var fd, n, got, r, err: INT; info: Sys.Info;
398-begin
399- info, err := Sys.info(path);
400- if err = -2 then return "there is no such file"; end;
401- if err = -13 then return "permission denied"; end;
402- if err < 0 then return "it can't be opened"; end;
403- if not info.file then return "it isn't a file"; end;
404- fd := Sys.openRead(path);
405- if fd = -2 then return "there is no such file"; end;
406- if fd = -13 then return "permission denied"; end;
407- if fd < 0 then return "it can't be opened"; end;
408- n := INT(info.size);
409- cur.buf := grab(n + 1);
410- got := 0;
411- while got < n do
412- r := Sys.read(fd, cur.buf[got..n]);
413- if r <= 0 then Diag.fatal(Diag.say("can't read {}", [Fmt.str(path)])); end;
414- got := got + r;
415- end;
416- Sys.close(fd);
417- cur.buf[n] := 0; (* the sentinel that ends every scan *)
418- cur.len := n;
419- cur.pos := 0;
420- cur.line := 1;
421- cur.lineStart := 0;
422- cur.tokPos := 0;
423- cur.tokLine := 1;
424- cur.tokLineStart := 0;
425- cur.f := Diag.addFile(path, cur.buf, n);
426- return "";
427-end;
428-
429-proc saveScan*(var st: State);
430-begin
431- st := cur;
432- st.tok := tok;
433- st.ival := ival;
434- st.rval := rval;
435- st.id := id;
436-end;
437-
438-proc restoreScan*(st: State);
439-begin
440- cur := st;
441- tok := st.tok;
442- ival := st.ival;
443- rval := st.rval;
444- id := st.id;
445-end;
446-
447-(* UTF-8 *)
448-
449-(* Decodes the character at buf[pos], which is not ASCII, checking that
450- it is well formed; returns its code point and moves pos past it. *)
451-proc utf8(var pos: INT): INT;
452-var b0, b1, n, i, cp: INT; lo, hi: INT;
453-begin
454- b0 := INT(cur.buf[pos]);
455- lo := 80H;
456- hi := 0BFH;
457- n := 0;
458- cp := 0;
459- match b0 of
460- | 0C2H..0DFH: n := 1; cp := b0 & 1FH;
461- | 0E0H: n := 2; lo := 0A0H;
462- | 0E1H..0ECH, 0EEH, 0EFH: n := 2; cp := b0 & 0FH;
463- | 0EDH: n := 2; cp := 0DH; hi := 9FH; (* no surrogates *)
464- | 0F0H: n := 3; lo := 90H;
465- | 0F1H..0F3H: n := 3; cp := b0 & 7;
466- | 0F4H: n := 3; cp := 4; hi := 8FH; (* up to 10FFFFH *)
467- | else:
468- cur.tokPos := pos;
469- lexError("invalid UTF-8");
470- end;
471- for i := 1 to n do
472- b1 := INT(cur.buf[pos + i]);
473- if (b1 < lo) or (b1 > hi) or (pos + i >= cur.len) then
474- cur.tokPos := pos;
475- lexError("bad UTF-8");
476- end;
477- cp := cp shl 6 | (b1 & 3FH);
478- lo := 80H;
479- hi := 0BFH;
480- end;
481- pos := pos + n + 1;
482- return cp;
483-end;
484-
485-proc put(b: INT);
486-begin
487- if slen >= MaxStr then
488- lexError(Diag.say("a string holds at most {} bytes", [Fmt.int(MaxStr)]));
489- end;
490- sbuf[slen] := U8(b);
491- INC(slen);
492-end;
493-
494-proc putUtf8(cp: INT);
495-begin
496- if cp < 80H then
497- put(cp);
498- elsif cp < 800H then
499- put(0C0H | cp shr 6); put(80H | cp & 3FH);
500- elsif cp < 10000H then
501- put(0E0H | cp shr 12); put(80H | cp shr 6 & 3FH); put(80H | cp & 3FH);
502- else
503- put(0F0H | cp shr 18); put(80H | cp shr 12 & 3FH);
504- put(80H | cp shr 6 & 3FH); put(80H | cp & 3FH);
505- end;
506-end;
507-
508-proc isDigit(c: U8): BOOL;
509-begin
510- return (c >= '0') and (c <= '9');
511-end;
512-
513-proc isLetter(c: U8): BOOL;
514-begin
515- return (c >= 'a') and (c <= 'z') or (c >= 'A') and (c <= 'Z') or (c = '_');
516-end;
517-
518-proc hexVal(c: U8): INT;
519-begin
520- if isDigit(c) then return INT(c) - '0';
521- elsif (c >= 'A') and (c <= 'F') then return INT(c) - 'A' + 10;
522- elsif (c >= 'a') and (c <= 'f') then return INT(c) - 'a' + 10;
523- end;
524- return -1;
525-end;
526-
527-(* The text of the file from byte a up to but not including b *)
528-proc text(a, b: INT): []U8;
529-begin
530- return Diag.source({f: cur.f, a: a, b: b});
531-end;
532-
533-(* One character of a character or string literal, at buf[pos]: its code
534- point, or for \xHH, minus one minus the byte. *)
535-proc litChar(inString: BOOL): INT;
536-var c: U8; v, d, n, esc, digits: INT;
537-begin
538- c := cur.buf[cur.pos];
539- esc := cur.pos;
540- v := 0;
541- if c = '\\' then
542- INC(cur.pos);
543- c := cur.buf[cur.pos];
544- INC(cur.pos);
545- match c of
546- | 'n': v := 10;
547- | 't': v := 9;
548- | 'r': v := 13;
549- | '0': v := 0;
550- | '\\', '\'', '"': v := INT(c);
551- | 'x':
552- if not inString then markBytes(esc, cur.pos, "\\x is only for strings"); end;
553- d := hexVal(cur.buf[cur.pos]);
554- n := hexVal(cur.buf[cur.pos + 1]);
555- if (d < 0) or (n < 0) then markBytes(esc, cur.pos + 2, "\\x needs two hex digits"); end;
556- INC(cur.pos, 2);
557- v := -1 - (d * 16 + n);
558- | 'u':
559- if cur.buf[cur.pos] # '{' then markBytes(esc, cur.pos, "expected \"{\" after \\u"); end;
560- INC(cur.pos);
561- digits := cur.pos;
562- v := 0;
563- n := 0;
564- while hexVal(cur.buf[cur.pos]) >= 0 do
565- v := v * 16 + hexVal(cur.buf[cur.pos]);
566- INC(n);
567- INC(cur.pos);
568- if n > 6 then markBytes(esc, cur.pos, "a code point has at most 6 hex digits"); end;
569- end;
570- if (n = 0) or (cur.buf[cur.pos] # '}') then
571- markBytes(esc, cur.pos, "expected hex digits and \"}\" after \\u{");
572- end;
573- INC(cur.pos);
574- if (v > 10FFFFH) or (v >= 0D800H) and (v <= 0DFFFH) then
575- markBytes(esc, cur.pos, Diag.say("{} isn't a code point", [Fmt.str(text(digits, cur.pos - 1))]));
576- end;
577- | else:
578- markBytes(esc, cur.pos, Diag.say("unknown escape \\{}", [Fmt.char(c)]));
579- end;
580- elsif c >= 80H then
581- v := utf8(cur.pos);
582- elsif (c < ' ') or (c = 127) then
583- if inString then lexError("string not closed"); else lexError("character not closed"); end;
584- else
585- v := INT(c);
586- INC(cur.pos);
587- end;
588- return v;
589-end;
590-
591-(* Symbols *)
592-
593-proc comment;
594-var depth, open: INT; c: U8;
595-begin
596- depth := 1;
597- open := cur.pos;
598- INC(cur.pos, 2);
599- repeat
600- c := cur.buf[cur.pos];
601- if c = 0 then
602- if cur.pos >= cur.len then markBytes(open, open + 2, "comment not closed"); end;
603- INC(cur.pos);
604- elsif (c = '(') and (cur.buf[cur.pos + 1] = '*') then
605- INC(depth);
606- INC(cur.pos, 2);
607- elsif (c = '*') and (cur.buf[cur.pos + 1] = ')') then
608- DEC(depth);
609- INC(cur.pos, 2);
610- elsif c = '\n' then
611- INC(cur.pos);
612- INC(cur.line);
613- cur.lineStart := cur.pos;
614- elsif c >= 80H then
615- _ := utf8(cur.pos);
616- else
617- INC(cur.pos);
618- end;
619- until depth = 0;
620-end;
621-
622-(* Reading a decimal real exactly: the F64 nearest to digits times 10 to
623- an exponent, ties to the even one, which a library's reader doesn't
624- promise. The number is a fraction of two big integers, num / den,
625- scaled by 2^e until its whole part has 53 or 54 bits; that part and
626- the remainder give the bits and the rounding. *)
627-type
628- Big = record
629- n: INT; (* words in use; 0 is zero *)
630- w: [96]U32; (* least significant first *)
631- end;
632-(* 96 words, 3072 bits, are plenty: a string holds at most 255
633- digits, so readReal's den is at most 10^(330 + 255), about 2^1944,
634- and num below 10^310; the shift that follows makes the larger one at
635- most 54 bits longer than den, about 2000 bits in all. *)
636-
637-(* a := a * m + add *)
638-proc bigMul(var a: Big; m, add: U32);
639-var i: INT; c: U64;
640-begin
641- c := U64(add);
642- for i := 0 to a.n - 1 do
643- c := U64(a.w[i]) * U64(m) + c;
644- a.w[i] := U32(c);
645- c := c shr 32;
646- end;
647- if c # 0 then
648- a.w[a.n] := U32(c);
649- INC(a.n);
650- end;
651-end;
652-
653-proc bigShl(var a: Big; k: INT);
654-var i, ws, bits: INT;
655-begin
656- if a.n = 0 then return; end;
657- ws := k div 32;
658- bits := k mod 32;
659- a.w[a.n + ws] := 0;
660- for i := a.n - 1 to 0 by -1 do
661- if bits > 0 then a.w[i + ws + 1] := a.w[i + ws + 1] | (a.w[i] shr (32 - bits)); end;
662- a.w[i + ws] := a.w[i] shl bits;
663- end;
664- for i := 0 to ws - 1 do a.w[i] := 0; end;
665- INC(a.n, ws + 1);
666- while (a.n > 0) and (a.w[a.n - 1] = 0) do DEC(a.n); end;
667-end;
668-
669-proc bigShr1(var a: Big);
670-var i: INT;
671-begin
672- for i := 0 to a.n - 1 do
673- a.w[i] := a.w[i] shr 1;
674- if i + 1 < a.n then a.w[i] := a.w[i] | (a.w[i + 1] shl 31); end;
675- end;
676- while (a.n > 0) and (a.w[a.n - 1] = 0) do DEC(a.n); end;
677-end;
678-
679-(* -1, 0 or 1 as a is below, equal to or above b *)
680-proc bigCmp(a, b: Big): INT;
681-var i: INT;
682-begin
683- if a.n # b.n then
684- if a.n > b.n then return 1; end;
685- return -1;
686- end;
687- for i := a.n - 1 to 0 by -1 do
688- if a.w[i] # b.w[i] then
689- if a.w[i] > b.w[i] then return 1; end;
690- return -1;
691- end;
692- end;
693- return 0;
694-end;
695-
696-(* a := a - b, b not above a *)
697-proc bigSub(var a: Big; b: Big);
698-var i: INT; d: I64;
699-begin
700- d := 0;
701- for i := 0 to a.n - 1 do
702- d := d + I64(a.w[i]);
703- if i < b.n then d := d - I64(b.w[i]); end;
704- a.w[i] := U32(d);
705- if d < 0 then d := -1; else d := 0; end; (* a borrow *)
706- end;
707- while (a.n > 0) and (a.w[a.n - 1] = 0) do DEC(a.n); end;
708-end;
709-
710-proc bigBits(a: Big): INT;
711-var t: U32; bits: INT;
712-begin
713- if a.n = 0 then return 0; end;
714- bits := (a.n - 1) * 32;
715- t := a.w[a.n - 1];
716- while t # 0 do
717- INC(bits);
718- t := t shr 1;
719- end;
720- return bits;
721-end;
722-
723-(* s is digits, a point, digits, and maybe E, a sign and digits. False if
724- the value is past the largest F64; one below the smallest is 0. *)
725-proc readReal(s: []U8): (F64, BOOL);
726-var
727- num, den, d: Big; i, digits, e, ex: INT; neg, half, sticky: BOOL;
728- q, b: U64; x: F64; bits: ^F64;
729-begin
730- num.n := 0;
731- den.n := 1;
732- den.w[0] := 1;
733- digits := 0;
734- e := 0;
735- i := 0;
736- while (i < LEN(s)) and (s[i] # 'E') do
737- if s[i] = '.' then
738- e := 1;
739- else
740- bigMul(num, 10, U32(INT(s[i]) - '0'));
741- if num.n > 0 then INC(digits); end; (* counted from the first that isn't 0 *)
742- if e > 0 then INC(e); end;
743- end;
744- INC(i);
745- end;
746- if e > 0 then e := 1 - e; end; (* minus the digits after the point *)
747- ex := 0;
748- neg := false;
749- if i < LEN(s) then
750- INC(i);
751- neg := s[i] = '-';
752- if (s[i] = '+') or (s[i] = '-') then INC(i); end;
753- while i < LEN(s) do
754- if ex < 100000 then ex := ex * 10 + INT(s[i]) - '0'; end;
755- INC(i);
756- end;
757- end;
758- if neg then ex := -ex; end;
759- INC(e, ex);
760- x := 0.0;
761- if num.n = 0 then return x, true; end;
762- if digits + e > 310 then return x, false; end; (* 10^310 is past every F64 *)
763- if digits + e < -330 then return x, true; end; (* and 10^-330 below half the least *)
764- for i := 1 to e do bigMul(num, 10, 0); end;
765- for i := 1 to -e do bigMul(den, 10, 0); end;
766- (* num / den 2^-e from 2^52 to 2^54, but not past the least exponent *)
767- e := bigBits(num) - bigBits(den) - 53;
768- if e < -1074 then e := -1074; end;
769- if e < 0 then bigShl(num, -e); else bigShl(den, e); end;
770- (* q, its whole part, by long division; num is left the remainder *)
771- d := den;
772- bigShl(d, 53);
773- q := 0;
774- for i := 53 to 0 by -1 do
775- if bigCmp(num, d) >= 0 then
776- bigSub(num, d);
777- q := q | (U64(1) shl i);
778- end;
779- bigShr1(d);
780- end;
781- if q >= U64(1) shl 53 then (* a bit too many: it rounds *)
782- half := (q & 1) # 0;
783- sticky := num.n > 0;
784- q := q shr 1;
785- INC(e);
786- else (* the remainder against half of den *)
787- bigShl(num, 1);
788- i := bigCmp(num, den);
789- half := i >= 0;
790- sticky := i > 0;
791- end;
792- if half and (sticky or ((q & 1) # 0)) then
793- INC(q);
794- if q = U64(1) shl 53 then
795- q := q shr 1;
796- INC(e);
797- end;
798- end;
799- if e > 971 then return x, false; end;
800- if q >= U64(1) shl 52 then
801- b := U64(e + 1075) shl 52 | (q & (U64(1) shl 52 - 1));
802- else
803- b := q; (* below the least normal, e is -1074 *)
804- end;
805- bits := ^F64(ADR(b));
806- return bits^, true;
807-end;
808-
809-proc number;
810-var start, i, d: INT; allDec, ok: BOOL; v: U64;
811-begin
812- start := cur.pos;
813- allDec := true;
814- while isDigit(cur.buf[cur.pos]) or (cur.buf[cur.pos] >= 'A') and (cur.buf[cur.pos] <= 'F') do
815- if cur.buf[cur.pos] > '9' then allDec := false; end;
816- INC(cur.pos);
817- end;
818- if cur.buf[cur.pos] = 'H' then
819- v := 0;
820- for i := start to cur.pos - 1 do
821- if v shr 60 # 0 then lexError(Diag.say("{} is too big for U64", [Fmt.str(text(start, cur.pos))])); end;
822- v := v * 16 + U64(hexVal(cur.buf[i]));
823- end;
824- INC(cur.pos);
825- tok := sInt;
826- ival := I64(v); (* 16 digits are the bits of a 64-bit word *)
827- elsif (cur.buf[cur.pos] = '.') and isDigit(cur.buf[cur.pos + 1]) then
828- if not allDec then lexError("a decimal number has only the digits 0 to 9"); end;
829- INC(cur.pos);
830- while isDigit(cur.buf[cur.pos]) do INC(cur.pos); end;
831- if cur.buf[cur.pos] = 'E' then
832- INC(cur.pos);
833- if (cur.buf[cur.pos] = '+') or (cur.buf[cur.pos] = '-') then INC(cur.pos); end;
834- if not isDigit(cur.buf[cur.pos]) then lexError("expected a digit in the exponent"); end;
835- while isDigit(cur.buf[cur.pos]) do INC(cur.pos); end;
836- end;
837- if cur.pos - start > 255 then lexError("a number has at most 255 characters"); end;
838- rval, ok := readReal(cur.buf[start..cur.pos]);
839- if not ok then lexError(Diag.say("{} is out of the range of F64", [Fmt.str(text(start, cur.pos))])); end;
840- tok := sReal;
841- else
842- if not allDec then lexError("a hex number ends with H"); end;
843- v := 0;
844- for i := start to cur.pos - 1 do
845- d := INT(cur.buf[i]) - '0';
846- if v > (U64(9223372036854775807) - U64(d)) div 10 then
847- lexError(Diag.say("{} is too big for I64", [Fmt.str(text(start, cur.pos))]));
848- end;
849- v := v * 10 + U64(d);
850- end;
851- tok := sInt;
852- ival := I64(v);
853- end;
854- if nameChar[cur.buf[cur.pos]] then
855- lexError("a name can't start with a digit");
856- end;
857-end;
858-
859-(* Reads the next symbol *)
860-proc next*;
861-var c: U8; start, h, v, i: INT;
862-begin
863- cur.prevEnd := cur.pos;
864- repeat
865- c := cur.buf[cur.pos];
866- while (c = ' ') or (c = '\t') or (c = '\r') or (c = '\n') do
867- if c = '\n' then
868- INC(cur.line);
869- cur.lineStart := cur.pos + 1;
870- end;
871- INC(cur.pos);
872- c := cur.buf[cur.pos];
873- end;
874- if (c = '(') and (cur.buf[cur.pos + 1] = '*') then
875- comment;
876- c := ' ';
877- end;
878- until c # ' ';
879- cur.tokPos := cur.pos;
880- cur.tokLine := cur.line;
881- cur.tokLineStart := cur.lineStart;
882- if single[c] # sNull then
883- INC(cur.pos);
884- tok := single[c];
885- return;
886- end;
887- match c of
888- | '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
892- lexError(Diag.say("a name has at most {} characters", [Fmt.int(MaxIdent)]));
893- end;
894- h := intern(cur.buf + start, cur.pos - start);
895- if (cur.pos - start = 1) and (c = '_') then
896- tok := sBlank;
897- elsif h < NumWords then
898- tok := Sym(INT(sAnd) + h);
899- else
900- tok := sIdent;
901- id := h;
902- end;
903- | '0'..'9': number;
904- | '\'':
905- INC(cur.pos);
906- if cur.buf[cur.pos] = '\'' then lexError("empty character"); end;
907- v := litChar(false);
908- if cur.buf[cur.pos] # '\'' then
909- (* 'ab': several characters, as some languages write a string *)
910- i := cur.pos;
911- while (cur.buf[i] # '\'') and (cur.buf[i] # '\n') and (cur.buf[i] # 0) do INC(i); end;
912- if cur.buf[i] = '\'' then
913- markBytes(cur.tokPos, i + 1,
914- Diag.say("a character is one character: the string is \"{}\"", [Fmt.str(text(cur.tokPos + 1, i))]));
915- else
916- lexError("character not closed");
917- end;
918- end;
919- INC(cur.pos);
920- tok := sChar;
921- ival := I64(v);
922- | '"':
923- INC(cur.pos);
924- slen := 0;
925- while cur.buf[cur.pos] # '"' do
926- v := litChar(true);
927- if v < 0 then put(-1 - v); else putUtf8(v); end;
928- end;
929- INC(cur.pos);
930- sbuf[slen] := 0;
931- tok := sString;
932- | '=':
933- if cur.buf[cur.pos + 1] = '=' then
934- slip(2, sEql, "comparing is written =, not ==");
935- else
936- INC(cur.pos);
937- tok := sEql;
938- end;
939- | '&':
940- if cur.buf[cur.pos + 1] = '&' then
941- slip(2, sAnd, "\"and\" is written and, not &&");
942- else
943- INC(cur.pos);
944- tok := sAmp;
945- end;
946- | '<':
947- INC(cur.pos);
948- if cur.buf[cur.pos] = '=' then INC(cur.pos); tok := sLeq; else tok := sLss; end;
949- | '>':
950- INC(cur.pos);
951- if cur.buf[cur.pos] = '=' then INC(cur.pos); tok := sGeq; else tok := sGtr; end;
952- | ':':
953- INC(cur.pos);
954- if cur.buf[cur.pos] = '=' then INC(cur.pos); tok := sBecomes; else tok := sColon; end;
955- | '.':
956- INC(cur.pos);
957- if cur.buf[cur.pos] = '.' then
958- INC(cur.pos);
959- if cur.buf[cur.pos] = '.' then INC(cur.pos); tok := sEllipsis; else tok := sUpto; end;
960- else
961- tok := sPeriod;
962- end;
963- | '|':
964- if cur.buf[cur.pos + 1] = '|' then
965- slip(2, sOr, "\"or\" is written or, not ||");
966- else
967- INC(cur.pos);
968- tok := sBar;
969- end;
970- | '!':
971- if cur.buf[cur.pos + 1] = '=' then
972- slip(2, sNeq, "\"not equal\" is written #, not !=");
973- else
974- slip(1, sNot, "\"not\" is written not, not !");
975- end;
976- | 0:
977- if cur.pos < cur.len then markBytes(cur.pos, cur.pos + 1, "NUL byte in the text"); end;
978- tok := sEof;
979- | else:
980- if c >= 80H then lexError("only ASCII outside strings, characters and comments"); end;
981- markBytes(cur.pos, cur.pos + 1, Diag.say("unexpected character \"{}\"", [Fmt.char(c)]));
982- end;
983-end;
984-
985-var i: INT;
986-
987-begin
988- for i := 0 to 255 do nameChar[i] := isLetter(U8(i)) or isDigit(U8(i)); end;
989- for i := 0 to NumOps - 1 do
990- if (LEN(ops[i]) = 1) and (Str.find(alone, ops[i]) >= 0) then
991- single[ops[i][0]] := Sym(INT(sPlus) + i);
992- end;
993- end;
994- chunkLeft := 0;
995- nameCap := 1 shl 12;
996- namePtr := ^NamePtr(grab(nameCap * SIZE(NamePtr)));
997- nameLen := ^INT(grab(nameCap * SIZE(INT)));
998- nameHash := ^INT(grab(nameCap * SIZE(INT)));
999- tableMask := 2 * nameCap - 1;
1000- table := words64(tableMask + 1);
1001- for i := 0 to NumWords - 1 do _ := intern(ADR(words[i][0]), LEN(words[i])); end;
1002-end Scan.

self/Sym.raz deleted +0 -684

@@ -1,684 +0,0 @@
1-(* Sym: types, objects and scopes.
2-
3- Every name the program declares becomes an object (Obj): a constant,
4- type, variable, procedure, module, record field, variant case or
5- built-in. Every type is a Type. Objects are found through one hash
6- table keyed by scope and name, so a lookup costs the same however
7- big a module grows. A scope is just a number: the universe is 0,
8- and each module, procedure, record and match arm gets a fresh one.
9-
10- Depends on: Scan, for names and errors; Diag, for positions.
11- Leaves out: code. Where a variable lives is decided here (frame
12- offsets, chunk numbers), but nothing is emitted.
13-
14- Exported variables can't be set from outside, so setCurModule is
15- how the parser says which module it is in. A name that holds a
16- reserved word of raz is spelled otherwise: a record's `module` is
17- its `home`, an object's `link` its `chain`. *)
18-module Sym;
19-import Mem, Heap, Buf, Fmt, Diag, Scan;
20-
21-type
22- Form* = (fNone, fBool, fInt, fReal, fConst, fNil, fStr, fPtr, fArray,
23- fSlice, fRecord, fVariant, fProc, fEnum, fSet, fError);
24- (* fConst is the type of an untyped integer constant; fStr of a string
25- literal, whose length the literal carries. F32 and F64 are fReal,
26- told apart by size, and so is tRConst, an untyped real constant. *)
27-
28- Class* = (oConst, oType, oVar, oProc, oModule, oField, oCase, oBuiltin);
29-
30- Type* = record
31- form*: Form;
32- size*, align*: I64;
33- signed*: BOOL; (* fInt *)
34- vol*: BOOL; (* fPtr: ^VOLATILE *)
35- packd*: BOOL; (* fRecord *)
36- variadic*: BOOL; (* fProc: ends in ... *)
37- tuple*: BOOL; (* fRecord: the results of a procedure that has several *)
38- base*: ^Type; (* fPtr, fArray, fSlice: what it holds; fProc: result *)
39- len*: I64; (* fArray: elements; fProc: parameters; fVariant: cases; a tuple: results *)
40- fields*: ^Obj; (* fRecord: fields; fVariant: cases; fProc: parameters *)
41- scope*: INT; (* fRecord: the scope of its fields *)
42- fwd*: INT; (* fPtr whose base isn't declared yet: its name, else -1 *)
43- obj*: ^Obj; (* the declaration that names it, or nil *)
44- home*: ^Module; (* the module that built it *)
45- end;
46-
47- Obj* = record
48- cls*: Class;
49- name*: INT;
50- exported*: BOOL;
51- typ*: ^Type;
52- next*: ^Obj; (* the next in its list: scope, fields, parameters *)
53- scope*: INT; (* where it is declared *)
54- pos*: Diag.Pos; (* where its name is declared, for messages *)
55- val*: I64; (* oConst: value; oBuiltin: which; oCase: tag;
56- oField: offset; oVar: frame offset *)
57- chunk*: INT; (* global oVar, oProc, string oConst: its chunk *)
58- lev*: INT; (* oVar: 0 for a module variable, 1 for a local *)
59- ind*: BOOL; (* oVar: the frame slot holds the variable's address *)
60- off*: I64; (* oVar with ind: added to that address *)
61- isVar*: BOOL; (* a var parameter *)
62- param*: BOOL; (* oVar: a parameter *)
63- used*: BOOL; (* named somewhere but in its own body *)
64- read*: BOOL; (* oVar: named other than as what := assigns *)
65- fwd*: BOOL; (* oProc: declared forward, no body yet *)
66- isCode*: BOOL; (* oProc: a code procedure *)
67- openEnd*: BOOL; (* oProc: has results, and may reach its end *)
68- reg*: INT; (* oVar: the register it lives in, or 0 if in memory;
69- for a slice, the one its pointer is in *)
70- reg2*: INT; (* oVar: a slice in registers: the one its length is in *)
71- ext*: BOOL; (* oProc, oVar: C's, reached through its chunk, which
72- holds its address *)
73- fields*: ^Obj; (* oCase: its fields *)
74- home*: ^Module; (* oModule: the module; others: where declared *)
75- chain*: ^Obj; (* the next declaration of its module, top-level or
76- local *)
77- end;
78-
79- (* The arguments of a generic module's instance: a type, or a
80- procedure (o) and its type. *)
81- Args* = record
82- n*: INT;
83- t*: [8]^Type;
84- o*: [8]^Obj;
85- pos*: [8]Diag.Pos; (* where each argument is, for messages *)
86- at*: Diag.Pos; (* where the import is *)
87- end;
88-
89- Import* = record
90- home*: ^Module;
91- next*: ^Import;
92- end;
93-
94- (* A library a module links, by its name, as interned *)
95- Lib* = record
96- name*: INT;
97- next*: ^Lib;
98- end;
99-
100- Module* = record
101- name*: INT;
102- sname*: INT; (* the name of its symbols: List(I64) for an instance *)
103- args*: Args;
104- scope*: INT;
105- path*: []U8;
106- first*, last*: ^Obj; (* its top-level declarations, in order *)
107- locals*, lastLocal*: ^Obj; (* its procedures' declarations, in order *)
108- imports*: ^Import;
109- body*: INT; (* the chunk of its body, or -1 *)
110- done*: BOOL; (* compiled to the end *)
111- checkOnly*: BOOL; (* read only to check another file's interface *)
112- used*: BOOL; (* imported, through others, by the main module *)
113- usesC*: BOOL; (* has an extern, or links a library *)
114- linkStatic*: BOOL; (* says link static *)
115- libs*: ^Lib; (* the libraries it links *)
116- next*: ^Module; (* modules in the order they were finished *)
117- end;
118-
119-const
120- (* built-in procedures *)
121- bSize* = 0; bAdr* = 1; bLen* = 2; bNew* = 3; bMsg* = 4; bSyscall* = 5;
122- bFence* = 6; bCas* = 7; bXchg* = 8; bXadd* = 9; bArgc* = 10; bArgv* = 11;
123- bInc* = 12; bDec* = 13; bCopy* = 14;
124-
125- MaxDepth* = 64; (* scopes open at once *)
126-
127-var
128- tI8*, tI16*, tI32*, tI64*, tU8*, tU16*, tU32*, tU64*: ^Type;
129- tInt*, tUInt*: ^Type; (* INT and UINT, as big as an address: 8 bytes here *)
130- tBool*, tF32*, tReal*, tRConst*, tError*, tConst*, tNil*, tStr*, tNone*, tPtrU8*, tBytes*: ^Type;
131- tPoison*: ^Type; (* of a name reported as not declared *)
132- curModule*: ^Module;
133-
134- scopes: [MaxDepth]INT;
135- depth: INT;
136- nextScope: INT;
137- hashTab: ^^Obj;
138- hashMask, hashCount: INT;
139-
140-proc setCurModule*(m: ^Module);
141-begin
142- curModule := m;
143-end;
144-
145-proc newType*(form: Form; size, align: I64): ^Type;
146-var t: ^Type;
147-begin
148- NEW(t, Heap.heap);
149- if t = nil then Diag.fatal("out of memory"); end;
150- t^.form := form;
151- t^.size := size;
152- t^.align := align;
153- t^.fwd := -1;
154- t^.home := curModule;
155- return t;
156-end;
157-
158-proc newObj*(cls: Class; name: INT; typ: ^Type): ^Obj;
159-var o: ^Obj;
160-begin
161- NEW(o, Heap.heap);
162- if o = nil then Diag.fatal("out of memory"); end;
163- o^.cls := cls;
164- o^.name := name;
165- o^.typ := typ;
166- o^.chunk := -1;
167- o^.home := curModule;
168- o^.pos := Scan.tokPos();
169- return o;
170-end;
171-
172-(* Scopes *)
173-
174-proc newScope*: INT;
175-begin
176- INC(nextScope);
177- return nextScope;
178-end;
179-
180-proc openScope*(s: INT): ERROR;
181-begin
182- if depth = MaxDepth then
183- return Scan.mark(Diag.say("scopes nested more than {} deep", [Fmt.int(MaxDepth)]));
184- end;
185- scopes[depth] := s;
186- INC(depth);
187- return nil;
188-end;
189-
190-proc closeScope*;
191-begin
192- DEC(depth);
193-end;
194-
195-(* An imported module is compiled in the middle of another, and must
196- see only the universe and itself. The scopes open are kept in saved,
197- and their number is the result. *)
198-proc saveScopes*(saved: []INT): INT;
199-var i, d: INT;
200-begin
201- d := depth;
202- for i := 0 to depth - 1 do saved[i] := scopes[i]; end;
203- depth := 1;
204- return d;
205-end;
206-
207-proc restoreScopes*(d: INT; saved: []INT);
208-var i: INT;
209-begin
210- depth := d;
211- for i := 0 to depth - 1 do scopes[i] := saved[i]; end;
212-end;
213-
214-proc scopeDepth*: INT;
215-begin
216- return depth;
217-end;
218-
219-(* Closes the scopes opened since there were d, after an error *)
220-proc cutScopes*(d: INT);
221-begin
222- depth := d;
223-end;
224-
225-proc topScope*: INT;
226-begin
227- return scopes[depth - 1];
228-end;
229-
230-(* Where the search for name in scope s starts in the hash table: each
231- number is multiplied by an odd constant near 2^32 or 2^16 over the
232- golden ratio (Knuth's multiplicative hashing), which spreads the low
233- bits the mask keeps. *)
234-proc slot(s, name: INT): INT;
235-begin
236- return INT(((U32(s & 0FFFFFFFFH) * 2654435761) xor (U32(name & 0FFFFFFFFH) * 40503)) & U32(hashMask));
237-end;
238-
239-(* A table of n slots, all empty *)
240-proc emptyTable(n: INT): ^^Obj;
241-var t: ^^Obj; i: INT;
242-begin
243- t := ^^Obj(Scan.grab(n * SIZE(^Obj)));
244- for i := 0 to n - 1 do t[i] := nil; end;
245- return t;
246-end;
247-
248-(* Doubles the table, which insert keeps at most half full so that the
249- linear probing stays short, and puts every entry in its new slot. *)
250-proc rehash;
251-var old: ^^Obj; n, i, j: INT;
252-begin
253- old := hashTab;
254- n := hashMask + 1;
255- hashMask := n * 2 - 1;
256- hashTab := emptyTable(n * 2);
257- for i := 0 to n - 1 do
258- if old[i] # nil then
259- j := slot(old[i]^.scope, old[i]^.name);
260- while hashTab[j] # nil do j := (j + 1) & hashMask; end;
261- hashTab[j] := old[i];
262- end;
263- end;
264- Mem.free(Heap.heap, ^U8(old));
265-end;
266-
267-proc insert*(obj: ^Obj; s: INT): ERROR;
268-var i: INT; o: ^Obj;
269-begin
270- i := slot(s, obj^.name);
271- o := hashTab[i];
272- while o # nil do
273- if (o^.scope = s) and (o^.name = obj^.name) then
274- Diag.error(obj^.pos, Diag.say("{} is declared twice", [Fmt.str(Scan.nameOf(obj^.name))]));
275- Diag.note(o^.pos, "the first one is here");
276- return Scan.Failed;
277- end;
278- i := (i + 1) & hashMask;
279- o := hashTab[i];
280- end;
281- obj^.scope := s;
282- hashTab[i] := obj;
283- INC(hashCount);
284- if hashCount * 2 > hashMask then rehash; end;
285- return nil;
286-end;
287-
288-proc find*(s, name: INT): ^Obj;
289-var i: INT; o: ^Obj;
290-begin
291- i := slot(s, name);
292- o := hashTab[i];
293- while o # nil do
294- if (o^.scope = s) and (o^.name = name) then return o; end;
295- i := (i + 1) & hashMask;
296- o := hashTab[i];
297- end;
298- return nil;
299-end;
300-
301-proc lookup*(name: INT): ^Obj;
302-var i: INT; o: ^Obj;
303-begin
304- for i := depth - 1 to 0 by -1 do
305- o := find(scopes[i], name);
306- if o # nil then return o; end;
307- end;
308- return nil;
309-end;
310-
311-proc min(a, b: INT): INT;
312-begin
313- if a < b then return a; end;
314- return b;
315-end;
316-
317-(* c, in capitals if it is a letter *)
318-proc up(c: U8): U8;
319-begin
320- if (c >= 97) and (c <= 122) then return c - 32; end;
321- return c;
322-end;
323-
324-(* How far apart two names are: the edits, a character put in, taken out,
325- changed or swapped with the next, that make one the other, ignoring
326- case. *)
327-proc distance(a, b: []U8): INT;
328-var d: [Scan.MaxIdent + 2][Scan.MaxIdent + 2]INT; i, j, c: INT;
329-begin
330- for i := 0 to LEN(a) do d[i][0] := i; end;
331- for j := 0 to LEN(b) do d[0][j] := j; end;
332- for i := 1 to LEN(a) do
333- for j := 1 to LEN(b) do
334- c := 1;
335- if up(a[i - 1]) = up(b[j - 1]) then c := 0; end;
336- d[i][j] := min(min(d[i - 1][j] + 1, d[i][j - 1] + 1), d[i - 1][j - 1] + c);
337- if (i > 1) and (j > 1) and (up(a[i - 1]) = up(b[j - 2]))
338- and (up(a[i - 2]) = up(b[j - 1])) then
339- d[i][j] := min(d[i][j], d[i - 2][j - 2] + 1);
340- end;
341- end;
342- end;
343- return d[LEN(a)][LEN(b)];
344-end;
345-
346-(* The name spelled most like name, for "did you mean": in scope s, if
347- it can be reached from here, or in the scopes in reach if s < 0; nil
348- if none is within an edit for every three characters. Only after an
349- error, so it looks at every object. *)
350-proc closest*(name, s: INT): ^Obj;
351-var i, j, d, best: INT; o, found: ^Obj; n: []U8; reach: BOOL;
352-begin
353- n := Scan.nameOf(name);
354- best := LEN(n) div 3 + 1;
355- found := nil;
356- for i := 0 to hashMask do
357- o := hashTab[i];
358- if (o = nil) or (o^.name = name) or (o^.name < 0) or (o^.typ = tPoison) then
359- reach := false;
360- elsif s >= 0 then
361- reach := (o^.scope = s) and (o^.exported or (o^.home = curModule));
362- else
363- reach := false;
364- for j := 0 to depth - 1 do reach := reach or (o^.scope = scopes[j]); end;
365- end;
366- if reach then
367- d := distance(n, Scan.nameOf(o^.name));
368- if d < best then best := d; found := o; end;
369- end;
370- end;
371- return found;
372-end;
373-
374-(* Types *)
375-
376-proc alignUp*(x, a: I64): I64;
377-begin
378- return (x + a - 1) div a * a;
379-end;
380-
381-proc isInt*(t: ^Type): BOOL;
382-begin
383- return t^.form in {fInt, fConst};
384-end;
385-
386-proc isScalar*(t: ^Type): BOOL;
387-begin
388- return t^.form in {fBool, fInt, fReal, fConst, fNil, fPtr, fProc, fEnum, fSet, fError};
389-end;
390-
391-proc isAggregate*(t: ^Type): BOOL;
392-begin
393- return t^.form in {fArray, fSlice, fRecord, fVariant};
394-end;
395-
396-(* Whether a result field f is a single value of at most a word, not a real *)
397-proc oneWord(f: ^Obj): BOOL;
398-begin
399- return isScalar(f^.typ) and (f^.typ^.form # fReal) and (f^.typ^.size <= 8);
400-end;
401-
402-(* Whether a procedure's result t is two words, which come back in rax
403- and rdx, as System V returns a struct of two integers: a slice (its
404- pointer, then its length), or two results that are each a single
405- value of 8 bytes at most and not a real. *)
406-proc inTwoRegs*(t: ^Type): BOOL;
407-begin
408- if t^.form = fSlice then return true; end;
409- return t^.tuple and (t^.len = 2) and oneWord(t^.fields) and oneWord(t^.fields^.next);
410-end;
411-
412-(* Whether a procedure's result t comes back in memory the caller
413- provides, whose address the caller passes as a hidden first argument,
414- in rdi: any result that is neither one value, in rax or xmm0, nor two
415- words, in rax and rdx. *)
416-proc behindPointer*(t: ^Type): BOOL;
417-begin
418- return isAggregate(t) and not inTwoRegs(t);
419-end;
420-
421-proc fits*(v: I64; t: ^Type): BOOL;
422-begin
423- if t^.form # fInt then return t^.form = fConst; end;
424- match t^.size of
425- | 1:
426- if t^.signed then return (v >= -128) and (v <= 127); end;
427- return (v >= 0) and (v <= 255);
428- | 2:
429- if t^.signed then return (v >= -32768) and (v <= 32767); end;
430- return (v >= 0) and (v <= 65535);
431- | 4:
432- if t^.signed then return (v >= -2147483648) and (v <= 2147483647); end;
433- return (v >= 0) and (v <= 4294967295);
434- | else: return t^.signed or (v >= 0);
435- end;
436-end;
437-
438-proc same*(a, b: ^Type): BOOL; forward;
439-
440-(* Whether two procedure types, or two tuples, are alike: the same
441- results and parameters, in the same modes *)
442-proc alikeShape(a, b: ^Type): BOOL;
443-var p, q: ^Obj;
444-begin
445- (* a record is the same only as itself, but for several results *)
446- if (a^.form = fRecord) and not (a^.tuple and b^.tuple) then return false; end;
447- if (a^.len # b^.len) or (a^.variadic # b^.variadic) then return false; end;
448- if (a^.base = nil) # (b^.base = nil) then return false; end;
449- if (a^.base # nil) and not same(a^.base, b^.base) then return false; end;
450- p := a^.fields; q := b^.fields;
451- while p # nil do
452- if (p^.isVar # q^.isVar) or not same(p^.typ, q^.typ) then return false; end;
453- p := p^.next; q := q^.next;
454- end;
455- return true;
456-end;
457-
458-(* Structural sameness of two types. Named types are the same only if
459- they are one declaration; a type with no name is the same as another
460- built alike. *)
461-proc alike(a, b: ^Type): BOOL;
462-begin
463- if a = b then return true; end;
464- if a^.form # b^.form then return false; end;
465- match a^.form of
466- | fPtr: return (a^.vol = b^.vol) and same(a^.base, b^.base);
467- | fArray: return (a^.len = b^.len) and same(a^.base, b^.base);
468- | fSlice: return same(a^.base, b^.base);
469- | fSet: return same(a^.base, b^.base);
470- | fProc: return alikeShape(a, b);
471- | fRecord: return alikeShape(a, b);
472- | else: return false;
473- end;
474-end;
475-
476-proc same*(a, b: ^Type): BOOL;
477-begin
478- if a = b then return true; end;
479- if (a = nil) or (b = nil) then return false; end;
480- if (a^.obj # nil) and (b^.obj # nil) then return false; end;
481- return alike(a, b);
482-end;
483-
484-(* What a type is called, added to b: the names a program gives it, else
485- what it is made of *)
486-proc typeText(b: ^Buf.Buf; t: ^Type);
487-var f: ^Obj;
488-begin
489- if t = nil then Buf.str(b, "nothing"); return; end;
490- if t^.obj # nil then
491- if (t^.obj^.home # nil) and (t^.obj^.home # curModule) then
492- Buf.str(b, Scan.nameOf(t^.obj^.home^.sname));
493- Buf.str(b, ".");
494- end;
495- Buf.str(b, Scan.nameOf(t^.obj^.name));
496- return;
497- end;
498- match t^.form of
499- | fConst: Buf.str(b, "an integer constant");
500- | fReal: Buf.str(b, "a real constant");
501- | fNil: Buf.str(b, "nil");
502- | fStr: Buf.str(b, "a string");
503- | fPtr:
504- if t^.vol then Buf.str(b, "^VOLATILE "); else Buf.str(b, "^"); end;
505- typeText(b, t^.base);
506- | fArray:
507- Fmt.write(b, "[{}]", [Fmt.int(t^.len)]);
508- typeText(b, t^.base);
509- | fSlice:
510- Buf.str(b, "[]");
511- typeText(b, t^.base);
512- | fRecord:
513- if not t^.tuple then
514- Buf.str(b, "record");
515- else
516- Buf.str(b, "(");
517- f := t^.fields;
518- while f # nil do
519- typeText(b, f^.typ);
520- f := f^.next;
521- if f # nil then Buf.str(b, ", "); end;
522- end;
523- Buf.str(b, ")");
524- end;
525- | fVariant: Buf.str(b, "variant");
526- | fProc:
527- Buf.str(b, "proc(");
528- f := t^.fields;
529- while f # nil do
530- if f^.isVar then Buf.str(b, "var "); end;
531- typeText(b, f^.typ);
532- f := f^.next;
533- if f # nil then Buf.str(b, ", "); end;
534- end;
535- Buf.str(b, ")");
536- if t^.base # nil then
537- Buf.str(b, ": ");
538- typeText(b, t^.base);
539- end;
540- | else: Buf.str(b, "?");
541- end;
542-end;
543-
544-(* A name for t, kept for good, as every message is *)
545-proc typeName*(t: ^Type): []U8;
546-var b: ^Buf.Buf;
547-begin
548- b := ^Buf.Buf(Scan.grab(SIZE(Buf.Buf)));
549- Buf.init(b, Heap.heap);
550- typeText(b, t);
551- return Buf.bytes(b);
552-end;
553-
554-(* A fingerprint of what a declaration exports, for the interface
555- check: two files of one module export the same thing when their
556- fingerprints agree. A named type counts by its name, so that a type
557- declared in each file stands for the other's. *)
558-proc mix(var h: U64; v: I64);
559-begin
560- h := (h xor U64(v)) * 1099511628211; (* FNV-1a's 64-bit prime *)
561-end;
562-
563-proc bit(f: BOOL): INT;
564-begin
565- if f then return 1; end;
566- return 0;
567-end;
568-
569-proc shape(var h: U64; t: ^Type; top: BOOL);
570-var f, g: ^Obj;
571-begin
572- if t = nil then mix(h, -1); return; end;
573- if (t^.obj # nil) and not top then
574- mix(h, t^.obj^.name);
575- if t^.obj^.home # nil then mix(h, t^.obj^.home^.sname); end;
576- return;
577- end;
578- mix(h, INT(t^.form));
579- mix(h, bit(t^.vol) + 2 * bit(t^.variadic));
580- mix(h, t^.len);
581- if t^.form in {fPtr, fArray, fSlice, fProc, fSet} then shape(h, t^.base, false); end;
582- f := t^.fields;
583- while f # nil do
584- if (t^.form # fRecord) or f^.exported then
585- mix(h, f^.name);
586- mix(h, bit(f^.isVar));
587- shape(h, f^.typ, false);
588- g := f^.fields;
589- while g # nil do shape(h, g^.typ, false); g := g^.next; end;
590- end;
591- f := f^.next;
592- end;
593-end;
594-
595-proc fingerprint*(o: ^Obj): U64;
596-var h: U64; f: ^Obj;
597-begin
598- h := 0CBF29CE484222325H; (* FNV-1a's 64-bit offset basis *)
599- mix(h, INT(o^.cls));
600- if o^.cls = oCase then
601- mix(h, o^.val);
602- f := o^.fields;
603- while f # nil do shape(h, f^.typ, false); f := f^.next; end;
604- else
605- shape(h, o^.typ, o^.cls = oType);
606- end;
607- return h;
608-end;
609-
610-(* The universe *)
611-
612-proc basic(name: []U8; form: Form; size: I64; signed: BOOL): ^Type;
613-var t: ^Type; o: ^Obj;
614-begin
615- t := newType(form, size, size);
616- t^.signed := signed;
617- o := newObj(oType, Scan.intern(ADR(name[0]), LEN(name)), t);
618- o^.exported := true;
619- t^.obj := o;
620- _ := insert(o, 0);
621- return t;
622-end;
623-
624-proc enter(name: []U8; cls: Class; t: ^Type; v: I64);
625-var o: ^Obj;
626-begin
627- o := newObj(cls, Scan.intern(ADR(name[0]), LEN(name)), t);
628- o^.val := v;
629- o^.exported := true;
630- _ := insert(o, 0);
631-end;
632-
633-begin
634- hashMask := (1 shl 14) - 1;
635- hashTab := emptyTable(hashMask + 1);
636- depth := 1;
637- scopes[0] := 0;
638- nextScope := 0;
639- curModule := nil;
640- tI8 := basic("I8", fInt, 1, true);
641- tI16 := basic("I16", fInt, 2, true);
642- tI32 := basic("I32", fInt, 4, true);
643- tI64 := basic("I64", fInt, 8, true);
644- tU8 := basic("U8", fInt, 1, false);
645- tU16 := basic("U16", fInt, 2, false);
646- tU32 := basic("U32", fInt, 4, false);
647- tU64 := basic("U64", fInt, 8, false);
648- tInt := basic("INT", fInt, 8, true);
649- tUInt := basic("UINT", fInt, 8, false);
650- tBool := basic("BOOL", fBool, 1, false);
651- tF32 := basic("F32", fReal, 4, false);
652- tReal := basic("F64", fReal, 8, false);
653- tRConst := newType(fReal, 8, 8);
654- tError := basic("ERROR", fError, 8, false);
655- tConst := newType(fConst, 8, 8);
656- tConst^.signed := true;
657- tNil := newType(fNil, 8, 8);
658- tStr := newType(fStr, 0, 1);
659- tNone := newType(fNone, 0, 1);
660- tPtrU8 := newType(fPtr, 8, 8);
661- tPtrU8^.base := tU8;
662- tBytes := newType(fSlice, 16, 8);
663- tBytes^.base := tU8;
664- tPoison := newType(fInt, 8, 8);
665- tPoison^.signed := true;
666- enter("true", oConst, tBool, 1);
667- enter("false", oConst, tBool, 0);
668- enter("nil", oConst, tNil, 0);
669- enter("SIZE", oBuiltin, nil, bSize);
670- enter("ADR", oBuiltin, nil, bAdr);
671- enter("LEN", oBuiltin, nil, bLen);
672- enter("NEW", oBuiltin, nil, bNew);
673- enter("MSG", oBuiltin, nil, bMsg);
674- enter("SYSCALL", oBuiltin, nil, bSyscall);
675- enter("FENCE", oBuiltin, nil, bFence);
676- enter("CAS", oBuiltin, nil, bCas);
677- enter("XCHG", oBuiltin, nil, bXchg);
678- enter("XADD", oBuiltin, nil, bXadd);
679- enter("ARGC", oBuiltin, nil, bArgc);
680- enter("ARGV", oBuiltin, nil, bArgv);
681- enter("INC", oBuiltin, nil, bInc);
682- enter("DEC", oBuiltin, nil, bDec);
683- enter("COPY", oBuiltin, nil, bCopy);
684-end Sym.

self/X64.raz deleted +0 -1472

@@ -1,1472 +0,0 @@
1-(* X64: machine code for x86-64.
2-
3- The encoder writes the instructions the code generator needs, and
4- no others, into the text of Chunk. Registers are numbered as the
5- hardware numbers them. Jumps within a procedure are patched here, as
6- soon as their target is known.
7-
8- Depends on: Scan, for errors and the assembler's symbols; Diag, for
9- positions; Chunk for the code buffer and fixups.
10- Leaves out: choosing instructions; that is Gen.
11-
12- The seed's `Mem` that is too large an offset is marked and the code
13- goes on, since a function that makes an operand has no place to give
14- an error back from; the compile ends with the error shown. *)
15-module X64;
16-import Out, Fmt, Heap, Buf, Str, Diag, Scan, Chunk;
17-
18-const
19- RAX* = 0; RCX* = 1; RDX* = 2; RBX* = 3; RSP* = 4; RBP* = 5; RSI* = 6; RDI* = 7;
20- R8* = 8; R9* = 9; R10* = 10; R11* = 11; R12* = 12; R13* = 13; R14* = 14; R15* = 15;
21- RIP* = -1; (* a base meaning rip-relative, to a chunk *)
22- NoIndex* = -1;
23-
24- (* condition codes *)
25- ccB* = 2; ccAE* = 3; ccE* = 4; ccNE* = 5; ccBE* = 6; ccA* = 7; ccS* = 8;
26- ccP* = 10; ccNP* = 11; ccL* = 12; ccGE* = 13; ccLE* = 14; ccG* = 15;
27-
28- (* group 1 operations, the /digit of 81 and 83 *)
29- aluAdd* = 0; aluOr* = 1; aluAnd* = 4; aluSub* = 5; aluXor* = 6; aluCmp* = 7;
30-
31- (* the /digit of D3 and C1 *)
32- shShl* = 4; shShr* = 5; shSar* = 7;
33-
34- NoLabel* = -1;
35-
36-type
37- Mem* = record
38- base*: INT; (* a register, or RIP *)
39- index*: INT; (* a register, or NoIndex *)
40- scale*: INT; (* 1, 2, 4 or 8 *)
41- disp*: INT;
42- chunk*: INT; (* with RIP: the chunk addressed *)
43- end;
44-
45- (* The parser's reader of an integer constant in a code procedure: a
46- whole expression, or, when whole is false, a single factor *)
47- ConstFn* = proc(whole: BOOL): (I64, ERROR);
48-
49- (* The text of the instruction that starts at at, for the listing *)
50- Said = record
51- at: INT;
52- text: []U8;
53- end;
54-
55-var
56- listing*: BOOL; (* -S: each instruction's text is kept, for list *)
57- said: ^Said;
58- numSaid, saidCap: INT;
59-
60-proc setListing*(yes: BOOL);
61-begin
62- listing := yes;
63-end;
64-
65-(* Operands *)
66-
67-proc mem*(base: INT; disp: I64): Mem;
68-var m: Mem;
69-begin
70- if (disp < -2147483648) or (disp > 2147483647) then
71- _ := Scan.mark("an offset beyond 32 bits");
72- end;
73- m.base := base; m.index := NoIndex; m.scale := 1;
74- m.disp := INT(disp); m.chunk := -1;
75- return m;
76-end;
77-
78-proc memRip*(chunk: INT; disp: INT): Mem;
79-var m: Mem;
80-begin
81- m.base := RIP; m.index := NoIndex; m.scale := 1;
82- m.disp := disp; m.chunk := chunk;
83- return m;
84-end;
85-
86-proc memIdx*(base, index, scale: INT; disp: I64): Mem;
87-var m: Mem;
88-begin
89- m := mem(base, disp);
90- m.index := index;
91- m.scale := scale;
92- return m;
93-end;
94-
95-(* The address of the code about to be written, as an operand *)
96-proc here*: Mem;
97-begin
98- return memRip(Chunk.curChunk, Chunk.pc - Chunk.chunks[Chunk.curChunk].start);
99-end;
100-
101-(* Encoding. An instruction is: a legacy prefix, REX, the opcode, ModRM,
102- SIB and displacement. Opcodes of more than one byte are given with
103- their first byte in the low eight bits. *)
104-
105-proc opcode(op: INT);
106-begin
107- repeat
108- Chunk.put1(op & 0FFH);
109- op := op shr 8;
110- until op = 0;
111-end;
112-
113-(* The legacy prefix pfx, if any, and REX: wide is REX.W; byte4 says
114- a byte register of 4 to 7 is used, spl to dil, which exist only with
115- a REX prefix. *)
116-proc prefix(pfx: INT; w: BOOL; reg, index, base: INT; byte4: BOOL);
117-var rex: INT;
118-begin
119- if pfx # 0 then Chunk.put1(pfx); end;
120- rex := 0;
121- if w then rex := rex | 8; end;
122- if reg >= 8 then rex := rex | 4; end;
123- if index >= 8 then rex := rex | 2; end;
124- if base >= 8 then rex := rex | 1; end;
125- if (rex # 0) or byte4 then Chunk.put1(40H | rex); end;
126-end;
127-
128-(* op reg, [mem] *)
129-proc opM(pfx: INT; w: BOOL; op, reg: INT; m: Mem; byteReg: BOOL);
130-var md, b, sc: INT;
131-begin
132- byteReg := byteReg and (reg >= 4) and (reg <= 7);
133- if m.base = RIP then
134- prefix(pfx, w, reg, NoIndex, 0, byteReg);
135- else
136- prefix(pfx, w, reg, m.index, m.base, byteReg);
137- end;
138- opcode(op);
139- reg := reg & 7;
140- if m.base = RIP then
141- Chunk.put1((reg shl 3) | 5);
142- (* mod 00 with r/m 101 is rip + disp32. The displacement counts
143- from the end of the instruction, and the fixup takes it to end
144- with these four bytes: an instruction with an immediate after
145- them, aluMI's or storeI's, takes the immediate's size off disp
146- first (the assembler can't name a chunk). *)
147- Chunk.addFixup(Chunk.pc, m.chunk, m.disp);
148- Chunk.put4(0);
149- return;
150- end;
151- b := m.base & 7;
152- (* mod 00 takes no displacement, but with r/m 101 (RBP or R13) it means
153- rip-relative, or disp32 under a SIB byte, so those bases take a
154- zero disp8 *)
155- if (m.disp = 0) and (b # RBP) then
156- md := 0;
157- elsif (m.disp >= -128) and (m.disp <= 127) then
158- md := 1;
159- else
160- md := 2;
161- end;
162- (* r/m 100 (RSP or R12) means a SIB byte follows, so those bases need
163- one, with index 100 meaning none *)
164- if (m.index # NoIndex) or (b = RSP) then
165- Chunk.put1((md shl 6) | (reg shl 3) | 4);
166- if m.scale = 1 then sc := 0; elsif m.scale = 2 then sc := 1; elsif m.scale = 4 then sc := 2; else sc := 3; end;
167- if m.index = NoIndex then
168- Chunk.put1((sc shl 6) | (4 shl 3) | b);
169- else
170- Chunk.put1((sc shl 6) | ((m.index & 7) shl 3) | b);
171- end;
172- else
173- Chunk.put1((md shl 6) | (reg shl 3) | b);
174- end;
175- if md = 1 then
176- Chunk.put1(m.disp);
177- elsif md = 2 then
178- Chunk.put4(m.disp);
179- end;
180-end;
181-
182-(* op reg, rm (both registers) *)
183-proc opR(pfx: INT; w: BOOL; op, reg, rm: INT; byteReg: BOOL);
184-begin
185- prefix(pfx, w, reg, NoIndex, rm, byteReg and (((reg >= 4) and (reg <= 7)) or ((rm >= 4) and (rm <= 7))));
186- opcode(op);
187- Chunk.put1(0C0H | ((reg & 7) shl 3) | (rm & 7));
188-end;
189-
190-(* The listing: the text of each instruction, as it is made *)
191-
192-(* How many instructions the listing has, and back to n of them, for
193- code made again *)
194-proc saidCount*: INT;
195-begin
196- return numSaid;
197-end;
198-
199-proc unsay*(n: INT);
200-begin
201- numSaid := n;
202-end;
203-
204-proc sayAt*(at: INT; s: []U8);
205-begin
206- if not listing then return; end;
207- if numSaid = saidCap then
208- said := ^Said(Scan.regrab(^U8(said), numSaid * SIZE(Said), (saidCap * 2 + 1024) * SIZE(Said)));
209- saidCap := saidCap * 2 + 1024;
210- end;
211- said[numSaid].at := at;
212- said[numSaid].text := s;
213- INC(numSaid);
214-end;
215-
216-(* The text of the instruction about to be written *)
217-proc say*(s: []U8);
218-begin
219- sayAt(Chunk.pc, s);
220-end;
221-
222-(* The text of the instruction at at, said again, as when its operand is
223- patched *)
224-proc restate*(at: INT; s: []U8);
225-var i: INT;
226-begin
227- i := numSaid - 1;
228- while (i >= 0) and (said[i].at # at) do DEC(i); end;
229- if i >= 0 then said[i].text := s; end;
230-end;
231-
232-const
233- RegNames: [4][16][]U8 = [
234- ["rax", "rcx", "rdx", "rbx", "rsp", "rbp", "rsi", "rdi",
235- "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15"],
236- ["eax", "ecx", "edx", "ebx", "esp", "ebp", "esi", "edi",
237- "r8d", "r9d", "r10d", "r11d", "r12d", "r13d", "r14d", "r15d"],
238- ["ax", "cx", "dx", "bx", "sp", "bp", "si", "di",
239- "r8w", "r9w", "r10w", "r11w", "r12w", "r13w", "r14w", "r15w"],
240- ["al", "cl", "dl", "bl", "spl", "bpl", "sil", "dil",
241- "r8b", "r9b", "r10b", "r11b", "r12b", "r13b", "r14b", "r15b"]];
242- CondNames*: [16][]U8 = ["o", "no", "b", "ae", "e", "ne", "be", "a", "s", "ns", "p", "np", "l", "ge", "le", "g"];
243- AluNames: [8][]U8 = ["add", "or", "adc", "sbb", "and", "sub", "xor", "cmp"];
244- ShiftNames: [8][]U8 = ["rol", "ror", "rcl", "rcr", "shl", "shr", "sal", "sar"];
245- UnaryNames: [8][]U8 = ["", "", "not", "neg", "mul", "imul", "div", "idiv"]; (* from 2 *)
246-
247-(* The name of register r, of size bytes *)
248-proc rnSized(r, size: INT): []U8;
249-begin
250- if size = 1 then return RegNames[3][r]; end;
251- if size = 2 then return RegNames[2][r]; end;
252- if size = 4 then return RegNames[1][r]; end;
253- return RegNames[0][r];
254-end;
255-
256-proc rn(r: INT): []U8;
257-begin
258- return RegNames[0][r];
259-end;
260-
261-proc xn(x: INT): []U8;
262-begin
263- return Diag.say("xmm{}", [Fmt.int(x)]);
264-end;
265-
266-(* A memory operand, with the size of what it holds, as the assembler
267- reads it *)
268-proc mnSized(m: Mem; size: INT): []U8;
269-var b: ^Buf.Buf;
270-begin
271- b := ^Buf.Buf(Scan.grab(SIZE(Buf.Buf)));
272- Buf.init(b, Heap.heap);
273- if size = 1 then Buf.str(b, "byte ");
274- elsif size = 2 then Buf.str(b, "word ");
275- elsif size = 4 then Buf.str(b, "dword ");
276- elsif size = 8 then Buf.str(b, "qword ");
277- end;
278- Buf.str(b, "[");
279- if m.base = RIP then Buf.str(b, Chunk.chunkName(m.chunk)); else Buf.str(b, rn(m.base)); end;
280- if m.index # NoIndex then Fmt.write(b, " + {} * {}", [Fmt.str(rn(m.index)), Fmt.int(m.scale)]); end;
281- if m.disp > 0 then
282- Fmt.write(b, " + {}", [Fmt.int(m.disp)]);
283- elsif m.disp < 0 then
284- Fmt.write(b, " - {}", [Fmt.int(-m.disp)]);
285- end;
286- Buf.str(b, "]");
287- return Buf.bytes(b);
288-end;
289-
290-proc mn(m: Mem): []U8;
291-begin
292- return mnSized(m, 0);
293-end;
294-
295-(* "op a, b" and "op a" *)
296-proc text2(op, a, b: []U8): []U8;
297-begin
298- return Diag.say("{} {}, {}", [Fmt.str(op), Fmt.str(a), Fmt.str(b)]);
299-end;
300-
301-proc text1(op, a: []U8): []U8;
302-begin
303- return Diag.say("{} {}", [Fmt.str(op), Fmt.str(a)]);
304-end;
305-
306-(* v in decimal *)
307-proc num(v: INT): []U8;
308-begin
309- return Diag.say("{}", [Fmt.int(v)]);
310-end;
311-
312-proc movRR*(dst, src: INT);
313-begin
314- if listing then say(text2("mov", rn(dst), rn(src))); end;
315- opR(0, true, 89H, src, dst, false);
316-end;
317-
318-(* The operand-size prefix a size of 2 bytes takes *)
319-proc pfx16(size: INT): INT;
320-begin
321- if size = 2 then return 66H; end;
322- return 0;
323-end;
324-
325-(* The immediate of n bytes that ends an instruction *)
326-proc putImm(v, n: INT);
327-begin
328- if n = 4 then
329- Chunk.put4(v);
330- else
331- Chunk.put1(v & 0FFH);
332- if n = 2 then Chunk.put1((v shr 8) & 0FFH); end;
333- end;
334-end;
335-
336-(* op [m], v, on size bytes; v fits in them, or in 32 bits for 8 *)
337-proc aluMI*(op: INT; m: Mem; v, size: INT);
338-var n: INT;
339-begin
340- if listing then say(text2(AluNames[op], mnSized(m, size), num(v))); end;
341- if (size = 1) or ((v >= -128) and (v <= 127)) then
342- n := 1;
343- elsif size = 2 then
344- n := 2;
345- else
346- n := 4;
347- end;
348- if m.base = RIP then m.disp := m.disp - n; end;
349- if size = 1 then
350- opM(0, false, 80H, op, m, false);
351- elsif n = 1 then
352- opM(pfx16(size), size = 8, 83H, op, m, false);
353- else
354- opM(pfx16(size), size = 8, 81H, op, m, false);
355- end;
356- putImm(v, n);
357-end;
358-
359-(* mov [m], v, of size bytes; v fits in them, or in 32 bits for 8 *)
360-proc storeI*(m: Mem; v, size: INT);
361-var n: INT;
362-begin
363- if listing then say(text2("mov", mnSized(m, size), num(v))); end;
364- n := size;
365- if n > 4 then n := 4; end;
366- if m.base = RIP then m.disp := m.disp - n; end;
367- if size = 1 then
368- opM(0, false, 0C6H, 0, m, false);
369- else
370- opM(pfx16(size), size = 8, 0C7H, 0, m, false);
371- end;
372- putImm(v, n);
373-end;
374-
375-proc movRI*(r: INT; v: I64);
376-begin
377- if listing then
378- if v = 0 then
379- say(text2("xor", rnSized(r, 4), rnSized(r, 4)));
380- else
381- say(text2("mov", rn(r), Diag.say("{}", [Fmt.int(v)])));
382- end;
383- end;
384- if (v >= -2147483648) and (v <= 2147483647) then
385- if v = 0 then
386- opR(0, false, 31H, r, r, false); (* xor r32, r32 *)
387- elsif v > 0 then (* mov r32, imm32 *)
388- prefix(0, false, 0, NoIndex, r, false); Chunk.put1(0B8H + (r & 7)); Chunk.put4(INT(v));
389- else
390- opR(0, true, 0C7H, 0, r, false); Chunk.put4(INT(v)); (* sign-extended imm32 *)
391- end;
392- elsif (v > 0) and (v <= 0FFFFFFFFH) then
393- prefix(0, false, 0, NoIndex, r, false); Chunk.put1(0B8H + (r & 7)); Chunk.put4(INT(v));
394- else
395- prefix(0, true, 0, NoIndex, r, false); Chunk.put1(0B8H + (r & 7)); Chunk.put8(v);
396- end;
397-end;
398-
399-proc load*(r: INT; m: Mem; size: INT; signed: BOOL);
400-begin
401- if listing then
402- if size = 8 then
403- say(text2("mov", rn(r), mn(m)));
404- elsif (size = 4) and not signed then
405- say(text2("mov", rnSized(r, 4), mn(m)));
406- elsif size = 4 then
407- say(text2("movsxd", rn(r), mnSized(m, 4)));
408- elsif signed then
409- say(text2("movsx", rn(r), mnSized(m, size)));
410- else
411- say(text2("movzx", rnSized(r, 4), mnSized(m, size)));
412- end;
413- end;
414- if size = 1 then
415- if signed then opM(0, true, 0BE0FH, r, m, false); else opM(0, false, 0B60FH, r, m, false); end;
416- elsif size = 2 then
417- if signed then opM(0, true, 0BF0FH, r, m, false); else opM(0, false, 0B70FH, r, m, false); end;
418- elsif size = 4 then
419- if signed then opM(0, true, 63H, r, m, false); else opM(0, false, 8BH, r, m, false); end;
420- else
421- opM(0, true, 8BH, r, m, false);
422- end;
423-end;
424-
425-proc store*(m: Mem; r: INT; size: INT);
426-begin
427- if listing then say(text2("mov", mn(m), rnSized(r, size))); end;
428- if size = 1 then
429- opM(0, false, 88H, r, m, true);
430- elsif size = 2 then
431- opM(66H, false, 89H, r, m, false);
432- elsif size = 4 then
433- opM(0, false, 89H, r, m, false);
434- else
435- opM(0, true, 89H, r, m, false);
436- end;
437-end;
438-
439-proc lea*(r: INT; m: Mem);
440-begin
441- if listing then say(text2("lea", rn(r), mn(m))); end;
442- opM(0, true, 8DH, r, m, false);
443-end;
444-
445-proc alu*(op, dst, src: INT);
446-begin
447- if listing then say(text2(AluNames[op], rn(dst), rn(src))); end;
448- opR(0, true, (op shl 3) | 1, src, dst, false);
449-end;
450-
451-proc aluI*(op, r: INT; v: INT);
452-begin
453- if listing then say(text2(AluNames[op], rn(r), num(v))); end;
454- if (v >= -128) and (v <= 127) then
455- opR(0, true, 83H, op, r, false); Chunk.put1(v);
456- else
457- opR(0, true, 81H, op, r, false); Chunk.put4(v);
458- end;
459-end;
460-
461-(* op r, [m] *)
462-proc aluM*(op, r: INT; m: Mem);
463-begin
464- if listing then say(text2(AluNames[op], rn(r), mn(m))); end;
465- opM(0, true, (op shl 3) | 3, r, m, false);
466-end;
467-
468-proc imul*(dst, src: INT);
469-begin
470- if listing then say(text2("imul", rn(dst), rn(src))); end;
471- opR(0, true, 0AF0FH, dst, src, false);
472-end;
473-
474-proc imulI*(r: INT; v: INT);
475-begin
476- if listing then say(Diag.say("imul {}, {}, {}", [Fmt.str(rn(r)), Fmt.str(rn(r)), Fmt.int(v)])); end;
477- opR(0, true, 69H, r, r, false);
478- Chunk.put4(v);
479-end;
480-
481-proc shift*(op, r: INT);
482-begin
483- if listing then say(text2(ShiftNames[op], rn(r), "cl")); end;
484- opR(0, true, 0D3H, op, r, false);
485-end;
486-
487-proc shiftI*(op, r, n: INT);
488-begin
489- if listing then say(text2(ShiftNames[op], rn(r), num(n))); end;
490- opR(0, true, 0C1H, op, r, false);
491- Chunk.put1(n);
492-end;
493-
494-(* F7 /ext: 2 not, 3 neg, 6 div, 7 idiv *)
495-proc unary*(ext, r: INT);
496-begin
497- if listing then say(text1(UnaryNames[ext], rn(r))); end;
498- opR(0, true, 0F7H, ext, r, false);
499-end;
500-
501-proc cqo*;
502-begin
503- if listing then say("cqo"); end;
504- Chunk.put1(48H); Chunk.put1(99H);
505-end;
506-
507-(* Brings a value of size bytes in r to 64 bits, by its sign or zeros. *)
508-proc extend*(r, size: INT; signed: BOOL);
509-begin
510- if listing then
511- if size = 4 then
512- if signed then
513- say(text2("movsxd", rn(r), rnSized(r, 4)));
514- else
515- say(text2("mov", rnSized(r, 4), rnSized(r, 4)));
516- end;
517- elsif signed then
518- say(text2("movsx", rn(r), rnSized(r, size)));
519- else
520- say(text2("movzx", rnSized(r, 4), rnSized(r, size)));
521- end;
522- end;
523- if size = 1 then
524- if signed then opR(0, true, 0BE0FH, r, r, true); else opR(0, false, 0B60FH, r, r, true); end;
525- elsif size = 2 then
526- if signed then opR(0, true, 0BF0FH, r, r, false); else opR(0, false, 0B70FH, r, r, false); end;
527- elsif size = 4 then
528- if signed then opR(0, true, 63H, r, r, false); else opR(0, false, 89H, r, r, false); end;
529- end;
530-end;
531-
532-(* r := 1 if the condition holds, else 0 *)
533-proc setCC*(cc, r: INT);
534-begin
535- if listing then say(text1(Diag.say("set{}", [Fmt.str(CondNames[cc])]), rnSized(r, 1))); end;
536- opR(0, false, 900FH + (cc shl 8), 0, r, true);
537- if listing then say(text2("movzx", rnSized(r, 4), rnSized(r, 1))); end;
538- opR(0, false, 0B60FH, r, r, true);
539-end;
540-
541-proc testRR*(a, b: INT);
542-begin
543- if listing then say(text2("test", rn(a), rn(b))); end;
544- opR(0, true, 85H, b, a, false);
545-end;
546-
547-proc push*(r: INT);
548-begin
549- if listing then say(text1("push", rn(r))); end;
550- if r >= 8 then Chunk.put1(41H); end;
551- Chunk.put1(50H + (r & 7));
552-end;
553-
554-proc pop*(r: INT);
555-begin
556- if listing then say(text1("pop", rn(r))); end;
557- if r >= 8 then Chunk.put1(41H); end;
558- Chunk.put1(58H + (r & 7));
559-end;
560-
561-proc callChunk*(c: INT);
562-begin
563- if listing then say(text1("call", Chunk.chunkName(c))); end;
564- Chunk.put1(0E8H);
565- Chunk.addFixup(Chunk.pc, c, 0);
566- Chunk.put4(0);
567-end;
568-
569-proc callBack*(target: INT);
570-begin
571- if listing then say("call"); end;
572- Chunk.put1(0E8H);
573- Chunk.put4(target - (Chunk.pc + 4));
574-end;
575-
576-proc callR*(r: INT);
577-begin
578- if listing then say(text1("call", rn(r))); end;
579- opR(0, false, 0FFH, 2, r, false);
580-end;
581-
582-proc jmpR*(r: INT);
583-begin
584- if listing then say(text1("jmp", rn(r))); end;
585- opR(0, false, 0FFH, 4, r, false);
586-end;
587-
588-proc callM*(m: Mem);
589-begin
590- if listing then say(text1("call", mn(m))); end;
591- opM(0, false, 0FFH, 2, m, false);
592-end;
593-
594-proc ret*;
595-begin
596- if listing then say("ret"); end;
597- Chunk.put1(0C3H);
598-end;
599-
600-proc leave*;
601-begin
602- say("leave"); Chunk.put1(0C9H);
603-end;
604-
605-proc syscall*;
606-begin
607- say("syscall"); Chunk.put1(0FH); Chunk.put1(05H);
608-end;
609-
610-proc mfence*;
611-begin
612- say("mfence"); Chunk.put1(0FH); Chunk.put1(0AEH); Chunk.put1(0F0H);
613-end;
614-
615-proc ud2*;
616-begin
617- say("ud2"); Chunk.put1(0FH); Chunk.put1(0BH);
618-end;
619-
620-(* Code made up to a multiple of n bytes with no-ops, the fewest: the
621- long forms of nop, of up to 8 bytes, that x86 decodes as one *)
622-proc align*(n: INT);
623-const
624- Nops: [8][]U8 = ["\x90", "\x66\x90", "\x0F\x1F\x00", "\x0F\x1F\x40\x00",
625- "\x0F\x1F\x44\x00\x00", "\x66\x0F\x1F\x44\x00\x00", "\x0F\x1F\x80\x00\x00\x00\x00",
626- "\x0F\x1F\x84\x00\x00\x00\x00\x00"];
627-var k, i: INT;
628-begin
629- while Chunk.pc mod n # 0 do
630- k := n - Chunk.pc mod n;
631- if k > 8 then k := 8; end;
632- say("nop");
633- for i := 0 to k - 1 do Chunk.put1(INT(Nops[k - 1][i])); end;
634- end;
635-end;
636-
637-proc repMovsb*;
638-begin
639- say("rep movsb"); Chunk.put1(0F3H); Chunk.put1(0A4H);
640-end;
641-
642-(* the direction flag, which has rep movsb go down, and back up *)
643-proc std*;
644-begin
645- say("std"); Chunk.put1(0FDH);
646-end;
647-
648-proc cld*;
649-begin
650- say("cld"); Chunk.put1(0FCH);
651-end;
652-
653-proc repStosb*;
654-begin
655- say("rep stosb"); Chunk.put1(0F3H); Chunk.put1(0AAH);
656-end;
657-
658-proc repeCmpsb*;
659-begin
660- say("repe cmpsb"); Chunk.put1(0F3H); Chunk.put1(0A6H);
661-end;
662-
663-proc lockCmpxchg*(m: Mem; r: INT);
664-begin
665- if listing then say(text2("lock cmpxchg", mn(m), rn(r))); end;
666- Chunk.put1(0F0H);
667- opM(0, true, 0B10FH, r, m, false);
668-end;
669-
670-proc xchg*(m: Mem; r: INT);
671-begin
672- if listing then say(text2("xchg", mn(m), rn(r))); end;
673- opM(0, true, 87H, r, m, false);
674-end;
675-
676-proc lockXadd*(m: Mem; r: INT);
677-begin
678- if listing then say(text2("lock xadd", mn(m), rn(r))); end;
679- Chunk.put1(0F0H);
680- opM(0, true, 0C10FH, r, m, false);
681-end;
682-
683-proc movqXR*(x, r: INT);
684-begin
685- if listing then say(text2("movq", xn(x), rn(r))); end;
686- opR(66H, true, 6E0FH, x, r, false);
687-end;
688-
689-proc movqRX*(r, x: INT);
690-begin
691- if listing then say(text2("movq", rn(r), xn(x))); end;
692- opR(66H, true, 7E0FH, x, r, false);
693-end;
694-
695-(* movaps: all of xmm y to xmm x, the shortest move between two *)
696-proc movX*(x, y: INT);
697-begin
698- if listing then say(text2("movaps", xn(x), xn(y))); end;
699- opR(0, false, 280FH, x, y, false);
700-end;
701-
702-(* The prefix of a real instruction, and the end of its name: sd, or ss for single *)
703-proc realPfx(single: BOOL): INT;
704-begin
705- if single then return 0F3H; end;
706- return 0F2H;
707-end;
708-
709-proc realEnd(single: BOOL): []U8;
710-begin
711- if single then return "ss"; end;
712- return "sd";
713-end;
714-
715-(* The real instructions take single: F32 (ss) rather than F64 (sd) *)
716-proc movsXM*(x: INT; m: Mem; single: BOOL);
717-begin
718- if listing then say(text2(Diag.say("movs{}", [Fmt.str(realEnd(single)[1..2])]), xn(x), mn(m))); end;
719- opM(realPfx(single), false, 100FH, x, m, false);
720-end;
721-
722-proc movsMX*(m: Mem; x: INT; single: BOOL);
723-begin
724- if listing then say(text2(Diag.say("movs{}", [Fmt.str(realEnd(single)[1..2])]), mn(m), xn(x))); end;
725- opM(realPfx(single), false, 110FH, x, m, false);
726-end;
727-
728-proc sseName(op: INT; single: BOOL): []U8;
729-begin
730- if op = 58H then return Diag.say("add{}", [Fmt.str(realEnd(single))]); end;
731- if op = 59H then return Diag.say("mul{}", [Fmt.str(realEnd(single))]); end;
732- if op = 5CH then return Diag.say("sub{}", [Fmt.str(realEnd(single))]); end;
733- if op = 5EH then return Diag.say("div{}", [Fmt.str(realEnd(single))]); end;
734- return Diag.say("cvt{}2{}", [Fmt.str(realEnd(single)), Fmt.str(realEnd(not single))]);
735-end;
736-
737-(* 58 add, 59 mul, 5C sub, 5E div, 5A convert *)
738-proc sse*(op, x, y: INT; single: BOOL);
739-begin
740- if listing then say(text2(sseName(op, single), xn(x), xn(y))); end;
741- opR(realPfx(single), false, 0FH | (op shl 8), x, y, false);
742-end;
743-
744-(* The same, its right operand in memory: addsd x, [m] *)
745-proc sseM*(op, x: INT; m: Mem; single: BOOL);
746-begin
747- if listing then say(text2(sseName(op, single), xn(x), mn(m))); end;
748- opM(realPfx(single), false, 0FH | (op shl 8), x, m, false);
749-end;
750-
751-proc ucomis*(x, y: INT; single: BOOL);
752-begin
753- if listing then say(text2(Diag.say("ucomi{}", [Fmt.str(realEnd(single))]), xn(x), xn(y))); end;
754- if single then opR(0, false, 2E0FH, x, y, false); else opR(66H, false, 2E0FH, x, y, false); end;
755-end;
756-
757-proc cvtsi2s*(x, r: INT; single: BOOL);
758-begin
759- if listing then say(text2(Diag.say("cvtsi2{}", [Fmt.str(realEnd(single))]), xn(x), rn(r))); end;
760- opR(realPfx(single), true, 2A0FH, x, r, false);
761-end;
762-
763-proc cvtts2si*(r, x: INT; single: BOOL);
764-begin
765- if listing then say(text2(Diag.say("cvtt{}2si", [Fmt.str(realEnd(single))]), rn(r), xn(x))); end;
766- opR(realPfx(single), true, 2C0FH, r, x, false);
767-end;
768-
769-proc btc*(r, bit: INT);
770-begin
771- if listing then say(text2("btc", rn(r), num(bit))); end;
772- opR(0, true, 0BA0FH, 7, r, false);
773- Chunk.put1(bit);
774-end;
775-
776-(* Jumps. A label not yet placed is the chain of the jumps to it, each
777- rel32 field holding the position of the one before, NoLabel ending
778- it. Placing the label walks the chain and patches each. *)
779-
780-proc jmp*(var L: INT);
781-begin
782- if listing then say("jmp"); end;
783- Chunk.put1(0E9H);
784- Chunk.put4(L);
785- L := Chunk.pc - 4;
786-end;
787-
788-proc jcc*(cc: INT; var L: INT);
789-begin
790- if listing then say(Diag.say("j{}", [Fmt.str(CondNames[cc])])); end;
791- Chunk.put1(0FH); Chunk.put1(80H + cc);
792- Chunk.put4(L);
793- L := Chunk.pc - 4;
794-end;
795-
796-proc jmpBack*(target: INT);
797-begin
798- if listing then say("jmp"); end;
799- Chunk.put1(0E9H);
800- Chunk.put4(target - (Chunk.pc + 4));
801-end;
802-
803-proc jccBack*(cc, target: INT);
804-begin
805- if listing then say(Diag.say("j{}", [Fmt.str(CondNames[cc])])); end;
806- Chunk.put1(0FH); Chunk.put1(80H + cc);
807- Chunk.put4(target - (Chunk.pc + 4));
808-end;
809-
810-proc fixLinkTo*(L, target: INT);
811-var next: INT;
812-begin
813- while L # NoLabel do
814- next := Chunk.get4At(L);
815- Chunk.put4At(L, target - (L + 4));
816- L := next;
817- end;
818-end;
819-
820-proc fixLink*(L: INT);
821-begin
822- fixLinkTo(L, Chunk.pc);
823-end;
824-
825-(* If the last instruction made is a jmp to L, it is taken back, since L
826- is to be placed just after it: a return at the end of a procedure
827- needn't jump to the code that returns. L is the place of the latest
828- jump's 4-byte field, so the last instruction is that jump when L is
829- 4 bytes back and an E9 byte (jmp) is before it; a jcc's field follows
830- the bytes 0F 8x, never E9. L then becomes the next jump on the chain,
831- which the field held. The caller must place L next, before anything
832- can have noted where the jmp ended. *)
833-proc dropJumpTo*(var L: INT);
834-begin
835- if (L = NoLabel) or (L # Chunk.pc - 4) or (Chunk.text[L - 1] # 0E9H) then return; end;
836- L := Chunk.get4At(L);
837- Chunk.takeBack(5);
838- if listing and (numSaid > 0) and (said[numSaid - 1].at = Chunk.pc) then DEC(numSaid); end;
839-end;
840-
841-(* The jumps of chains L1 and L2, as one chain: each jump's field holds
842- the next one's place until it is fixed, the last NoLabel *)
843-proc joinLinks*(L1, L2: INT): INT;
844-var L: INT;
845-begin
846- if L2 = NoLabel then return L1; end;
847- if L1 # NoLabel then
848- L := L2;
849- while Chunk.get4At(L) # NoLabel do L := Chunk.get4At(L); end;
850- Chunk.put4At(L, L1);
851- end;
852- return L2;
853-end;
854-
855-(* The assembler, for code procedures: x86-64 in Intel's syntax as NASM
856- writes it (report, appendix A). It reads instructions with the
857- scanner up to end, and encodes them with opM and opR; constants are
858- read by the parser's constExpr. *)
859-
860-const
861- NoBase = -3; (* a memory operand's base, not yet read *)
862-
863-type
864- OpKind = (oReg, oXmm, oMem, oImm);
865- Operand = record
866- kind: OpKind;
867- r, size: INT; (* oReg, oXmm: the register and its size; oMem: its size, or 0 *)
868- m: Mem;
869- v: I64; (* oImm *)
870- end;
871-
872-(* The current symbol as a word: an identifier, or a reserved word that
873- is also an instruction *)
874-proc asmWord: []U8;
875-begin
876- match Scan.tok of
877- | sIdent: return Scan.nameOf(Scan.id);
878- | sAnd: return "and";
879- | sOr: return "or";
880- | sXor: return "xor";
881- | sNot: return "not";
882- | sDiv: return "div";
883- | sShl: return "shl";
884- | sShr: return "shr";
885- | else: return "";
886- end;
887-end;
888-
889-(* Whether w names a register: rax, eax, ax, al and so on, or xmm0 to
890- xmm15 (size 16); r and size are set if so *)
891-proc isReg(w: []U8; r, size: ^INT): BOOL;
892-const Sizes: [4]INT = [8, 4, 2, 1];
893-var i, j, n, d: INT;
894-begin
895- for i := 0 to 3 do
896- for j := 0 to 15 do
897- if RegNames[i][j] = w then r^ := j; size^ := Sizes[i]; return true; end;
898- end;
899- end;
900- size^ := 16;
901- if not Str.hasPrefix(w, "xmm") or (LEN(w) <= 3) then return false; end;
902- (* the seed read the two bytes after xmm as a number, whatever follows *)
903- n := LEN(w) - 3;
904- if n > 2 then n := 2; end;
905- r^ := 0;
906- for i := 0 to n - 1 do
907- d := INT(w[3 + i]) - 48;
908- if (d < 0) or (d > 9) then return false; end;
909- r^ := r^ * 10 + d;
910- end;
911- return r^ <= 15;
912-end;
913-
914-(* Which word of list, a list of words each with a space either side,
915- w is, from 0; -1 if none *)
916-proc wordIndex(w: []U8; list: []U8): INT;
917-var i, n, start: INT;
918-begin
919- n := 0;
920- start := 1;
921- for i := 1 to LEN(list) - 1 do
922- if list[i] = ' ' then
923- if (i - start = LEN(w)) and (list[start..i] = w) then return n; end;
924- INC(n);
925- start := i + 1;
926- end;
927- end;
928- return -1;
929-end;
930-
931-(* w from byte from on, at most n bytes of it, as copy does *)
932-proc part(w: []U8; from, n: INT): []U8;
933-var e: INT;
934-begin
935- e := from + n;
936- if e > LEN(w) then e := LEN(w); end;
937- if from >= e then return ""; end;
938- return w[from..e];
939-end;
940-
941-(* The condition a name ends in: e of je, nz of jnz *)
942-proc cond(w: []U8): INT;
943-const
944- Alias: [12][]U8 = ["c", "nae", "nc", "nb", "z", "nz", "na", "nbe", "nge", "nl", "ng", "nle"];
945- AliasCc: [12]INT = [2, 2, 3, 3, 4, 5, 6, 7, 12, 13, 14, 15];
946-var i: INT;
947-begin
948- for i := 0 to 15 do
949- if CondNames[i] = w then return i; end;
950- end;
951- for i := 0 to 11 do
952- if Alias[i] = w then return AliasCc[i]; end;
953- end;
954- return -1;
955-end;
956-
957-proc operand(o: ^Operand; constExpr: ConstFn): ERROR;
958-var w: []U8; r, size, sz: INT; st: Scan.State; v: I64; isR, wasMinus: BOOL;
959-begin
960- o^ := {};
961- w := asmWord();
962- sz := 0;
963- if w = "byte" then sz := 1;
964- elsif w = "word" then sz := 2;
965- elsif w = "dword" then sz := 4;
966- elsif w = "qword" then sz := 8;
967- end;
968- if sz # 0 then Scan.next; w := asmWord(); end;
969- if Scan.tok = Scan.sLbrak then
970- (* [base + index * scale + disp], the displacement last *)
971- Scan.next;
972- o^.kind := oMem; o^.size := sz;
973- o^.m := mem(NoBase, 0);
974- repeat
975- if isReg(asmWord(), ADR(r), ADR(size)) and (size = 8) then
976- Scan.next;
977- (* the scale is a single number or constant: a whole expression
978- would take in the displacement after it, as 4 + 16 in
979- [rdi + rsi * 4 + 16] *)
980- if Scan.tok = Scan.sTimes then
981- Scan.next;
982- o^.m.index := r;
983- v := try constExpr(false);
984- o^.m.scale := INT(v);
985- elsif o^.m.base = NoBase then
986- o^.m.base := r;
987- else
988- o^.m.index := r; o^.m.scale := 1;
989- end;
990- else
991- v := try constExpr(true);
992- o^.m.disp := o^.m.disp + INT(v);
993- end;
994- if (Scan.tok # Scan.sPlus) and (Scan.tok # Scan.sMinus) then break; end;
995- wasMinus := Scan.tok = Scan.sMinus;
996- Scan.saveScan(st);
997- Scan.next;
998- isR := isReg(asmWord(), ADR(r), ADR(size));
999- if not isR and wasMinus then Scan.restoreScan(st); end;
1000- until false;
1001- if (Scan.tok # Scan.sRbrak) or (o^.m.base = NoBase)
1002- or not ((o^.m.scale = 1) or (o^.m.scale = 2) or (o^.m.scale = 4) or (o^.m.scale = 8)) then
1003- return Scan.mark("expected a memory operand, [base + index * scale + disp]");
1004- end;
1005- Scan.next;
1006- elsif isReg(w, ADR(o^.r), ADR(o^.size)) then
1007- if o^.size = 16 then o^.kind := oXmm; else o^.kind := oReg; end;
1008- Scan.next;
1009- else
1010- o^.kind := oImm;
1011- o^.v := try constExpr(true);
1012- end;
1013- return nil;
1014-end;
1015-
1016-(* op with register reg and the register or memory operand o *)
1017-proc rm(pfx: INT; w: BOOL; op, reg: INT; o: Operand; byteReg: BOOL);
1018-begin
1019- if o.kind = oMem then opM(pfx, w, op, reg, o.m, byteReg); else opR(pfx, w, op, reg, o.r, byteReg); end;
1020-end;
1021-
1022-proc putImmV(v: I64; size: INT);
1023-begin
1024- if size = 1 then
1025- Chunk.put1(INT(v & 0FFH));
1026- elsif size = 2 then
1027- Chunk.put1(INT(v & 0FFH)); Chunk.put1(INT((v shr 8) & 0FFH));
1028- else
1029- Chunk.put4(INT(v & 0FFFFFFFFH));
1030- end;
1031-end;
1032-
1033-const
1034- Alus = " add or adc sbb and sub xor cmp ";
1035- Unaries = " not neg mul imul div idiv ";
1036- Shifts = " rol ror rcl rcr shl shr sal sar ";
1037- SseOps = " sqrt add mul sub min div max ";
1038- SseCodes: [7]INT = [51H, 58H, 59H, 5CH, 5DH, 5EH, 5FH];
1039- (* SSE2 integer instructions that work on 16 bytes at a time: 66 0F code,
1040- xmm and xmm or memory (pshufd also takes a byte) *)
1041- PackedOps = " punpcklbw punpcklwd pcmpeqb pshufd pand pandn por pxor paddb psubb ";
1042- PackedCodes: [10]INT = [60H, 61H, 74H, 70H, 0DBH, 0DFH, 0EBH, 0EFH, 0FCH, 0F8H];
1043- (* bit scans and counts: reg, reg or memory, with the prefix and code that tell them *)
1044- BitOps = " bsf bsr tzcnt lzcnt popcnt ";
1045- BitPfx: [5]INT = [0, 0, 0F3H, 0F3H, 0F3H];
1046- BitCodes: [5]INT = [0BC0FH, 0BD0FH, 0BC0FH, 0BD0FH, 0B80FH];
1047- Plain: [15][]U8 = ["ret", "leave", "syscall", "cpuid", "rdtsc",
1048- "pause", "nop", "ud2", "int3", "hlt", "cqo", "cdq", "mfence", "lfence", "sfence"];
1049- PlainOp: [15]INT = [0C3H, 0C9H, 050FH, 0A20FH, 310FH,
1050- 90F3H, 90H, 0B0FH, 0CCH, 0F4H, 9948H, 99H, 0F0AE0FH, 0E8AE0FH, 0F8AE0FH];
1051-
1052-var
1053- (* the instruction being assembled *)
1054- aw: []U8; (* its word *)
1055- ao: [3]Operand; (* its operands *)
1056- an: INT; (* how many *)
1057- asize, apfx: INT;
1058- awide, abyte: BOOL;
1059- aat: Diag.Pos; (* where it starts *)
1060- (* the labels of the procedure *)
1061- lnames, lplaces, lchains: [64]INT;
1062- lusedAt: [64]Diag.Pos;
1063- numLabels: INT;
1064-
1065-(* The label called n, entered if new *)
1066-proc lab(n: INT): (INT, ERROR);
1067-var i: INT;
1068-begin
1069- for i := 0 to numLabels - 1 do
1070- if lnames[i] = n then return i, nil; end;
1071- end;
1072- if numLabels > 63 then return 0, Scan.mark("more than 64 labels"); end;
1073- lnames[numLabels] := n; lplaces[numLabels] := -1; lchains[numLabels] := NoLabel;
1074- lusedAt[numLabels] := Scan.tokPos();
1075- numLabels := numLabels + 1;
1076- return numLabels - 1, nil;
1077-end;
1078-
1079-proc bad: ERROR;
1080-begin
1081- return Scan.markAt(aat, Diag.say("can't assemble {} with these operands", [Fmt.str(aw)]));
1082-end;
1083-
1084-(* an instruction of two operands: a register or memory, and a
1085- register (opcode toRM), the other way (fromRM), or an immediate
1086- (opImm /digit, or none if opImm < 0) *)
1087-proc two(toRM, fromRM, opImm, digit: INT): ERROR;
1088-var b: INT;
1089-begin
1090- b := 0;
1091- if abyte then b := 1; end;
1092- if an # 2 then return bad(); end;
1093- if ao[1].kind = oImm then
1094- if (ao[0].kind = oImm) or (opImm < 0) then return bad(); end;
1095- if (opImm = 81H) and not abyte and (ao[1].v >= -128) and (ao[1].v <= 127) then
1096- rm(apfx, awide, 83H, digit, ao[0], false); (* a byte, sign-extended *)
1097- Chunk.put1(INT(ao[1].v & 0FFH));
1098- else
1099- rm(apfx, awide, opImm - b, digit, ao[0], false);
1100- putImmV(ao[1].v, asize);
1101- end;
1102- elsif (ao[1].kind = oReg) and ((ao[0].kind = oReg) or (ao[0].kind = oMem)) then
1103- rm(apfx, awide, toRM - b, ao[1].r, ao[0], abyte);
1104- elsif (ao[0].kind = oReg) and (ao[1].kind = oMem) then
1105- rm(apfx, awide, fromRM - b, ao[0].r, ao[1], abyte);
1106- else
1107- return bad();
1108- end;
1109- return nil;
1110-end;
1111-
1112-(* whether operand i is an xmm register or a memory operand *)
1113-proc isXM(i: INT): BOOL;
1114-begin
1115- return (ao[i].kind = oXmm) or (ao[i].kind = oMem);
1116-end;
1117-
1118-(* whether operand i is a general register or a memory operand, for an
1119- xmm register's partner *)
1120-proc isRMem(i: INT): BOOL;
1121-begin
1122- return (ao[i].kind = oReg) or (ao[i].kind = oMem);
1123-end;
1124-
1125-(* b as 1 for true *)
1126-proc bit(f: BOOL): INT;
1127-begin
1128- if f then return 1; end;
1129- return 0;
1130-end;
1131-
1132-(* The instruction w with its operands, in ao and an, apart from the
1133- jumps to labels and db, which assemble does *)
1134-proc instruction(): ERROR;
1135-var k: INT;
1136-begin
1137- if wordIndex(aw, Alus) >= 0 then
1138- k := wordIndex(aw, Alus);
1139- return two(k * 8 + 1, k * 8 + 3, 81H, k);
1140- elsif aw = "mov" then
1141- if (an = 2) and (ao[0].kind = oReg) and (ao[1].kind = oImm) and (asize >= 4) then
1142- if awide then
1143- movRI(ao[0].r, ao[1].v);
1144- else
1145- prefix(0, false, 0, NoIndex, ao[0].r, false); Chunk.put1(0B8H + (ao[0].r & 7)); Chunk.put4(INT(ao[1].v & 0FFFFFFFFH));
1146- end;
1147- return nil;
1148- end;
1149- return two(89H, 8BH, 0C7H, 0);
1150- elsif aw = "test" then
1151- return two(85H, 85H, 0F7H, 0);
1152- elsif aw = "xchg" then
1153- return two(87H, 87H, -1, 0);
1154- elsif (aw = "cmpxchg") or (aw = "xadd") then
1155- if (an # 2) or (ao[1].kind # oReg) then return bad(); end;
1156- if aw = "xadd" then k := 0C10FH; else k := 0B10FH; end;
1157- rm(apfx, awide, k - (bit(abyte) shl 8), ao[1].r, ao[0], abyte);
1158- elsif aw = "lea" then
1159- if (an # 2) or (ao[0].kind # oReg) or (ao[1].kind # oMem) then return bad(); end;
1160- rm(apfx, awide, 8DH, ao[0].r, ao[1], false);
1161- elsif (aw = "movzx") or (aw = "movsx") or (aw = "movsxd") then
1162- if (an # 2) or (ao[0].kind # oReg) or (ao[1].kind = oImm) then return bad(); end;
1163- if aw = "movsxd" then
1164- k := 63H;
1165- elsif ao[1].size = 1 then
1166- k := 0B60FH;
1167- elsif ao[1].size = 2 then
1168- k := 0B70FH;
1169- else
1170- return bad();
1171- end;
1172- if aw = "movsx" then k := k + 0800H; end;
1173- rm(apfx, awide, k, ao[0].r, ao[1], ao[1].size = 1);
1174- elsif ((wordIndex(aw, Unaries) >= 0) and (an = 1)) or (aw = "inc") or (aw = "dec") then
1175- if ao[0].kind = oImm then return bad(); end;
1176- if aw = "inc" then
1177- rm(apfx, awide, 0FFH - bit(abyte), 0, ao[0], abyte);
1178- elsif aw = "dec" then
1179- rm(apfx, awide, 0FFH - bit(abyte), 1, ao[0], abyte);
1180- else
1181- rm(apfx, awide, 0F7H - bit(abyte), wordIndex(aw, Unaries) + 2, ao[0], abyte);
1182- end;
1183- elsif aw = "imul" then
1184- if (an < 2) or (ao[0].kind # oReg) or (ao[1].kind = oImm) then return bad(); end;
1185- if an = 2 then
1186- rm(apfx, awide, 0AF0FH, ao[0].r, ao[1], false);
1187- else
1188- rm(apfx, awide, 69H, ao[0].r, ao[1], false);
1189- putImmV(ao[2].v, asize);
1190- end;
1191- elsif wordIndex(aw, Shifts) >= 0 then
1192- k := wordIndex(aw, Shifts);
1193- if k = 6 then k := 4; end; (* sal is shl *)
1194- if (an # 2) or (ao[0].kind = oImm) then return bad(); end;
1195- if ao[1].kind = oImm then
1196- rm(apfx, awide, 0C1H - bit(abyte), k, ao[0], abyte);
1197- Chunk.put1(INT(ao[1].v & 0FFH));
1198- elsif (ao[1].kind = oReg) and (ao[1].r = RCX) and (ao[1].size = 1) then
1199- rm(apfx, awide, 0D3H - bit(abyte), k, ao[0], abyte);
1200- else
1201- return bad();
1202- end;
1203- elsif (aw = "push") or (aw = "pop") then
1204- if (an # 1) or (ao[0].kind # oReg) or not awide then return bad(); end;
1205- if aw = "push" then push(ao[0].r); else pop(ao[0].r); end;
1206- elsif (aw = "call") or (aw = "jmp") then
1207- if (an # 1) or (ao[0].kind = oImm) then return bad(); end;
1208- if aw = "call" then rm(0, false, 0FFH, 2, ao[0], false); else rm(0, false, 0FFH, 4, ao[0], false); end;
1209- elsif Str.hasPrefix(aw, "set") and (cond(part(aw, 3, 3)) >= 0) then
1210- if (an # 1) or (ao[0].kind = oImm) or (asize # 1) then return bad(); end;
1211- rm(0, false, 900FH + (cond(part(aw, 3, 3)) shl 8), 0, ao[0], true);
1212- elsif Str.hasPrefix(aw, "cmov") and (cond(part(aw, 4, 3)) >= 0) then
1213- if (an # 2) or (ao[0].kind # oReg) or (ao[1].kind = oImm) then return bad(); end;
1214- rm(apfx, awide, 400FH + (cond(part(aw, 4, 3)) shl 8), ao[0].r, ao[1], false);
1215- elsif (LEN(aw) > 2) and (wordIndex(aw[0..LEN(aw) - 2], SseOps) >= 0)
1216- and ((aw[LEN(aw) - 2..LEN(aw)] = "sd") or (aw[LEN(aw) - 2..LEN(aw)] = "ss")) then
1217- (* sqrtsd, addss and the like: xmm, xmm or memory *)
1218- if (an # 2) or (ao[0].kind # oXmm) or not isXM(1) then return bad(); end;
1219- k := 0FH | (SseCodes[wordIndex(aw[0..LEN(aw) - 2], SseOps)] shl 8);
1220- rm(realPfx(aw[LEN(aw) - 1] = 's'), false, k, ao[0].r, ao[1], false);
1221- elsif wordIndex(aw, PackedOps) >= 0 then
1222- if (an < 2) or (ao[0].kind # oXmm) or not isXM(1) then return bad(); end;
1223- k := wordIndex(aw, PackedOps);
1224- rm(66H, false, 0FH | (PackedCodes[k] shl 8), ao[0].r, ao[1], false);
1225- if aw = "pshufd" then
1226- if (an # 3) or (ao[2].kind # oImm) then return bad(); end;
1227- Chunk.put1(INT(ao[2].v & 0FFH));
1228- elsif an # 2 then
1229- return bad();
1230- end;
1231- elsif (aw = "movdqu") or (aw = "movdqa") then
1232- (* the load is 6F and the store 7F; movdqu is F3, movdqa 66 *)
1233- if aw = "movdqu" then k := 0F3H; else k := 66H; end;
1234- if (an = 2) and (ao[0].kind = oXmm) and isXM(1) then
1235- rm(k, false, 6F0FH, ao[0].r, ao[1], false);
1236- elsif (an = 2) and (ao[0].kind = oMem) and (ao[1].kind = oXmm) then
1237- rm(k, false, 7F0FH, ao[1].r, ao[0], false);
1238- else
1239- return bad();
1240- end;
1241- elsif aw = "pmovmskb" then
1242- if (an # 2) or (ao[0].kind # oReg) or (ao[1].kind # oXmm) then return bad(); end;
1243- rm(66H, false, 0D70FH, ao[0].r, ao[1], false);
1244- elsif wordIndex(aw, BitOps) >= 0 then
1245- if (an # 2) or (ao[0].kind # oReg) or (ao[1].kind = oImm) or (asize < 4) then return bad(); end;
1246- k := wordIndex(aw, BitOps);
1247- rm(BitPfx[k], awide, BitCodes[k], ao[0].r, ao[1], false);
1248- elsif (aw = "movsd") or (aw = "movss") then
1249- if aw = "movsd" then k := 0F2H; else k := 0F3H; end;
1250- if (an = 2) and (ao[0].kind = oXmm) and isXM(1) then
1251- rm(k, false, 100FH, ao[0].r, ao[1], false);
1252- elsif (an = 2) and (ao[0].kind = oMem) and (ao[1].kind = oXmm) then
1253- rm(k, false, 110FH, ao[1].r, ao[0], false);
1254- else
1255- return bad();
1256- end;
1257- elsif (aw = "movq") or (aw = "movd") then
1258- if (an = 2) and (ao[0].kind = oXmm) and isRMem(1) then
1259- rm(66H, aw = "movq", 6E0FH, ao[0].r, ao[1], false);
1260- elsif (an = 2) and (ao[1].kind = oXmm) and isRMem(0) then
1261- rm(66H, aw = "movq", 7E0FH, ao[1].r, ao[0], false);
1262- else
1263- return bad();
1264- end;
1265- elsif (aw = "ucomisd") or (aw = "ucomiss") then
1266- if (an # 2) or (ao[0].kind # oXmm) or not isXM(1) then return bad(); end;
1267- if aw = "ucomisd" then
1268- rm(66H, false, 2E0FH, ao[0].r, ao[1], false);
1269- else
1270- rm(0, false, 2E0FH, ao[0].r, ao[1], false);
1271- end;
1272- elsif (aw = "cvtsi2sd") or (aw = "cvtsi2ss") then
1273- if (an # 2) or (ao[0].kind # oXmm) or not isRMem(1) then return bad(); end;
1274- rm(realPfx(aw = "cvtsi2ss"), ao[1].size # 4, 2A0FH, ao[0].r, ao[1], false);
1275- elsif (aw = "cvttsd2si") or (aw = "cvttss2si") then
1276- if (an # 2) or (ao[0].kind # oReg) or not isXM(1) then return bad(); end;
1277- rm(realPfx(aw = "cvttss2si"), awide, 2C0FH, ao[0].r, ao[1], false);
1278- elsif (aw = "cvtsd2ss") or (aw = "cvtss2sd") then
1279- if (an # 2) or (ao[0].kind # oXmm) or not isXM(1) then return bad(); end;
1280- rm(realPfx(aw = "cvtss2sd"), false, 5A0FH, ao[0].r, ao[1], false);
1281- else
1282- k := 0;
1283- while (k <= 14) and (Plain[k] # aw) do INC(k); end;
1284- if (k > 14) or (an # 0) then
1285- return Scan.markAt(aat, Diag.say("unknown instruction {}", [Fmt.str(aw)]));
1286- end;
1287- opcode(PlainOp[k]);
1288- end;
1289- return nil;
1290-end;
1291-
1292-(* One instruction or label, as assemble reads it *)
1293-proc statement(constExpr: ConstFn): ERROR;
1294-var
1295- i, k, cc, first: INT; wasListing: BOOL; start: Diag.Pos; v: I64;
1296-begin
1297- aat := Scan.tokPos();
1298- aw := asmWord();
1299- if LEN(aw) = 0 then return Scan.mark("expected an instruction"); end;
1300- Scan.next;
1301- if Scan.tok = Scan.sColon then
1302- sayAt(Chunk.pc, Diag.say("{}:", [Fmt.str(aw)]));
1303- k := try lab(Scan.intern(ADR(aw[0]), LEN(aw)));
1304- if lplaces[k] >= 0 then
1305- return Scan.markAt(aat, Diag.say("label {} is defined twice", [Fmt.str(aw)]));
1306- end;
1307- lplaces[k] := Chunk.pc;
1308- fixLink(lchains[k]);
1309- Scan.next;
1310- return nil;
1311- end;
1312- first := Chunk.pc;
1313- wasListing := listing;
1314- listing := false; (* the instruction is said as it is written *)
1315- if aw = "lock" then
1316- Chunk.put1(0F0H);
1317- aw := asmWord();
1318- Scan.next;
1319- end;
1320- cc := -1;
1321- if aw = "db" then
1322- repeat
1323- start := Scan.tokPos();
1324- v := try constExpr(true);
1325- if (v < -128) or (v > 255) then
1326- return Scan.markAt(Scan.spanFrom(start), Diag.say("expected a byte from 0 to 255, found {}", [Fmt.int(v)]));
1327- end;
1328- Chunk.put1(INT(v & 0FFH));
1329- if Scan.tok # Scan.sComma then break; end;
1330- Scan.next;
1331- until false;
1332- elsif (aw[0] = 'j') and ((aw = "jmp") or (cond(part(aw, 1, 3)) >= 0)) and (Scan.tok = Scan.sIdent) then
1333- (* a jump to a label *)
1334- k := try lab(Scan.id);
1335- Scan.next;
1336- if aw # "jmp" then cc := cond(part(aw, 1, 3)); end;
1337- if lplaces[k] >= 0 then
1338- if cc < 0 then jmpBack(lplaces[k]); else jccBack(cc, lplaces[k]); end;
1339- elsif cc < 0 then
1340- jmp(lchains[k]);
1341- else
1342- jcc(cc, lchains[k]);
1343- end;
1344- else
1345- an := 0;
1346- if Scan.tok # Scan.sSemicolon then
1347- repeat
1348- if an > 2 then return Scan.mark("too many operands"); end;
1349- try operand(ADR(ao[an]), constExpr);
1350- INC(an);
1351- if Scan.tok # Scan.sComma then break; end;
1352- Scan.next;
1353- until false;
1354- end;
1355- (* the size: a register's, or what the memory operand says *)
1356- asize := 8;
1357- for i := an - 1 to 0 by -1 do
1358- if (ao[i].kind = oReg) or ((ao[i].kind = oMem) and (ao[i].size # 0)) then asize := ao[i].size; end;
1359- end;
1360- if an > 0 then
1361- if (ao[0].kind = oReg) or ((ao[0].kind = oMem) and (ao[0].size # 0)) then asize := ao[0].size; end;
1362- end;
1363- awide := asize = 8;
1364- abyte := asize = 1;
1365- if asize = 2 then apfx := 66H; else apfx := 0; end;
1366- try instruction();
1367- end;
1368- if Scan.tok # Scan.sSemicolon then return Scan.mark("expected \";\""); end;
1369- listing := wasListing;
1370- sayAt(first, Diag.source(Scan.spanFrom(aat)));
1371- Scan.next;
1372- return nil;
1373-end;
1374-
1375-proc assemble*(constExpr: ConstFn): ERROR;
1376-var k: INT;
1377-begin
1378- numLabels := 0;
1379- while (Scan.tok # Scan.sEnd) and (Scan.tok # Scan.sEof) do
1380- if Scan.tok = Scan.sSemicolon then
1381- Scan.next;
1382- else
1383- try statement(constExpr);
1384- end;
1385- end;
1386- for k := 0 to numLabels - 1 do
1387- if lplaces[k] < 0 then
1388- return Scan.markAt(lusedAt[k], Diag.say("label {} isn't defined", [Fmt.str(Scan.nameOf(lnames[k]))]));
1389- end;
1390- end;
1391- return nil;
1392-end;
1393-
1394-(* Whether s holds a space *)
1395-proc hasSpace(s: []U8): BOOL;
1396-var i: INT;
1397-begin
1398- for i := 0 to LEN(s) - 1 do
1399- if s[i] = ' ' then return true; end;
1400- end;
1401- return false;
1402-end;
1403-
1404-(* n, in decimal, at least w wide, as write(n: w) *)
1405-proc padded(n, w: INT);
1406-var s: []U8; i: INT;
1407-begin
1408- s := Diag.say("{}", [Fmt.int(n)]);
1409- for i := LEN(s) to w - 1 do Out.str(" "); end;
1410- Out.str(s);
1411-end;
1412-
1413-(* The listing, raz -S: each live procedure of the module in the order
1414- it was made, each line of source it comes from, and under it the
1415- instructions made for it, at their offsets in the procedure; a jump
1416- within it says where to by its offset too. *)
1417-proc list*(home: INT);
1418-var order: ^INT; n, i, j, k, c, t, line: INT; text: []U8;
1419-begin
1420- order := ^INT(Scan.grab(Chunk.numChunks * SIZE(INT)));
1421- n := 0;
1422- for c := 0 to Chunk.numChunks - 1 do
1423- if Chunk.chunks[c].live and (Chunk.chunks[c].sec = Chunk.secText) and (Chunk.chunks[c].home = home) then
1424- i := n;
1425- while (i > 0) and (Chunk.chunks[order[i - 1]].start > Chunk.chunks[c].start) do
1426- order[i] := order[i - 1];
1427- DEC(i);
1428- end;
1429- order[i] := c;
1430- INC(n);
1431- end;
1432- end;
1433- i := 0; j := 0;
1434- for k := 0 to n - 1 do
1435- c := order[k];
1436- Out.ln;
1437- Out.str(Chunk.chunkName(c)); Out.str(":\n");
1438- line := -1;
1439- while (i < numSaid) and (said[i].at < Chunk.chunks[c].start) do INC(i); end;
1440- while (i < numSaid) and (said[i].at < Chunk.chunks[c].start + Chunk.chunks[c].size) do
1441- while (j < Chunk.numLines) and (Chunk.lines[j].at <= said[i].at) do
1442- if (Chunk.lines[j].chunk = c) and (Chunk.lines[j].line # line) then
1443- line := Chunk.lines[j].line;
1444- padded(line, 6);
1445- Out.str(" ");
1446- Out.str(Diag.lineText(Scan.nameOf(Chunk.lines[j].path), line));
1447- Out.ln;
1448- end;
1449- INC(j);
1450- end;
1451- text := said[i].text;
1452- t := said[i].at;
1453- if (text = "jmp") or (text = "call") then
1454- text := Diag.say("{} {}", [Fmt.str(text), Fmt.int(t + 5 + Chunk.get4At(t + 1) - Chunk.chunks[c].start)]);
1455- elsif (text[0] = 'j') and not hasSpace(text) then
1456- text := Diag.say("{} {}", [Fmt.str(text), Fmt.int(t + 6 + Chunk.get4At(t + 2) - Chunk.chunks[c].start)]);
1457- end;
1458- padded(t - Chunk.chunks[c].start, 14);
1459- Out.str(" ");
1460- Out.str(text);
1461- Out.ln;
1462- INC(i);
1463- end;
1464- end;
1465-end;
1466-
1467-begin
1468- listing := false;
1469- numSaid := 0;
1470- saidCap := 0;
1471- said := nil;
1472-end X64.

self/bench.sh deleted +0 -34

@@ -1,34 +0,0 @@
1-#!/bin/sh
2-# The scanner's speed against the seed's, on the compiler's own
3-# benchmark program: the best of seven runs of each. Run from the
4-# repository root, after self/check.sh has built the tests.
5-set -e
6-b=build/self
7-python3 test/genbench.py 12000 >$b/Bench.raz
8-fpc -O2 -Mobjfpc -Sh- -vew -FUbuild -Fusrc -o$b/scanbench.seed self/test/ScanBench.pas >/dev/null
9-./raz -Werror -I self -o $b/scanbench.self self/test/ScanBench.raz
10-echo "$(wc -l <$b/Bench.raz) lines"
11-for t in seed self; do
12- best=0
13- for i in 1 2 3 4 5 6 7; do
14- s=$(date +%s%N); $b/scanbench.$t $b/Bench.raz >/dev/null; e=$(date +%s%N)
15- d=$(( (e - s) / 1000000 )); if [ $best = 0 ] || [ $d -lt $best ]; then best=$d; fi
16- done
17- echo "$t: $best ms"
18-done
19-
20-# The whole compiler's speed, the seed's and this one's, on the same
21-# program: the best of five runs of each, as build/cmp/raz, which finds
22-# the library beside it.
23-mkdir -p build/cmp/bench
24-ln -sfn ../../lib build/cmp/lib
25-cp $b/Bench.raz build/cmp/bench/Bench.raz
26-for t in seed self; do
27- if [ $t = seed ]; then cp raz build/cmp/raz; else cp $b/raz.self build/cmp/raz; fi
28- best=0
29- for i in 1 2 3 4 5; do
30- s=$(date +%s%N); build/cmp/raz -o build/cmp/bench/Bench.$t build/cmp/bench/Bench.raz; e=$(date +%s%N)
31- d=$(( (e - s) / 1000000 )); if [ $best = 0 ] || [ $d -lt $best ]; then best=$d; fi
32- done
33- echo "compile, $t: $best ms"
34-done

self/check.sh deleted +0 -180

@@ -1,180 +0,0 @@
1-#!/bin/sh
2-# Tests self/'s units against the seed's: each dumper reads the same
3-# files and must give the same standard output, standard error and
4-# status. Run from the repository root, after `make raz`; the seed's
5-# side is built by fpc from src/.
6-set -e
7-b=build/self
8-mkdir -p $b
9-fpc -O2 -Mobjfpc -Sh- -vew -FUbuild -Fusrc -o$b/scandump.seed self/test/ScanDump.pas >/dev/null
10-./raz -Werror -I self -o $b/scandump.self self/test/ScanDump.raz
11-python3 self/test/genreals.py > $b/reals.raz
12-# one small file for each message the scanner makes, and the places
13-# diag shows them in: a tab, a long line, characters before the place
14-mkdir -p $b/lex
15-python3 self/test/genlex.py $b/lex
16-n=0; bad=0
17-for f in $b/lex/*.raz lib/*.raz examples/*.raz tools/*.raz self/*.raz self/test/*.raz test/run/*.raz test/err/*.raz \
18- conform/*/*.raz $b/reals.raz; do
19- [ -f "$f" ] || continue
20- s1=0; s2=0
21- $b/scandump.seed $f >$b/seed.out 2>$b/seed.err || s1=$?
22- $b/scandump.self $f >$b/self.out 2>$b/self.err || s2=$?
23- n=$((n + 1))
24- if [ $s1 != $s2 ] || ! cmp -s $b/seed.out $b/self.out || ! cmp -s $b/seed.err $b/self.err; then
25- echo "differs: $f (status $s1 and $s2)"; bad=$((bad + 1))
26- fi
27-done
28-echo "$n files, $bad differ"
29-test $bad = 0
30-
31-# Jump: a parser's way of going on after an error
32-./raz -Werror -I self -o $b/recover self/test/Recover.raz
33-printf 'a bad b bad bad c\nd bad\n' >$b/rec.raz
34-r=$($b/recover $b/rec.raz 2>/dev/null) || test $? = 1
35-test "$r" = "8 names, 4 failed, 4 errors" && echo "recover ok"
36-
37-# Chunk and Sym: a fixed pseudo-random script each, run by both sides,
38-# which print all they have made or answered; Sym also ends, as the
39-# argument says, in an error, whose message and status must agree
40-for u in Chunk Sym; do
41- l=$(echo $u | tr A-Z a-z)
42- fpc -O2 -Mobjfpc -Sh- -vew -FUbuild -Fusrc -o$b/${l}dump.seed self/test/${u}Dump.pas >/dev/null
43- ./raz -Werror -I self -o $b/${l}dump.self self/test/${u}Dump.raz
44-done
45-for a in "" dup deep; do
46- for s in seed self; do
47- t=0; $b/chunkdump.$s >$b/chunk.$s 2>/dev/null || t=$?
48- t2=0; $b/symdump.$s $a >$b/sym.$s.out 2>$b/sym.$s.err || t2=$?
49- echo "$t $t2" >$b/status.$s
50- done
51- cmp $b/status.seed $b/status.self
52- cmp $b/chunk.seed $b/chunk.self
53- cmp $b/sym.seed.out $b/sym.self.out
54- cmp $b/sym.seed.err $b/sym.self.err
55-done
56-echo "chunk and sym ok"
57-
58-# Link and Elf: a program of chunks made by a script, linked and written
59-# as a static, a dynamic and a stripped executable, which must be the
60-# same file from both sides
61-fpc -O2 -Mobjfpc -Sh- -vew -FUbuild -Fusrc -o$b/linkdump.seed self/test/LinkDump.pas >/dev/null
62-./raz -Werror -I self -o $b/linkdump.self self/test/LinkDump.raz
63-for m in 0 1 2; do
64- $b/linkdump.seed $m $b/link.seed
65- $b/linkdump.self $m $b/link.self
66- cmp $b/link.seed $b/link.self
67-done
68-echo "link and elf ok"
69-
70-# X64: every encoder, then the assembler on a long run of instructions
71-# of every kind and a file for each error it makes; the bytes and the
72-# listing, or the message and status, must be the same
73-fpc -O2 -Mobjfpc -Sh- -vew -FUbuild -Fusrc -o$b/x64dump.seed self/test/X64Dump.pas >/dev/null
74-./raz -Werror -I self -o $b/x64dump.self self/test/X64Dump.raz
75-$b/x64dump.seed >$b/x64.seed
76-$b/x64dump.self >$b/x64.self
77-cmp $b/x64.seed $b/x64.self
78-fpc -O2 -Mobjfpc -Sh- -vew -FUbuild -Fusrc -o$b/asmdump.seed self/test/AsmDump.pas >/dev/null
79-./raz -Werror -I self -o $b/asmdump.self self/test/AsmDump.raz
80-mkdir -p $b/asm
81-python3 self/test/genasm.py $b/asm
82-n=0; bad=0
83-for f in $b/asm/*.raz; do
84- s1=0; s2=0
85- $b/asmdump.seed $f >$b/seed.out 2>$b/seed.err || s1=$?
86- $b/asmdump.self $f >$b/self.out 2>$b/self.err || s2=$?
87- n=$((n + 1))
88- if [ $s1 != $s2 ] || ! cmp -s $b/seed.out $b/self.out || ! cmp -s $b/seed.err $b/self.err; then
89- echo "differs: $f (status $s1 and $s2)"; bad=$((bad + 1))
90- fi
91-done
92-echo "x64: $n assembler files, $bad differ"
93-test $bad = 0
94-
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 -Fusrc -o$b/gendump.seed self/test/GenDump.pas >/dev/null
100-./raz -Werror -I self -o $b/gendump.self self/test/GenDump.raz
101-for a in "" dyn; do
102- $b/gendump.seed $a >$b/gen.seed
103- $b/gendump.self $a >$b/gen.self
104- cmp $b/gen.seed $b/gen.self
105-done
106-echo "gen ok"
107-
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 -Fusrc -o$b/itemdump.seed self/test/ItemDump.pas >/dev/null
113-./raz -Werror -I self -o $b/itemdump.self self/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.self $a >$b/self.out 2>$b/self.err || s2=$?
119- n=$((n + 1))
120- if [ $s1 != $s2 ] || ! cmp -s $b/seed.out $b/self.out || ! cmp -s $b/seed.err $b/self.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-
127-# 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
130-# one's own options. Both sides run as build/cmp/raz, since a program
131-# holds the paths it was made from and the library is found beside the
132-# compiler.
133-printf 'module Version;\nconst Text* = "%s";\nend Version.\n' "$(tr -d "'" < build/version.inc)" >$b/Version.raz
134-./raz -Werror -I self -I $b -o $b/raz.self self/Raz.raz
135-c=build/cmp
136-mkdir -p $c
137-ln -sfn ../../lib $c/lib
138-# and the big program that times the compiler, 348,025 lines
139-mkdir -p $c/bench
140-python3 test/genbench.py 12000 >$c/bench/Bench.raz
141-files=
142-for f in $c/bench/Bench.raz lib/*.raz examples/*.raz tools/*.raz self/*.raz test/run/*.raz test/libc/*.raz test/bench/*.raz \
143- conform/run/*.raz test/err/*.raz conform/err/*.raz; do
144- files="$files $f"
145-done
146-for side in seed self; do
147- rm -rf $c/$side
148- mkdir -p $c/$side
149- if [ $side = seed ]; then cp raz $c/raz; else cp $b/raz.self $c/raz; fi
150- for f in $files; do
151- dir=$(dirname $f); name=$(basename $f .raz); x=$(echo $dir | tr / _).$name
152- flags=
153- case $dir in
154- examples|tools|lib|self) flags=-Werror ;;
155- esac
156- [ -f $dir/$name.args ] && [ $dir = test/err ] && flags="$flags $(cat $dir/$name.args)"
157- case $dir in
158- lib) opts= ;;
159- self|tools) opts="-I self -I build/self" ;;
160- test/err) opts="-I test/err/mods -I test/run/mods" ;;
161- *) opts="-I $dir/mods" ;;
162- esac
163- s=0
164- $c/raz $flags $opts -o $c/$side/$x $f >$c/$side/$x.out 2>$c/$side/$x.err || s=$?
165- echo $s >$c/$side/$x.status
166- done
167-done
168-n=0; bad=0
169-for f in $files; do
170- x=$(dirname $f | tr / _).$(basename $f .raz)
171- n=$((n + 1))
172- for e in "" .out .err .status; do
173- [ -f $c/seed/$x$e ] || [ -f $c/self/$x$e ] || continue
174- if ! cmp -s $c/seed/$x$e $c/self/$x$e; then
175- echo "differs: $f ($x$e)"; bad=$((bad + 1)); break
176- fi
177- done
178-done
179-echo "raz: $n files, $bad differ"
180-test $bad = 0

self/fixpoint.sh deleted +0 -27

@@ -1,27 +0,0 @@
1-#!/bin/sh
2-# The fixpoint: the seed builds self/ (stage 1), that builds self/
3-# (stage 2), that builds it again (stage 3), and stages 2 and 3 must
4-# be the same file. A program holds the paths it was made from, so each
5-# stage is built by the same command in the same place, from the
6-# compiler before it copied to build/fix/raz. Run from the repository
7-# root, after `make raz`. Then stage 3 stands in for ./raz (messages name
8-# the library by its path from the compiler, so it must be at the root)
9-# while `make check` and `make bench` run on it; the seed's comes back.
10-set -e
11-d=build/fix
12-rm -rf $d
13-mkdir -p $d/v
14-ln -s ../../lib $d/lib
15-printf 'module Version;\nconst Text* = "%s";\nend Version.\n' "$(tr -d "'" < build/version.inc)" >$d/v/Version.raz
16-cp raz $d/stage0
17-for n in 1 2 3; do
18- cp $d/stage$((n - 1)) $d/raz
19- $d/raz -Werror -I self -I $d/v -o $d/stage$n self/Raz.raz
20-done
21-cmp $d/stage2 $d/stage3
22-echo "fixpoint: stages 2 and 3 are the same, $(wc -c <$d/stage3) bytes"
23-cp raz $d/seed
24-trap 'cp $d/seed raz' EXIT
25-cp $d/stage3 raz
26-make check
27-make bench

self/test/AsmDump.pas deleted +0 -46

@@ -1,46 +0,0 @@
1-{ Assembles the instructions in the file of the argument, as the body of
2- a code procedure that ends in end, and prints the bytes and the
3- listing: the seed's side of a test of the assembler in self/X64.raz,
4- whose AsmDump.raz does the same and prints the same. Constants are
5- numbers, with a minus sign, and sums of them. }
6-program asmdump;
7-{$mode objfpc}{$H-}
8-uses diag, scan, chunk, x64;
9-var i: longint; path: string;
10-
11-function ConstVal(whole: boolean): int64;
12-var neg: boolean; v: int64;
13-begin
14- neg := tok = sMinus;
15- if neg then Next;
16- if tok <> sInt then Mark('expected a number');
17- v := ival;
18- Next;
19- if neg then v := -v;
20- while whole and (tok in [sPlus, sMinus]) do begin
21- neg := tok = sMinus;
22- Next;
23- if tok <> sInt then Mark('expected a number');
24- if neg then v := v - ival else v := v + ival;
25- Next;
26- end;
27- ConstVal := v;
28-end;
29-
30-begin
31- if Open(ParamStr(1)) <> '' then Fatal('no file');
32- path := 'lib/Rt.raz';
33- curFile := Intern(@path[1], length(path));
34- listing := true;
35- NewChunk(secText, 0, 0);
36- BeginChunk(0);
37- NoteLine(1, 1);
38- Next;
39- Assemble(@ConstVal);
40- EndChunk(0);
41- chunks^[0].live := true;
42- for i := 0 to pc - 1 do write(HexStr(code^[i], 2));
43- writeln;
44- List(0);
45- Finish;
46-end.

self/test/AsmDump.raz deleted +0 -55

@@ -1,55 +0,0 @@
1-(* Assembles the instructions in the file of the argument, as the body of
2- a code procedure that ends in end, and prints the bytes and the
3- listing: self/X64.raz's assembler's side of a test against the seed's,
4- AsmDump.pas, which prints the same. Constants are numbers, with a
5- minus sign, and sums of them. *)
6-module AsmDump;
7-import Out, Files, Diag, Scan, Chunk, X64;
8-
9-proc number(neg: BOOL): (I64, ERROR);
10-var v: I64;
11-begin
12- if Scan.tok # Scan.sInt then return 0, Scan.mark("expected a number"); end;
13- v := Scan.ival;
14- Scan.next;
15- if neg then v := -v; end;
16- return v, nil;
17-end;
18-
19-proc constant(whole: BOOL): (I64, ERROR);
20-var neg: BOOL; v, w: I64;
21-begin
22- neg := Scan.tok = Scan.sMinus;
23- if neg then Scan.next; end;
24- v := try number(neg);
25- while whole and ((Scan.tok = Scan.sPlus) or (Scan.tok = Scan.sMinus)) do
26- neg := Scan.tok = Scan.sMinus;
27- Scan.next;
28- w := try number(neg);
29- v := v + w;
30- end;
31- return v, nil;
32-end;
33-
34-proc main*;
35-var i: INT; path: []U8; err: ERROR;
36-begin
37- if LEN(Scan.open(Files.arg(1))) # 0 then Diag.fatal("no file"); end;
38- path := "lib/Rt.raz";
39- Chunk.setCurFile(Scan.intern(ADR(path[0]), LEN(path)));
40- X64.setListing(true);
41- _ := Chunk.newChunk(Chunk.secText, 0, 0);
42- Chunk.beginChunk(0);
43- Chunk.noteLine(1, 1);
44- Scan.next;
45- err := X64.assemble(constant);
46- if err # nil then Diag.finish; end;
47- Chunk.endChunk(0);
48- Chunk.setLive(0);
49- for i := 0 to Chunk.pc - 1 do Out.hex(U64(Chunk.text[i]), 2); end;
50- Out.ln;
51- X64.list(0);
52- Diag.finish;
53-end;
54-
55-end AsmDump.

self/test/ChunkDump.pas deleted +0 -89

@@ -1,89 +0,0 @@
1-{ Makes a program of chunks by a fixed pseudo-random script and prints
2- all of it: the seed's side of a test of self/Chunk.raz, whose
3- ChunkDump.raz does the same and prints the same. }
4-program chunkdump;
5-{$mode objfpc}{$H-}
6-uses diag, scan, chunk;
7-var
8- seed: int64;
9- names: array[0..7] of longint;
10- i, k, n, op, c, sum, open, x, y, z: longint;
11- b: array[0..63] of byte;
12-
13-function Rnd(n: longint): longint;
14-begin
15- seed := (seed * 1103515245 + 12345) and $7FFFFFFF;
16- Rnd := (seed shr 8) mod n;
17-end;
18-
19-begin
20- seed := 7;
21- for i := 0 to 7 do begin b[0] := 97 + i; names[i] := Intern(@b[0], 1) end;
22- open := -1;
23- sum := 0;
24- for k := 1 to 30000 do begin
25- op := Rnd(16);
26- case op of
27- 0..3: Put1(Rnd(256));
28- 4: begin x := Rnd(1 shl 30); y := Rnd(1 shl 30); Put4(x - y) end;
29- 5: begin x := Rnd(1 shl 30); y := Rnd(1 shl 30); Put8(int64(x) * 4096 - y) end;
30- 6: begin
31- if open >= 0 then EndChunk(open);
32- x := Rnd(5); y := Rnd(9);
33- open := NewChunk(secText, x - 1, y - 1);
34- BeginChunk(open);
35- end;
36- 7: begin x := Rnd(8); curFile := names[x]; x := Rnd(300); y := Rnd(80); NoteLine(x, y) end;
37- 8: if numChunks > 0 then begin x := Rnd(numChunks); y := Rnd(100); AddFixup(pc, x, y - 50) end;
38- 9: if (open >= 0) and (pc - chunks^[open].start > 8) then begin x := Rnd(6); TakeBack(x) end;
39- 10: begin
40- x := Rnd(5); y := Rnd(9);
41- c := NewChunk(secRodata, x - 1, y - 1);
42- n := Rnd(64);
43- for i := 0 to n - 1 do b[i] := Rnd(256);
44- x := Rnd(4);
45- SetData(c, @b[0], n, 1 shl x);
46- n := Rnd(4);
47- for i := 1 to n do begin x := Rnd(8); y := Rnd(numChunks); z := Rnd(10); AddDataFixup(c, x * 8, y, z) end;
48- end;
49- 11: begin
50- x := Rnd(5); y := Rnd(9);
51- c := NewChunk(secBss, x - 1, y - 1);
52- x := Rnd(100); y := Rnd(4);
53- SetBss(c, x, 1 shl y);
54- end;
55- 12: begin x := Rnd(8); c := ExternChunk(names[x]) end;
56- 13: if numChunks > 0 then begin
57- x := Rnd(numChunks); y := Rnd(8); z := Rnd(200); n := Rnd(5);
58- NoteVar(x, names[y], z - 100, n);
59- end;
60- 14: if pc >= 8 then begin
61- x := Rnd(1 shl 30); y := Rnd(1 shl 30);
62- Put4At(pc - 8, x - y);
63- sum := (sum + Get4At(pc - 8)) and $FFFFFF;
64- end;
65- 15: if numChunks > 0 then begin
66- x := Rnd(numChunks); chunks^[x].live := true;
67- x := Rnd(numChunks); y := Rnd(1 shl 30); chunks^[x].adr := y;
68- end;
69- end;
70- end;
71- if open >= 0 then EndChunk(open);
72- writeln('sum ', sum, ' pc ', pc, ' rolen ', rolen);
73- for i := 0 to numChunks - 1 do
74- with chunks^[i] do
75- writeln('C ', i, ' ', ord(sec), ' ', start, ' ', size, ' ', align, ' ', firstFix, ' ', numFix, ' ',
76- module, ' ', name, ' ', adr, ' ', ord(live), ' ', ord(ext), ' ', ChunkName(i));
77- for i := 0 to numFixups - 1 do
78- writeln('F ', fixups^[i].at, ' ', fixups^[i].chunk, ' ', fixups^[i].addend);
79- for i := 0 to numDataFixups - 1 do
80- writeln('D ', dataFixups^[i].at, ' ', dataFixups^[i].chunk, ' ', dataFixups^[i].addend);
81- for i := 0 to numLines - 1 do
82- writeln('L ', lines^[i].at, ' ', lines^[i].chunk, ' ', lines^[i].path, ' ', lines^[i].line, ' ', lines^[i].col);
83- for i := 0 to numVarNotes - 1 do
84- writeln('V ', varNotes[i].chunk, ' ', varNotes[i].name, ' ', varNotes[i].off, ' ', varNotes[i].kind);
85- for i := 0 to pc - 1 do write(HexStr(code^[i], 2));
86- writeln;
87- for i := 0 to rolen - 1 do write(HexStr(rodata^[i], 2));
88- writeln;
89-end.

self/test/ChunkDump.raz deleted +0 -118

@@ -1,118 +0,0 @@
1-(* Makes a program of chunks by a fixed pseudo-random script and prints
2- all of it: self/Chunk.raz's side of a test against the seed's,
3- ChunkDump.pas, which prints the same. *)
4-module ChunkDump;
5-import Out, Fmt, Scan, Chunk;
6-
7-var seed: I64;
8-
9-proc rnd(n: INT): INT;
10-begin
11- seed := (seed * 1103515245 + 12345) & 7FFFFFFFH;
12- return INT((seed shr 8) mod I64(n));
13-end;
14-
15-(* a flag, as the number the seed's side prints for it *)
16-proc bit(f: BOOL): INT;
17-begin
18- if f then return 1; end;
19- return 0;
20-end;
21-
22-proc main*;
23-var
24- names: [8]INT; b: [64]U8;
25- i, k, n, op, c, sum, open, x, y, z: INT;
26-begin
27- seed := 7;
28- for i := 0 to 7 do b[0] := U8(97 + i); names[i] := Scan.intern(ADR(b[0]), 1); end;
29- open := -1;
30- sum := 0;
31- for k := 1 to 30000 do
32- op := rnd(16);
33- match op of
34- | 0..3: Chunk.put1(rnd(256));
35- | 4: x := rnd(1 shl 30); y := rnd(1 shl 30); Chunk.put4(x - y);
36- | 5: x := rnd(1 shl 30); y := rnd(1 shl 30); Chunk.put8(I64(x) * 4096 - I64(y));
37- | 6:
38- if open >= 0 then Chunk.endChunk(open); end;
39- x := rnd(5); y := rnd(9);
40- open := Chunk.newChunk(Chunk.secText, x - 1, y - 1);
41- Chunk.beginChunk(open);
42- | 7:
43- x := rnd(8); Chunk.setCurFile(names[x]);
44- x := rnd(300); y := rnd(80); Chunk.noteLine(x, y);
45- | 8:
46- if Chunk.numChunks > 0 then
47- x := rnd(Chunk.numChunks); y := rnd(100); Chunk.addFixup(Chunk.pc, x, y - 50);
48- end;
49- | 9:
50- if (open >= 0) and (Chunk.pc - Chunk.chunks[open].start > 8) then
51- x := rnd(6); Chunk.takeBack(x);
52- end;
53- | 10:
54- x := rnd(5); y := rnd(9);
55- c := Chunk.newChunk(Chunk.secRodata, x - 1, y - 1);
56- n := rnd(64);
57- for i := 0 to n - 1 do b[i] := U8(rnd(256)); end;
58- x := rnd(4);
59- Chunk.setData(c, ADR(b[0]), n, 1 shl x);
60- n := rnd(4);
61- for i := 1 to n do
62- x := rnd(8); y := rnd(Chunk.numChunks); z := rnd(10);
63- Chunk.addDataFixup(c, x * 8, y, z);
64- end;
65- | 11:
66- x := rnd(5); y := rnd(9);
67- c := Chunk.newChunk(Chunk.secBss, x - 1, y - 1);
68- x := rnd(100); y := rnd(4);
69- Chunk.setBss(c, x, 1 shl y);
70- | 12: x := rnd(8); c := Chunk.externChunk(names[x]);
71- | 13:
72- if Chunk.numChunks > 0 then
73- x := rnd(Chunk.numChunks); y := rnd(8); z := rnd(200); n := rnd(5);
74- Chunk.noteVar(x, names[y], z - 100, n);
75- end;
76- | 14:
77- if Chunk.pc >= 8 then
78- x := rnd(1 shl 30); y := rnd(1 shl 30);
79- Chunk.put4At(Chunk.pc - 8, x - y);
80- sum := (sum + Chunk.get4At(Chunk.pc - 8)) & 0FFFFFFH;
81- end;
82- | else:
83- if Chunk.numChunks > 0 then
84- x := rnd(Chunk.numChunks); Chunk.setLive(x);
85- x := rnd(Chunk.numChunks); y := rnd(1 shl 30); Chunk.setAdr(x, y);
86- end;
87- end;
88- end;
89- if open >= 0 then Chunk.endChunk(open); end;
90- Fmt.print("sum {} pc {} rolen {}\n", [Fmt.int(sum), Fmt.int(Chunk.pc), Fmt.int(Chunk.rolen)]);
91- for i := 0 to Chunk.numChunks - 1 do
92- Fmt.print("C {} {} {} {} {} {} {} {} {} {} {} {} {}\n", [Fmt.int(i), Fmt.int(INT(Chunk.chunks[i].sec)),
93- Fmt.int(Chunk.chunks[i].start), Fmt.int(Chunk.chunks[i].size), Fmt.int(Chunk.chunks[i].align),
94- Fmt.int(Chunk.chunks[i].firstFix), Fmt.int(Chunk.chunks[i].numFix), Fmt.int(Chunk.chunks[i].home),
95- Fmt.int(Chunk.chunks[i].name), Fmt.int(Chunk.chunks[i].adr),
96- Fmt.int(bit(Chunk.chunks[i].live)), Fmt.int(bit(Chunk.chunks[i].ext)), Fmt.str(Chunk.chunkName(i))]);
97- end;
98- for i := 0 to Chunk.numFixups - 1 do
99- Fmt.print("F {} {} {}\n", [Fmt.int(Chunk.fixups[i].at), Fmt.int(Chunk.fixups[i].chunk), Fmt.int(Chunk.fixups[i].addend)]);
100- end;
101- for i := 0 to Chunk.numDataFixups - 1 do
102- Fmt.print("D {} {} {}\n", [Fmt.int(Chunk.dataFixups[i].at), Fmt.int(Chunk.dataFixups[i].chunk), Fmt.int(Chunk.dataFixups[i].addend)]);
103- end;
104- for i := 0 to Chunk.numLines - 1 do
105- Fmt.print("L {} {} {} {} {}\n", [Fmt.int(Chunk.lines[i].at), Fmt.int(Chunk.lines[i].chunk),
106- Fmt.int(Chunk.lines[i].path), Fmt.int(Chunk.lines[i].line), Fmt.int(Chunk.lines[i].col)]);
107- end;
108- for i := 0 to Chunk.numVarNotes - 1 do
109- Fmt.print("V {} {} {} {}\n", [Fmt.int(Chunk.varNotes[i].chunk), Fmt.int(Chunk.varNotes[i].name),
110- Fmt.int(Chunk.varNotes[i].off), Fmt.int(Chunk.varNotes[i].kind)]);
111- end;
112- for i := 0 to Chunk.pc - 1 do Out.hex(U64(Chunk.text[i]), 2); end;
113- Out.ln;
114- for i := 0 to Chunk.rolen - 1 do Out.hex(U64(Chunk.rodata[i]), 2); end;
115- Out.ln;
116-end;
117-
118-end ChunkDump.

self/test/GenDump.pas deleted +0 -708

@@ -1,708 +0,0 @@
1-{ Compiles procedures made by a fixed pseudo-random script of calls to
2- Gen, valid by construction, then prints the bytes, the fixups and the
3- listing (raz -S) of what it made: the seed's side of a test of
4- self/Gen.raz, whose GenDump.raz makes and prints the same. With an
5- argument, the entry point is the dynamic one. }
6-program gendump;
7-{$mode objfpc}{$H-}
8-uses diag, scan, sym, chunk, x64, gen;
9-
10-const
11- FirstProc = 3;
12- NumProcs = 80;
13- FirstGlob = FirstProc + NumProcs;
14- NumGlobs = 4;
15- Arith: array[0..9] of TSym = (sPlus, sMinus, sTimes, sDiv, sMod, sAmp, sBar, sXor, sShl, sShr);
16- Cmps: array[0..5] of TSym = (sEql, sNeq, sLss, sLeq, sGtr, sGeq);
17- RealOps: array[0..3] of TSym = (sPlus, sMinus, sTimes, sSlash);
18-
19-var
20- seed: int64;
21- slots: array[0..5] of int64;
22- regs: array[0..4] of longint;
23- numRegs: longint;
24- xregs: array[0..3] of longint;
25- numX: longint;
26- tuple2, tuple3, record3, sliceT: PType;
27- results: array[0..8] of PType;
28- curRes: longint;
29-
30-function Rnd(n: longint): longint;
31-begin
32- seed := (seed * 1103515245 + 12345) and $7FFFFFFF;
33- Rnd := (seed shr 8) mod n;
34-end;
35-
36-function Pos: TPos;
37-var p: TPos;
38-begin
39- p.f := 0; p.a := Rnd(400); p.b := p.a + 1;
40- Pos := p;
41-end;
42-
43-function Size: longint;
44-begin
45- Size := 1 shl Rnd(4);
46-end;
47-
48-function Slot: int64;
49-begin
50- Slot := slots[Rnd(6)];
51-end;
52-
53-function Bit(f: boolean): longint;
54-begin
55- if f then Bit := 1 else Bit := 0;
56-end;
57-
58-function Flag: boolean;
59-begin
60- Flag := Rnd(2) = 0;
61-end;
62-
63-function ConstVal: int64;
64-var x: longint; r: int64;
65-begin
66- x := Rnd(1 shl 30);
67- case Rnd(7) of
68- 0: r := x mod 10;
69- 1: r := -(x mod 100);
70- 2: r := int64(1) shl (x mod 20);
71- 3: r := x;
72- 4: r := int64(x) * 4096 * 4096 * 9 - 7;
73- 5: r := -int64(x) * 8;
74- else r := x mod 1000 - 500;
75- end;
76- ConstVal := r;
77-end;
78-
79-function NewObjs(t: PType; n: longint): PObj;
80-var first, o, last: PObj; i: longint;
81-begin
82- first := nil; last := nil;
83- for i := 0 to n - 1 do begin
84- o := NewObj(oVar, 0, t);
85- o^.val := 8 * i;
86- if last = nil then first := o else last^.next := o;
87- last := o;
88- end;
89- NewObjs := first;
90-end;
91-
92-procedure MakeTypes;
93-begin
94- tuple2 := NewType(fRecord, 16, 8);
95- tuple2^.tuple := true; tuple2^.len := 2; tuple2^.fields := NewObjs(tInt, 2);
96- tuple3 := NewType(fRecord, 24, 8);
97- tuple3^.tuple := true; tuple3^.len := 3; tuple3^.fields := NewObjs(tInt, 3);
98- record3 := NewType(fRecord, 24, 8);
99- record3^.fields := NewObjs(tReal, 3);
100- sliceT := NewType(fSlice, 16, 8);
101- sliceT^.base := tU8;
102- results[0] := nil;
103- results[1] := tInt;
104- results[2] := tReal;
105- results[3] := sliceT;
106- results[4] := tuple2;
107- results[5] := tuple3;
108- results[6] := tF32;
109- results[7] := tI16;
110- results[8] := record3;
111-end;
112-
113-function MemAdr: TAdr;
114-var a: TAdr; c: longint;
115-begin
116- c := Rnd(3);
117- if c = 0 then begin
118- a.base := bFrame; a.chunk := 0; a.hi := 0; a.off := Slot; if Flag then a.off := a.off + 8;
119- end else if c = 1 then begin
120- a.base := bGlobal; a.chunk := FirstGlob + Rnd(NumGlobs); a.hi := 0; a.off := 8 * Rnd(3);
121- end else begin
122- a.base := bSlot; a.chunk := Slot; a.hi := 0; a.off := 8 * Rnd(3);
123- end;
124- MemAdr := a;
125-end;
126-
127-function PushableAdr: TAdr;
128-var a: TAdr;
129-begin
130- a.chunk := 0; a.hi := 0;
131- if Flag then begin
132- a.base := bFrame; a.off := Slot; if Flag then a.off := a.off + 8;
133- end else begin
134- a.base := bGlobal; a.chunk := FirstGlob + Rnd(NumGlobs); a.off := 8 * Rnd(3);
135- end;
136- PushableAdr := a;
137-end;
138-
139-function RegAdr(r: longint): TAdr;
140-var a: TAdr;
141-begin
142- a.base := bReg; a.chunk := r; a.hi := 0; a.off := 0;
143- RegAdr := a;
144-end;
145-
146-function StackAdr: TAdr;
147-var a: TAdr;
148-begin
149- a.base := bStack; a.chunk := 0; a.hi := 0; a.off := 8 * Rnd(3);
150- StackAdr := a;
151-end;
152-
153-procedure PushIntVar;
154-var a: TAdr; sz, c: longint;
155-begin
156- sz := Size;
157- c := Rnd(5);
158- if (c = 0) and (numRegs > 0) then begin
159- if Flag then inPlace := regs[Rnd(numRegs)];
160- PushVar(RegAdr(regs[Rnd(numRegs)]), 8, false, kWord);
161- end else if c = 1 then begin
162- PushAdr(PushableAdr);
163- a := StackAdr;
164- PushVar(a, sz, Flag, kWord);
165- end else begin
166- a := MemAdr;
167- PushVar(a, sz, Flag, kWord);
168- end;
169-end;
170-
171-procedure IntExpr(b: longint); forward;
172-procedure RealExpr(k: TKind; b: longint); forward;
173-procedure CallExpr(want, b: longint); forward;
174-
175-function RealKind: TKind;
176-begin
177- if Flag then RealKind := kF64 else RealKind := kF32;
178-end;
179-
180-procedure IntExpr(b: longint);
181-var c, sz, n: longint; sg, f: boolean; k: TKind; sy: TSym; a: TAdr;
182-begin
183- if b > 0 then c := Rnd(14) else c := Rnd(3);
184- case c of
185- 0: PushConst(kWord, ConstVal);
186- 1: PushIntVar;
187- 2: PushIntVar;
188- 3, 4, 5: begin
189- IntExpr(b - 1); IntExpr(b - 1);
190- sy := Arith[Rnd(10)]; sz := Size; sg := Flag;
191- Op(sy, kWord, sz, sg);
192- end;
193- 6:
194- if Flag then begin
195- IntExpr(b - 1); IntExpr(b - 1);
196- sy := Cmps[Rnd(6)]; sg := Flag;
197- Compare(sy, kWord, sg);
198- end else begin
199- k := RealKind;
200- RealExpr(k, b - 1); RealExpr(k, b - 1);
201- sy := Cmps[Rnd(6)];
202- Compare(sy, k, false);
203- end;
204- 7: begin
205- IntExpr(b - 1);
206- n := Rnd(4); sz := Size; sg := Flag;
207- if n = 0 then Neg(kWord, sz, sg)
208- else if n = 1 then Complement(sz, sg)
209- else if n = 2 then NotBool
210- else Narrow(sz, sg);
211- end;
212- 8: begin
213- IntExpr(b - 1);
214- a := PushableAdr;
215- sz := Size; sg := Flag;
216- n := 10 + Rnd(100);
217- CheckIndex(n, Pos);
218- IndexArray(a, sz);
219- a := StackAdr; a.off := 0;
220- PushVar(a, sz, sg, kWord);
221- end;
222- 9: begin
223- n := Rnd(3);
224- sz := Size; sg := Flag;
225- if n = 0 then begin
226- a := MemAdr;
227- if a.base = bGlobal then a.base := bFrame;
228- IntExpr(b - 1);
229- f := Flag;
230- IndexSlice(a, sz, f, Pos);
231- end else if n = 1 then begin
232- PushAdr(PushableAdr);
233- IntExpr(b - 1);
234- a := StackAdr; a.off := 0;
235- f := Flag;
236- IndexSlice(a, sz, f, Pos);
237- end else begin
238- a.base := bReg; a.chunk := R13; a.hi := R14; a.off := 0;
239- IntExpr(b - 1);
240- f := Flag;
241- IndexSlice(a, sz, f, Pos);
242- end;
243- a := StackAdr; a.off := 0;
244- PushVar(a, sz, sg, kWord);
245- end;
246- 10: begin
247- k := RealKind;
248- RealExpr(k, b - 1);
249- RealToInt(k);
250- end;
251- 11: CallExpr(1, b - 1);
252- 12: begin
253- IntExpr(b - 1);
254- PushConst(kWord, Rnd(100) - 50);
255- Op(sPlus, kWord, 8, false);
256- end;
257- else begin
258- IntExpr(b - 1);
259- PushConst(kWord, ConstVal);
260- sy := Arith[Rnd(10)]; sz := Size; sg := Flag;
261- Op(sy, kWord, sz, sg);
262- end;
263- end;
264-end;
265-
266-procedure RealExpr(k: TKind; b: longint);
267-var c, n: longint; sy: TSym; a: TAdr; k2: TKind; v: int64;
268-begin
269- if b > 0 then c := Rnd(9) else c := Rnd(3);
270- case c of
271- 0: begin
272- n := Rnd(4);
273- if n = 0 then v := $3FF0000000000000
274- else if n = 1 then v := $4000000000000000
275- else if n = 2 then v := 0
276- else v := $3FE0000000000000;
277- PushConst(k, v);
278- end;
279- 1: begin
280- a := MemAdr;
281- if k = kF32 then PushVar(a, 4, false, k) else PushVar(a, 8, false, k);
282- end;
283- 2:
284- if numX > 0 then begin
285- if Flag then inPlace := xregs[Rnd(numX)];
286- PushVar(RegAdr(xregs[Rnd(numX)]), 8, false, k);
287- end else begin
288- PushAdr(PushableAdr);
289- a := StackAdr;
290- PushVar(a, 8, false, k);
291- end;
292- 3, 4: begin
293- RealExpr(k, b - 1); RealExpr(k, b - 1);
294- sy := RealOps[Rnd(4)];
295- Op(sy, k, 8, false);
296- end;
297- 5: begin
298- IntExpr(b - 1);
299- IntToReal(k, Flag);
300- end;
301- 6: begin
302- RealExpr(k, b - 1);
303- Neg(k, 8, false);
304- end;
305- 7: begin
306- if k = kF32 then k2 := kF64 else k2 := kF32;
307- RealExpr(k2, b - 1);
308- RealToReal(k2);
309- end;
310- else CallExpr(2, b - 1);
311- end;
312-end;
313-
314-procedure CallExpr(want, b: longint);
315-var
316- c: TCall; sig: PType; i, n, kind, r, ni: longint; k: TKind;
317-begin
318- sig := NewType(fProc, 8, 8);
319- sig^.variadic := Rnd(5) = 0;
320- if want = 1 then begin
321- r := Rnd(5);
322- if r = 0 then sig^.base := tBool
323- else if r = 1 then sig^.base := tI8
324- else if r = 2 then sig^.base := tU32
325- else if r = 3 then sig^.base := tuple2
326- else sig^.base := tInt;
327- end else if want = 2 then begin
328- if Flag then sig^.base := tReal else sig^.base := tF32;
329- end else
330- sig^.base := results[Rnd(9)];
331- c.sig := sig; c.param := nil; c.obj := nil; c.ext := Rnd(4) = 0;
332- c.n := 0; c.target := 0;
333- c.chunk := FirstProc + Rnd(NumProcs);
334- if Rnd(5) = 0 then begin c.chunk := -1; c.ext := false; c.target := Slot end;
335- n := Rnd(8);
336- for i := 0 to n - 1 do begin
337- kind := Rnd(4);
338- if kind = 0 then begin
339- k := RealKind;
340- RealExpr(k, b);
341- c.isF[c.n] := true; c.pair[c.n] := false;
342- inc(c.n);
343- end else if kind = 1 then begin
344- IntExpr(b); IntExpr(b);
345- c.isF[c.n] := false; c.pair[c.n] := true;
346- c.isF[c.n + 1] := false; c.pair[c.n + 1] := false;
347- inc(c.n, 2);
348- end else begin
349- IntExpr(b);
350- c.isF[c.n] := false; c.pair[c.n] := false;
351- inc(c.n);
352- end;
353- end;
354- Call(c);
355- ni := 0;
356- if sig^.base <> nil then begin
357- if sig^.base^.form = fSlice then ni := 0
358- else if sig^.base = tuple2 then ni := 2
359- else if BehindPointer(sig^.base) then ni := 0
360- else ni := 1;
361- end;
362- if want = 0 then begin
363- for i := 1 to ni do Drop;
364- end else if ni = 2 then
365- Drop;
366-end;
367-
368-procedure BoolExpr(b: longint);
369-var sy: TSym; sg: boolean;
370-begin
371- if Flag then begin
372- IntExpr(b); IntExpr(b);
373- sy := Cmps[Rnd(6)]; sg := Flag;
374- Compare(sy, kWord, sg);
375- end else
376- IntExpr(b);
377-end;
378-
379-procedure Stmt(b: longint); forward;
380-
381-procedure Assign(b: longint);
382-var a: TAdr; c, sz: longint; k: TKind;
383-begin
384- c := Rnd(6);
385- sz := Size;
386- if c = 0 then begin
387- a := MemAdr;
388- IntExpr(b);
389- PopVar(a, sz);
390- end else if c = 1 then begin
391- PushAdr(PushableAdr);
392- a := StackAdr;
393- IntExpr(b);
394- PopVar(a, sz);
395- end else if (c = 2) and (numRegs > 0) then begin
396- a := RegAdr(regs[Rnd(numRegs)]);
397- inPlace := a.chunk;
398- PushVar(a, 8, false, kWord);
399- IntExpr(b);
400- Op(Arith[Rnd(3)], kWord, 8, false);
401- PopVar(a, 8);
402- end else if (c = 3) and (numX > 0) then begin
403- k := RealKind;
404- a := RegAdr(xregs[Rnd(numX)]);
405- RealExpr(k, b);
406- PopVar(a, 8);
407- end else if c = 4 then begin
408- k := RealKind;
409- a := MemAdr;
410- RealExpr(k, b);
411- if k = kF32 then PopVar(a, 4) else PopVar(a, 8);
412- end else begin
413- a := MemAdr;
414- PushConst(kWord, ConstVal);
415- PopVar(a, sz);
416- end;
417-end;
418-
419-procedure RetStmt(b: longint);
420-var i: longint;
421-begin
422- if curRes = 1 then IntExpr(b)
423- else if curRes = 7 then IntExpr(b)
424- else if curRes = 2 then RealExpr(kF64, b)
425- else if curRes = 6 then RealExpr(kF32, b)
426- else if (curRes = 3) or (curRes = 4) then begin IntExpr(b); IntExpr(b) end
427- else if curRes = 5 then begin
428- for i := 0 to 2 do begin IntExpr(b); ResultTo(8 * i, 8) end;
429- end else if curRes = 8 then begin
430- PushAdr(PushableAdr);
431- CopyResult(0, 24);
432- end;
433- ReturnJump;
434-end;
435-
436-procedure Stmt(b: longint);
437-var
438- c, n, lo, i, start, saved, sz, tmp: longint; L, E, S, fj, tj: longint; a, a2: TAdr; sy: TSym; sg: boolean;
439- mk: int64; f: boolean;
440-begin
441- mk := TempMark;
442- if b <= 0 then c := Rnd(4) else c := Rnd(22);
443- case c of
444- 0, 1, 2, 3: Assign(b);
445- 4: begin
446- L := NoLabel;
447- BoolExpr(b);
448- JumpIf(L, false);
449- Stmt(b - 1);
450- Fix(L);
451- end;
452- 5: begin
453- L := NoLabel;
454- AlignLoop;
455- start := pc;
456- BoolExpr(b);
457- JumpIf(L, false);
458- Stmt(b - 1);
459- JumpBack(start);
460- Fix(L);
461- end;
462- 6: begin
463- L := NoLabel;
464- IntExpr(b); IntExpr(b);
465- sy := Cmps[Rnd(6)]; sg := Flag;
466- if Flag then JumpCmp(sy, sg, L) else JumpOut(sy, sg, L);
467- Stmt(b - 1);
468- Fix(L);
469- end;
470- 7: begin
471- fj := NoLabel; tj := NoLabel;
472- IntExpr(b); IntExpr(b);
473- sy := Cmps[Rnd(6)]; sg := Flag;
474- CondValue(sy, sg, fj, tj);
475- a := MemAdr;
476- PopVar(a, 1);
477- end;
478- 8: CallExpr(0, b);
479- 9: begin
480- a := MemAdr;
481- if a.base = bSlot then begin a.base := bFrame; a.off := slots[0] end;
482- IntExpr(b);
483- PopVar(a, 8);
484- E := NoLabel;
485- n := 2 + Rnd(4); lo := Rnd(5) - 2;
486- if Flag then S := NoLabel else S := pc;
487- start := JumpTable(a.off, lo, n, S, E);
488- for i := 0 to n - 1 do TableEntry(start, pc + 4 * (n - i));
489- for i := 0 to n - 1 do
490- Stmt(b - 1);
491- Fix(E);
492- end;
493- 10: begin
494- PushAdr(PushableAdr); PushAdr(PushableAdr);
495- n := 1 + Rnd(150); lo := 8 * Rnd(3);
496- CopyBlock(n, lo);
497- end;
498- 11: begin
499- PushAdr(PushableAdr);
500- a := MemAdr;
501- if Flag and (numRegs > 1) then begin
502- a.base := bReg; a.chunk := regs[0]; a.hi := regs[1]; a.off := 0;
503- end;
504- n := 1 + Rnd(150);
505- CopyTo(a, n);
506- end;
507- 12: begin
508- a := MemAdr;
509- n := 1 + Rnd(100);
510- ZeroVar(a, n);
511- end;
512- 13: begin
513- tmp := AllocTemp(16, 8);
514- n := Rnd(3);
515- sz := Size; sg := Flag;
516- if n = 0 then begin
517- a := PushableAdr;
518- PushAdr(a); IntExpr(b); IntExpr(b);
519- a := StackAdr; a.off := 0;
520- f := Flag; n := 10 + Rnd(50);
521- Slice(a, f, n, sz, tmp, sg, Pos);
522- end else if n = 1 then begin
523- a := MemAdr;
524- if a.base = bGlobal then a.base := bFrame;
525- IntExpr(b); IntExpr(b);
526- Slice(a, false, 0, sz, tmp, sg, Pos);
527- end else begin
528- IntExpr(b); IntExpr(b); IntExpr(b);
529- SlicePtr(sz, tmp, sg, Pos);
530- end;
531- end;
532- 14: begin
533- a.off := Slot; a2.off := Slot; sz := Size; f := Flag;
534- CopySlice(a.off, a2.off, sz, f, Pos);
535- end;
536- 15: begin
537- n := Rnd(4); sz := Size; sg := Flag;
538- if n = 0 then begin
539- PushAdr(PushableAdr); IntExpr(b);
540- f := Flag;
541- IncDec(sz, sg, f);
542- end else if (n = 1) and (numRegs > 0) then begin
543- IntExpr(b);
544- IncDecReg(regs[0], sz, sg, Flag);
545- end else if n = 2 then begin
546- IntExpr(b);
547- n := 3 + Rnd(6); lo := FirstGlob + Rnd(NumGlobs);
548- CheckEnum(n, lo, Pos);
549- Drop;
550- end else begin
551- IntExpr(b);
552- n := Rnd(8000);
553- CheckNil(n, Pos);
554- Drop;
555- end;
556- end;
557- 16: begin
558- n := Rnd(3);
559- if n = 0 then begin
560- a.off := Slot; a2.off := Slot; n := Rnd(4); f := Flag;
561- CompareSeq(a.off, a2.off, n, f);
562- Drop;
563- end else if n = 1 then begin
564- IntExpr(b);
565- ErrorText(AllocTemp(16, 8));
566- end else begin
567- IntExpr(b);
568- n := 1 + Rnd(200);
569- ZeroNew(n);
570- Drop;
571- end;
572- end;
573- 17: begin
574- n := Rnd(3);
575- if n = 0 then begin
576- IntExpr(b); IntExpr(b); IntExpr(b);
577- Atomic(bCas);
578- end else if n = 1 then begin
579- IntExpr(b); IntExpr(b);
580- Atomic(bXchg);
581- end else begin
582- IntExpr(b); IntExpr(b);
583- Atomic(bXadd);
584- end;
585- Drop;
586- end;
587- 18: begin
588- n := Rnd(7);
589- for i := 1 to n do IntExpr(b);
590- SysCall(n);
591- Drop;
592- if Flag then Fence;
593- end;
594- 19: begin
595- L := NoLabel;
596- start := DeferBegin(L, saved);
597- Stmt(b - 1);
598- DeferEnd(L, saved);
599- RunDefer(start);
600- end;
601- 20: if curRes <> 0 then RetStmt(b) else Assign(b);
602- else
603- if curRes <> 0 then begin
604- TryAlign;
605- TryReturn(Slot);
606- end else
607- Assign(b);
608- end;
609- ReleaseTemps(mk);
610-end;
611-
612-procedure GenProc(c: longint);
613-var
614- sig: PType; params, p, last: PObj; i, n, kind, mask, j, ns, line: longint; t: PType;
615- mk: TCodeMark; open: boolean;
616-begin
617- sig := NewType(fProc, 8, 8);
618- curRes := Rnd(9);
619- sig^.base := results[curRes];
620- params := nil; last := nil;
621- n := Rnd(8);
622- for i := 0 to n - 1 do begin
623- kind := Rnd(5);
624- if kind = 0 then t := tReal
625- else if kind = 1 then t := sliceT
626- else if kind = 2 then t := tI32
627- else t := tInt;
628- p := NewObj(oVar, 0, t);
629- p^.param := true;
630- p^.isVar := kind = 4;
631- if last = nil then params := p else last^.next := p;
632- last := p;
633- end;
634- BeginProc(sig, params);
635- for i := 0 to 5 do slots[i] := AllocPerm(8, 8);
636- mask := Rnd(32);
637- j := Rnd(16);
638- mask := mask or (j shl XBit);
639- if Rnd(3) = 0 then mask := 0;
640- numRegs := 0; numX := 0;
641- for j := 0 to 4 do
642- if mask and (1 shl j) <> 0 then begin regs[numRegs] := VarRegs[j]; inc(numRegs) end;
643- for j := 0 to 3 do
644- if mask and (1 shl (XBit + j)) <> 0 then begin
645- xregs[numX] := XVarRegs[j]; inc(numX);
646- XHome(XVarRegs[j], AllocPerm(8, 8));
647- end;
648- j := 0;
649- p := params;
650- while p <> nil do begin
651- if (p^.typ = tInt) and (not p^.isVar) and (j < numRegs) and Flag then begin
652- p^.reg := regs[j]; inc(j);
653- end else if (p^.typ = tReal) and (numX > 0) and Flag then begin
654- p^.reg := xregs[0];
655- end else if Flag then
656- KeepArrived(p);
657- p := p^.next;
658- end;
659- UseRegs(mask);
660- line := 1 + Rnd(40);
661- EnterBody(c, line);
662- MarkCode(mk);
663- if Flag then begin
664- Stmt(2);
665- Rewind(mk);
666- Redo(mk);
667- end;
668- ns := 2 + Rnd(8);
669- for i := 1 to ns do Stmt(3);
670- open := Flag and (sig^.base <> nil);
671- if (sig^.base <> nil) and (not open) then RetStmt(2);
672- EndProc(c, open);
673- writeln('proc ', c, ' lost ', Bit(lost), ' regs ', mask, ' saves ', chunks^[c].saveMask, ' at ', chunks^[c].saveAt);
674-end;
675-
676-function ChunkNameOf(i: longint): longint;
677-var s: string;
678-begin
679- s := 'p' + chr(48 + i div 10) + chr(48 + i mod 10);
680- ChunkNameOf := Intern(@s[1], 3);
681-end;
682-
683-var
684- i, c, entry: longint; path: string; links: array[0..1] of TLink; dyn: boolean;
685-begin
686- seed := 5;
687- path := 'lib/Rt.raz';
688- if Open(path) <> '' then Fatal('no file');
689- dyn := ParamCount >= 1;
690- listing := true;
691- curFile := Intern(@path[1], length(path));
692- for i := 0 to NumProcs - 1 do begin c := NewChunk(secText, -1, ChunkNameOf(i)); chunks^[c].live := true end;
693- for i := 0 to NumGlobs - 1 do begin
694- c := NewChunk(secBss, -1, ChunkNameOf(NumProcs + i));
695- SetBss(c, 64, 8);
696- end;
697- MakeTypes;
698- for i := 0 to NumProcs - 1 do GenProc(FirstProc + i);
699- links[0].chunk := FirstProc; links[0].into := FirstGlob;
700- links[1].chunk := FirstProc + 1; links[1].into := FirstGlob + 1;
701- entry := EntryPoint(dyn, nil, nil, FirstProc + 2, FirstProc + 3, links, 2);
702- writeln('entry ', entry, ' pc ', pc, ' fixups ', numFixups, ' lines ', numLines, ' said ', SaidCount);
703- for i := 0 to pc - 1 do write(HexStr(code^[i], 2));
704- writeln;
705- for i := 0 to numFixups - 1 do writeln('F ', fixups^[i].at, ' ', fixups^[i].chunk, ' ', fixups^[i].addend);
706- for i := 0 to numLines - 1 do writeln('L ', lines^[i].at, ' ', lines^[i].chunk, ' ', lines^[i].line, ' ', lines^[i].col);
707- List(-1);
708-end.

self/test/GenDump.raz deleted +0 -732

@@ -1,732 +0,0 @@
1-(* Compiles procedures made by a fixed pseudo-random script of calls to
2- Gen, valid by construction (an expression pushes its operands, then
3- operates on them; a statement leaves the stack as it found it), then
4- prints the bytes, the fixups, the line notes and the listing (raz -S)
5- of what it made: self/Gen.raz's side of a test against the seed's,
6- GenDump.pas, which makes and prints the same. With the argument dyn,
7- the entry point is the dynamic one. *)
8-module GenDump;
9-import Out, Fmt, Diag, Scan, Sym, Chunk, X := X64, Gen;
10-
11-const
12- FirstProc = 3; (* chunks 0 to 2 are Gen's own *)
13- NumProcs = 80;
14- FirstGlob = FirstProc + NumProcs;
15- NumGlobs = 4;
16- Arith: [10]Scan.Sym = [Scan.sPlus, Scan.sMinus, Scan.sTimes, Scan.sDiv, Scan.sMod,
17- Scan.sAmp, Scan.sBar, Scan.sXor, Scan.sShl, Scan.sShr];
18- Cmps: [6]Scan.Sym = [Scan.sEql, Scan.sNeq, Scan.sLss, Scan.sLeq, Scan.sGtr, Scan.sGeq];
19- RealOps: [4]Scan.Sym = [Scan.sPlus, Scan.sMinus, Scan.sTimes, Scan.sSlash];
20-
21-var
22- seed: I64;
23- slots: [6]I64; (* frame slots of the procedure *)
24- regs: [5]INT; (* the registers of variables it keeps *)
25- numRegs: INT;
26- xregs: [4]INT; (* ... of reals, as numbered from XmmVar *)
27- numX: INT;
28- tuple2, tuple3, record3, sliceT: ^Sym.Type;
29- results: [9]^Sym.Type;
30- curRes: INT; (* the procedure's result: an index of results *)
31-
32-proc rnd(n: INT): INT;
33-begin
34- seed := (seed * 1103515245 + 12345) & 7FFFFFFFH;
35- return INT((seed shr 8) mod I64(n));
36-end;
37-
38-proc pos: Diag.Pos;
39-var p: Diag.Pos;
40-begin
41- p.f := 0; p.a := rnd(400); p.b := p.a + 1;
42- return p;
43-end;
44-
45-(* a size of 1, 2, 4 or 8 bytes *)
46-proc size: INT;
47-begin
48- return 1 shl rnd(4);
49-end;
50-
51-(* a slot of the procedure's frame *)
52-proc slot: I64;
53-begin
54- return slots[rnd(6)];
55-end;
56-
57-proc bit(f: BOOL): INT;
58-begin
59- if f then return 1; end;
60- return 0;
61-end;
62-
63-proc flag: BOOL;
64-begin
65- return rnd(2) = 0;
66-end;
67-
68-proc constVal: I64;
69-var x: INT; r: I64;
70-begin
71- x := rnd(1 shl 30);
72- match rnd(7) of
73- | 0: r := x mod 10;
74- | 1: r := -(x mod 100);
75- | 2: r := I64(1) shl (x mod 20);
76- | 3: r := x;
77- | 4: r := I64(x) * 4096 * 4096 * 9 - 7;
78- | 5: r := -I64(x) * 8;
79- | else: r := x mod 1000 - 500;
80- end;
81- return r;
82-end;
83-
84-proc newObjs(t: ^Sym.Type; n: INT): ^Sym.Obj;
85-var first, o, last: ^Sym.Obj; i: INT;
86-begin
87- first := nil; last := nil;
88- for i := 0 to n - 1 do
89- o := Sym.newObj(Sym.oVar, 0, t);
90- o^.val := 8 * i;
91- if last = nil then first := o; else last^.next := o; end;
92- last := o;
93- end;
94- return first;
95-end;
96-
97-proc makeTypes;
98-begin
99- tuple2 := Sym.newType(Sym.fRecord, 16, 8);
100- tuple2^.tuple := true; tuple2^.len := 2; tuple2^.fields := newObjs(Sym.tInt, 2);
101- tuple3 := Sym.newType(Sym.fRecord, 24, 8);
102- tuple3^.tuple := true; tuple3^.len := 3; tuple3^.fields := newObjs(Sym.tInt, 3);
103- record3 := Sym.newType(Sym.fRecord, 24, 8);
104- record3^.fields := newObjs(Sym.tReal, 3);
105- sliceT := Sym.newType(Sym.fSlice, 16, 8);
106- sliceT^.base := Sym.tU8;
107- results[0] := nil;
108- results[1] := Sym.tInt;
109- results[2] := Sym.tReal;
110- results[3] := sliceT;
111- results[4] := tuple2;
112- results[5] := tuple3;
113- results[6] := Sym.tF32;
114- results[7] := Sym.tI16;
115- results[8] := record3;
116-end;
117-
118-(* Variables *)
119-
120-(* the address of a variable of the procedure that has one: in the frame,
121- a chunk, or a slot holding its address *)
122-proc memAdr: Gen.Adr;
123-var a: Gen.Adr; c: INT;
124-begin
125- c := rnd(3);
126- if c = 0 then
127- a.base := Gen.bFrame; a.chunk := 0; a.hi := 0; a.off := slot(); if flag() then a.off := a.off + 8; end;
128- elsif c = 1 then
129- a.base := Gen.bGlobal; a.chunk := FirstGlob + rnd(NumGlobs); a.hi := 0; a.off := 8 * rnd(3);
130- else
131- a.base := Gen.bSlot; a.chunk := INT(slot()); a.hi := 0; a.off := 8 * rnd(3);
132- end;
133- return a;
134-end;
135-
136-(* an address that can go on the stack: frame or chunk *)
137-proc pushableAdr: Gen.Adr;
138-var a: Gen.Adr;
139-begin
140- a.chunk := 0; a.hi := 0;
141- if flag() then
142- a.base := Gen.bFrame; a.off := slot(); if flag() then a.off := a.off + 8; end;
143- else
144- a.base := Gen.bGlobal; a.chunk := FirstGlob + rnd(NumGlobs); a.off := 8 * rnd(3);
145- end;
146- return a;
147-end;
148-
149-proc regAdr(r: INT): Gen.Adr;
150-var a: Gen.Adr;
151-begin
152- a.base := Gen.bReg; a.chunk := r; a.hi := 0; a.off := 0;
153- return a;
154-end;
155-
156-proc stackAdr: Gen.Adr;
157-var a: Gen.Adr;
158-begin
159- a.base := Gen.bStack; a.chunk := 0; a.hi := 0; a.off := 8 * rnd(3);
160- return a;
161-end;
162-
163-proc pushIntVar;
164-var a: Gen.Adr; sz: INT; c: INT;
165-begin
166- sz := size();
167- c := rnd(5);
168- if (c = 0) and (numRegs > 0) then
169- if flag() then Gen.setInPlace(regs[rnd(numRegs)]); end;
170- Gen.pushVar(regAdr(regs[rnd(numRegs)]), 8, false, Gen.kWord);
171- elsif c = 1 then
172- Gen.pushAdr(pushableAdr());
173- a := stackAdr();
174- Gen.pushVar(a, sz, flag(), Gen.kWord);
175- else
176- a := memAdr();
177- Gen.pushVar(a, sz, flag(), Gen.kWord);
178- end;
179-end;
180-
181-proc intExpr(b: INT); forward;
182-proc realExpr(k: Gen.Kind; b: INT); forward;
183-proc callExpr(want, b: INT); forward;
184-
185-proc realKind: Gen.Kind;
186-begin
187- if flag() then return Gen.kF64; end;
188- return Gen.kF32;
189-end;
190-
191-proc intExpr(b: INT);
192-var c, sz, n: INT; sg, f: BOOL; k: Gen.Kind; sy: Scan.Sym; a: Gen.Adr;
193-begin
194- if b > 0 then c := rnd(14); else c := rnd(3); end;
195- match c of
196- | 0: Gen.pushConst(Gen.kWord, constVal());
197- | 1: pushIntVar();
198- | 2: pushIntVar();
199- | 3, 4, 5:
200- intExpr(b - 1); intExpr(b - 1);
201- sy := Arith[rnd(10)]; sz := size(); sg := flag();
202- Gen.op(sy, Gen.kWord, sz, sg);
203- | 6:
204- if flag() then
205- intExpr(b - 1); intExpr(b - 1);
206- sy := Cmps[rnd(6)]; sg := flag();
207- Gen.compare(sy, Gen.kWord, sg);
208- else
209- k := realKind();
210- realExpr(k, b - 1); realExpr(k, b - 1);
211- sy := Cmps[rnd(6)];
212- Gen.compare(sy, k, false);
213- end;
214- | 7:
215- intExpr(b - 1);
216- n := rnd(4); sz := size(); sg := flag();
217- if n = 0 then Gen.neg(Gen.kWord, sz, sg);
218- elsif n = 1 then Gen.complement(sz, sg);
219- elsif n = 2 then Gen.notBool();
220- else Gen.narrow(sz, sg); end;
221- | 8:
222- (* an element of an array in the frame or a chunk *)
223- intExpr(b - 1);
224- a := pushableAdr();
225- sz := size(); sg := flag();
226- n := 10 + rnd(100);
227- Gen.checkIndex(n, pos());
228- Gen.indexArray(a, sz);
229- a := stackAdr(); a.off := 0;
230- Gen.pushVar(a, sz, sg, Gen.kWord);
231- | 9:
232- (* an element of a slice, in a frame slot or on the stack, or in registers *)
233- n := rnd(3);
234- sz := size(); sg := flag();
235- if n = 0 then
236- a := memAdr();
237- if a.base = Gen.bGlobal then a.base := Gen.bFrame; end;
238- intExpr(b - 1);
239- f := flag();
240- Gen.indexSlice(a, sz, f, pos());
241- elsif n = 1 then
242- Gen.pushAdr(pushableAdr());
243- intExpr(b - 1);
244- a := stackAdr(); a.off := 0;
245- f := flag();
246- Gen.indexSlice(a, sz, f, pos());
247- else
248- a.base := Gen.bReg; a.chunk := X.R13; a.hi := X.R14; a.off := 0;
249- intExpr(b - 1);
250- f := flag();
251- Gen.indexSlice(a, sz, f, pos());
252- end;
253- a := stackAdr(); a.off := 0;
254- Gen.pushVar(a, sz, sg, Gen.kWord);
255- | 10:
256- k := realKind();
257- realExpr(k, b - 1);
258- Gen.realToInt(k);
259- | 11: callExpr(1, b - 1);
260- | 12:
261- (* x + 1, and the offset noted on a word *)
262- intExpr(b - 1);
263- Gen.pushConst(Gen.kWord, rnd(100) - 50);
264- Gen.op(Scan.sPlus, Gen.kWord, 8, false);
265- | else:
266- intExpr(b - 1);
267- Gen.pushConst(Gen.kWord, constVal());
268- sy := Arith[rnd(10)]; sz := size(); sg := flag();
269- Gen.op(sy, Gen.kWord, sz, sg);
270- end;
271-end;
272-
273-proc realExpr(k: Gen.Kind; b: INT);
274-var c, n: INT; sy: Scan.Sym; a: Gen.Adr; k2: Gen.Kind; v: I64;
275-begin
276- if b > 0 then c := rnd(9); else c := rnd(3); end;
277- match c of
278- | 0:
279- n := rnd(4);
280- if n = 0 then v := 3FF0000000000000H;
281- elsif n = 1 then v := 4000000000000000H;
282- elsif n = 2 then v := 0;
283- else v := 3FE0000000000000H; end;
284- Gen.pushConst(k, v);
285- | 1:
286- a := memAdr();
287- if k = Gen.kF32 then Gen.pushVar(a, 4, false, k); else Gen.pushVar(a, 8, false, k); end;
288- | 2:
289- if numX > 0 then
290- if flag() then Gen.setInPlace(xregs[rnd(numX)]); end;
291- Gen.pushVar(regAdr(xregs[rnd(numX)]), 8, false, k);
292- else
293- Gen.pushAdr(pushableAdr());
294- a := stackAdr();
295- Gen.pushVar(a, 8, false, k);
296- end;
297- | 3, 4:
298- realExpr(k, b - 1); realExpr(k, b - 1);
299- sy := RealOps[rnd(4)];
300- Gen.op(sy, k, 8, false);
301- | 5:
302- intExpr(b - 1);
303- Gen.intToReal(k, flag());
304- | 6:
305- realExpr(k, b - 1);
306- Gen.neg(k, 8, false);
307- | 7:
308- if k = Gen.kF32 then k2 := Gen.kF64; else k2 := Gen.kF32; end;
309- realExpr(k2, b - 1);
310- Gen.realToReal(k2);
311- | else: callExpr(2, b - 1);
312- end;
313-end;
314-
315-(* A call of one of the procedures, with arguments of all kinds. want: 0
316- for a statement, any result; 1 an integer is left on the stack, 2 a
317- real. *)
318-proc callExpr(want, b: INT);
319-var
320- c: Gen.CallInfo; sig: ^Sym.Type; i, n, kind, r, ni: INT; k: Gen.Kind;
321-begin
322- sig := Sym.newType(Sym.fProc, 8, 8);
323- sig^.variadic := rnd(5) = 0;
324- if want = 1 then
325- r := rnd(5);
326- if r = 0 then sig^.base := Sym.tBool;
327- elsif r = 1 then sig^.base := Sym.tI8;
328- elsif r = 2 then sig^.base := Sym.tU32;
329- elsif r = 3 then sig^.base := tuple2;
330- else sig^.base := Sym.tInt; end;
331- elsif want = 2 then
332- if flag() then sig^.base := Sym.tReal; else sig^.base := Sym.tF32; end;
333- else
334- sig^.base := results[rnd(9)];
335- end;
336- c.sig := sig; c.param := nil; c.obj := nil; c.ext := rnd(4) = 0;
337- c.n := 0; c.target := 0;
338- c.chunk := FirstProc + rnd(NumProcs);
339- if rnd(5) = 0 then c.chunk := -1; c.ext := false; c.target := slot(); end;
340- n := rnd(8);
341- for i := 0 to n - 1 do
342- kind := rnd(4);
343- if kind = 0 then
344- k := realKind();
345- realExpr(k, b);
346- c.isF[c.n] := true; c.pair[c.n] := false;
347- INC(c.n);
348- elsif kind = 1 then
349- intExpr(b); intExpr(b);
350- c.isF[c.n] := false; c.pair[c.n] := true;
351- c.isF[c.n + 1] := false; c.pair[c.n + 1] := false;
352- INC(c.n, 2);
353- else
354- intExpr(b);
355- c.isF[c.n] := false; c.pair[c.n] := false;
356- INC(c.n);
357- end;
358- end;
359- Gen.call(c);
360- (* what comes back: a value or two, or nothing, or a temporary *)
361- ni := 0;
362- if sig^.base # nil then
363- if sig^.base^.form = Sym.fSlice then ni := 0;
364- elsif sig^.base = tuple2 then ni := 2;
365- elsif Sym.behindPointer(sig^.base) then ni := 0;
366- else ni := 1; end;
367- end;
368- if want = 0 then
369- for i := 1 to ni do Gen.drop(); end;
370- elsif ni = 2 then
371- Gen.drop(); (* the second; the first is the value *)
372- end;
373-end;
374-
375-(* A condition, left as a BOOL on the stack *)
376-proc boolExpr(b: INT);
377-var sy: Scan.Sym; sg: BOOL;
378-begin
379- if flag() then
380- intExpr(b); intExpr(b);
381- sy := Cmps[rnd(6)]; sg := flag();
382- Gen.compare(sy, Gen.kWord, sg);
383- else
384- intExpr(b);
385- end;
386-end;
387-
388-proc stmt(b: INT); forward;
389-
390-(* a variable assigned the value on top: its address, if on the stack,
391- having been pushed first *)
392-proc assign(b: INT);
393-var a: Gen.Adr; c, sz: INT; k: Gen.Kind;
394-begin
395- c := rnd(6);
396- sz := size();
397- if c = 0 then
398- a := memAdr();
399- intExpr(b);
400- Gen.popVar(a, sz);
401- elsif c = 1 then
402- Gen.pushAdr(pushableAdr());
403- a := stackAdr();
404- intExpr(b);
405- Gen.popVar(a, sz);
406- elsif (c = 2) and (numRegs > 0) then
407- a := regAdr(regs[rnd(numRegs)]);
408- Gen.setInPlace(a.chunk);
409- Gen.pushVar(a, 8, false, Gen.kWord);
410- intExpr(b);
411- Gen.op(Arith[rnd(3)], Gen.kWord, 8, false);
412- Gen.popVar(a, 8);
413- elsif (c = 3) and (numX > 0) then
414- k := realKind();
415- a := regAdr(xregs[rnd(numX)]);
416- realExpr(k, b);
417- Gen.popVar(a, 8);
418- elsif c = 4 then
419- k := realKind();
420- a := memAdr();
421- realExpr(k, b);
422- if k = Gen.kF32 then Gen.popVar(a, 4); else Gen.popVar(a, 8); end;
423- else
424- a := memAdr();
425- Gen.pushConst(Gen.kWord, constVal());
426- Gen.popVar(a, sz);
427- end;
428-end;
429-
430-proc retStmt(b: INT);
431-var i: INT;
432-begin
433- if curRes = 1 then intExpr(b);
434- elsif curRes = 7 then intExpr(b);
435- elsif curRes = 2 then realExpr(Gen.kF64, b);
436- elsif curRes = 6 then realExpr(Gen.kF32, b);
437- elsif (curRes = 3) or (curRes = 4) then intExpr(b); intExpr(b);
438- elsif curRes = 5 then
439- for i := 0 to 2 do intExpr(b); Gen.resultTo(8 * i, 8); end;
440- elsif curRes = 8 then
441- Gen.pushAdr(pushableAdr());
442- Gen.copyResult(0, 24);
443- end;
444- Gen.returnJump();
445-end;
446-
447-proc stmt(b: INT);
448-var
449- c, n, lo, i, start, saved, sz, tmp: INT; L, E, S, fj, tj: INT; a, a2: Gen.Adr; sy: Scan.Sym; sg: BOOL;
450- mk: I64; f: BOOL;
451-begin
452- mk := Gen.tempMark();
453- if b <= 0 then c := rnd(4); else c := rnd(22); end;
454- match c of
455- | 0, 1, 2, 3: assign(b);
456- | 4:
457- (* if cond then s end *)
458- L := Gen.NoLabel;
459- boolExpr(b);
460- Gen.jumpIf(L, false);
461- stmt(b - 1);
462- Gen.fix(L);
463- | 5:
464- (* while cond do s end *)
465- L := Gen.NoLabel;
466- Gen.alignLoop();
467- start := Chunk.pc;
468- boolExpr(b);
469- Gen.jumpIf(L, false);
470- stmt(b - 1);
471- Gen.jumpBack(start);
472- Gen.fix(L);
473- | 6:
474- (* if a < b then s end, with a jump on the comparison *)
475- L := Gen.NoLabel;
476- intExpr(b); intExpr(b);
477- sy := Cmps[rnd(6)]; sg := flag();
478- if flag() then Gen.jumpCmp(sy, sg, L); else Gen.jumpOut(sy, sg, L); end;
479- stmt(b - 1);
480- Gen.fix(L);
481- | 7:
482- (* v := a < b and c, a condition worked out into a BOOL *)
483- fj := Gen.NoLabel; tj := Gen.NoLabel;
484- intExpr(b); intExpr(b);
485- sy := Cmps[rnd(6)]; sg := flag();
486- Gen.condValue(sy, sg, fj, tj);
487- a := memAdr();
488- Gen.popVar(a, 1);
489- | 8: callExpr(0, b);
490- | 9:
491- (* a match through a jump table *)
492- a := memAdr();
493- if a.base = Gen.bSlot then a.base := Gen.bFrame; a.off := slots[0]; end;
494- intExpr(b);
495- Gen.popVar(a, 8);
496- E := Gen.NoLabel;
497- n := 2 + rnd(4); lo := rnd(5) - 2;
498- if flag() then S := Gen.NoLabel; else S := Chunk.pc; end;
499- start := Gen.jumpTable(a.off, lo, n, S, E);
500- for i := 0 to n - 1 do Gen.tableEntry(start, Chunk.pc + 4 * (n - i)); end;
501- for i := 0 to n - 1 do
502- stmt(b - 1);
503- end;
504- Gen.fix(E);
505- | 10:
506- Gen.pushAdr(pushableAdr()); Gen.pushAdr(pushableAdr());
507- n := 1 + rnd(150); lo := 8 * rnd(3);
508- Gen.copyBlock(n, lo);
509- | 11:
510- Gen.pushAdr(pushableAdr());
511- a := memAdr();
512- if flag() and (numRegs > 1) then
513- a.base := Gen.bReg; a.chunk := regs[0]; a.hi := regs[1]; a.off := 0;
514- end;
515- n := 1 + rnd(150);
516- Gen.copyTo(a, n);
517- | 12:
518- a := memAdr();
519- n := 1 + rnd(100);
520- Gen.zeroVar(a, n);
521- | 13:
522- (* a slice of an array, of a slice, of a pointer *)
523- tmp := INT(Gen.allocTemp(16, 8));
524- n := rnd(3);
525- sz := size(); sg := flag();
526- if n = 0 then
527- a := pushableAdr();
528- Gen.pushAdr(a); intExpr(b); intExpr(b);
529- a := stackAdr(); a.off := 0;
530- f := flag(); n := 10 + rnd(50);
531- Gen.slice(a, f, n, sz, tmp, sg, pos());
532- elsif n = 1 then
533- a := memAdr();
534- if a.base = Gen.bGlobal then a.base := Gen.bFrame; end;
535- intExpr(b); intExpr(b);
536- Gen.slice(a, false, 0, sz, tmp, sg, pos());
537- else
538- intExpr(b); intExpr(b); intExpr(b);
539- Gen.slicePtr(sz, tmp, sg, pos());
540- end;
541- | 14:
542- a.off := slot(); a2.off := slot(); sz := size(); f := flag();
543- Gen.copySlice(a.off, a2.off, sz, f, pos());
544- | 15:
545- n := rnd(4); sz := size(); sg := flag();
546- if n = 0 then
547- Gen.pushAdr(pushableAdr()); intExpr(b);
548- f := flag();
549- Gen.incDec(sz, sg, f);
550- elsif (n = 1) and (numRegs > 0) then
551- intExpr(b);
552- Gen.incDecReg(regs[0], sz, sg, flag());
553- elsif n = 2 then
554- intExpr(b);
555- n := 3 + rnd(6); lo := FirstGlob + rnd(NumGlobs);
556- Gen.checkEnum(n, lo, pos());
557- Gen.drop();
558- else
559- intExpr(b);
560- n := rnd(8000);
561- Gen.checkNil(n, pos());
562- Gen.drop();
563- end;
564- | 16:
565- n := rnd(3);
566- if n = 0 then
567- a.off := slot(); a2.off := slot(); n := rnd(4); f := flag();
568- Gen.compareSeq(a.off, a2.off, n, f);
569- Gen.drop();
570- elsif n = 1 then
571- intExpr(b);
572- Gen.errorText(Gen.allocTemp(16, 8));
573- else
574- intExpr(b);
575- n := 1 + rnd(200);
576- Gen.zeroNew(n);
577- Gen.drop();
578- end;
579- | 17:
580- n := rnd(3);
581- if n = 0 then
582- intExpr(b); intExpr(b); intExpr(b);
583- Gen.atomic(Sym.bCas);
584- elsif n = 1 then
585- intExpr(b); intExpr(b);
586- Gen.atomic(Sym.bXchg);
587- else
588- intExpr(b); intExpr(b);
589- Gen.atomic(Sym.bXadd);
590- end;
591- Gen.drop();
592- | 18:
593- n := rnd(7);
594- for i := 1 to n do intExpr(b); end;
595- Gen.sysCall(n);
596- Gen.drop();
597- if flag() then Gen.fence(); end;
598- | 19:
599- (* defer s *)
600- L := Gen.NoLabel;
601- start, saved := Gen.deferBegin(L);
602- stmt(b - 1);
603- Gen.deferEnd(L, saved);
604- Gen.runDefer(start);
605- | 20:
606- if curRes # 0 then retStmt(b); else assign(b); end;
607- | else:
608- if curRes # 0 then
609- Gen.tryAlign();
610- Gen.tryReturn(slot());
611- else
612- assign(b);
613- end;
614- end;
615- Gen.releaseTemps(mk);
616-end;
617-
618-(* Each statement may be preceded by a few that are made and taken back,
619- as the parser does when it compiles a body a second time *)
620-proc genProc(c: INT);
621-var
622- sig: ^Sym.Type; params, p, last: ^Sym.Obj; i, n, kind, mask, j, ns, line: INT; t: ^Sym.Type;
623- mk: Gen.CodeMark; open: BOOL;
624-begin
625- sig := Sym.newType(Sym.fProc, 8, 8);
626- curRes := rnd(9);
627- sig^.base := results[curRes];
628- params := nil; last := nil;
629- n := rnd(8);
630- for i := 0 to n - 1 do
631- kind := rnd(5);
632- if kind = 0 then t := Sym.tReal;
633- elsif kind = 1 then t := sliceT;
634- elsif kind = 2 then t := Sym.tI32;
635- else t := Sym.tInt; end;
636- p := Sym.newObj(Sym.oVar, 0, t);
637- p^.param := true;
638- p^.isVar := kind = 4;
639- if last = nil then params := p; else last^.next := p; end;
640- last := p;
641- end;
642- Gen.beginProc(sig, params);
643- for i := 0 to 5 do slots[i] := Gen.allocPerm(8, 8); end;
644- mask := rnd(32);
645- j := rnd(16);
646- mask := mask | (j shl Gen.XBit);
647- if rnd(3) = 0 then mask := 0; end;
648- numRegs := 0; numX := 0;
649- for j := 0 to 4 do
650- if (mask & (1 shl j)) # 0 then regs[numRegs] := Gen.VarRegs[j]; INC(numRegs); end;
651- end;
652- for j := 0 to 3 do
653- if (mask & (1 shl (Gen.XBit + j))) # 0 then
654- xregs[numX] := Gen.XVarRegs[j]; INC(numX);
655- Gen.xHome(Gen.XVarRegs[j], Gen.allocPerm(8, 8));
656- end;
657- end;
658- (* some parameters live in registers: a register variable's, or kept
659- where they arrived *)
660- j := 0;
661- p := params;
662- while p # nil do
663- if (p^.typ = Sym.tInt) and (not p^.isVar) and (j < numRegs) and flag() then
664- p^.reg := regs[j]; INC(j);
665- elsif (p^.typ = Sym.tReal) and (numX > 0) and flag() then
666- p^.reg := xregs[0];
667- elsif flag() then
668- Gen.keepArrived(p);
669- end;
670- p := p^.next;
671- end;
672- Gen.useRegs(mask);
673- line := 1 + rnd(40);
674- Gen.enterBody(c, line);
675- Gen.markCode(mk);
676- (* a body made and taken back *)
677- if flag() then
678- stmt(2);
679- Gen.rewind(mk);
680- Gen.redo(mk); (* the jumps to the exit went with the code *)
681- end;
682- ns := 2 + rnd(8);
683- for i := 1 to ns do stmt(3); end;
684- open := flag() and (sig^.base # nil);
685- if (sig^.base # nil) and (not open) then retStmt(2); end;
686- _ := Gen.endProc(c, open);
687- Fmt.print("proc {} lost {} regs {} saves {} at {}\n", [Fmt.int(c), Fmt.int(bit(Gen.lost)), Fmt.int(mask),
688- Fmt.int(Chunk.chunks[c].saveMask), Fmt.int(Chunk.chunks[c].saveAt)]);
689-end;
690-
691-(* The name p0, p1, ... of chunk i, interned *)
692-proc chunkNameOf(i: INT): INT;
693-var s: [3]U8;
694-begin
695- s[0] := 'p'; s[1] := U8(48 + i div 10); s[2] := U8(48 + i mod 10);
696- return Scan.intern(ADR(s[0]), 3);
697-end;
698-
699-proc main*;
700-var i, c: INT; path: []U8; links: [2]Gen.Link; entry: INT; dyn: BOOL;
701-begin
702- seed := 5;
703- path := "lib/Rt.raz";
704- if LEN(Scan.open(path)) # 0 then Diag.fatal("no file"); end;
705- dyn := ARGC > 1;
706- X.setListing(true);
707- Chunk.setCurFile(Scan.intern(ADR(path[0]), LEN(path)));
708- for i := 0 to NumProcs - 1 do c := Chunk.newChunk(Chunk.secText, -1, chunkNameOf(i)); Chunk.setLive(c); end;
709- for i := 0 to NumGlobs - 1 do
710- c := Chunk.newChunk(Chunk.secBss, -1, chunkNameOf(NumProcs + i));
711- Chunk.setBss(c, 64, 8);
712- end;
713- makeTypes();
714- for i := 0 to NumProcs - 1 do genProc(FirstProc + i); end;
715- links[0].chunk := FirstProc; links[0].into := FirstGlob;
716- links[1].chunk := FirstProc + 1; links[1].into := FirstGlob + 1;
717- entry := Gen.entryPoint(dyn, nil, nil, FirstProc + 2, FirstProc + 3, links, 2);
718- Fmt.print("entry {} pc {} fixups {} lines {} said {}\n", [Fmt.int(entry), Fmt.int(Chunk.pc),
719- Fmt.int(Chunk.numFixups), Fmt.int(Chunk.numLines), Fmt.int(X.saidCount())]);
720- for i := 0 to Chunk.pc - 1 do Out.hex(U64(Chunk.text[i]), 2); end;
721- Out.ln;
722- for i := 0 to Chunk.numFixups - 1 do
723- Fmt.print("F {} {} {}\n", [Fmt.int(Chunk.fixups[i].at), Fmt.int(Chunk.fixups[i].chunk), Fmt.int(Chunk.fixups[i].addend)]);
724- end;
725- for i := 0 to Chunk.numLines - 1 do
726- Fmt.print("L {} {} {} {}\n", [Fmt.int(Chunk.lines[i].at), Fmt.int(Chunk.lines[i].chunk),
727- Fmt.int(Chunk.lines[i].line), Fmt.int(Chunk.lines[i].col)]);
728- end;
729- X.list(-1);
730-end;
731-
732-end GenDump.

self/test/ItemDump.pas deleted +0 -665

@@ -1,665 +0,0 @@
1-{ Drives item with a fixed pseudo-random script of operands and
2- operations, with mistakes among them, and prints what each step gave
3- (the item, or that it failed, whose message goes to standard error),
4- then the bytes, fixups, line notes and listing (raz -S) of the code
5- it made: the seed's side of a test of self/Item.raz, whose
6- ItemDump.raz does and prints the same. The argument, a number,
7- changes the script. A run ends at the 20th error, as a compile does,
8- so several scripts are run. }
9-program itemdump;
10-{$mode objfpc}{$H-}
11-uses diag, scan, sym, chunk, x64, gen, item;
12-
13-const
14- FirstProc = 3;
15- NumProcs = 30;
16- FirstGlob = FirstProc + NumProcs;
17- NumGlobs = 4;
18- Steps = 14;
19- YInt = 0; YI64 = 1; YI32 = 2; YU8 = 3; YU16 = 4; YU32 = 5; YU64 = 6; YBool = 7;
20- YReal = 8; YF32 = 9; YI8 = 10; YEnum = 11; YSet = 12; YPtr = 13; YVptr = 14;
21- YPtrArr = 15; YArr = 16; YArrU8 = 17; YSlice = 18; YBytes = 19; YRec = 20;
22- YPacked = 21; YVariant = 22; YProc0 = 23; YProc1 = 24; YProc2 = 25;
23- YPtrRec = 26; YErr = 27; YVrec = 28; YVarr = 29;
24- NumT = 30;
25- IntTypes: array[0..7] of longint = (YInt, YI64, YI32, YU8, YU16, YU32, YU64, YI8);
26- Ops: array[0..19] of TSym = (sPlus, sMinus, sTimes, sDiv, sMod,
27- sAmp, sBar, sXor, sShl, sShr,
28- sEql, sNeq, sLss, sLeq, sGtr, sGeq,
29- sSlash, sIn, sPlus, sMinus);
30- Cmps: array[0..5] of TSym = (sEql, sNeq, sLss, sLeq, sGtr, sGeq);
31-
32-var
33- Letters: string[9];
34- seed: int64;
35- ty: array[0..NumT - 1] of PType;
36- vars: array[0..NumT - 1] of PObj;
37- procs: array[0..5] of PObj;
38- strs: array[0..2] of PObj;
39- arrConst, typeObj, builtinObj, caseObj: PObj;
40- mod0, mod1: PModule;
41- tuple2, record3, packedR, variantT: PType;
42- results: array[0..8] of PType;
43- curRes: longint;
44- call: TCall;
45- jb: jmp_buf;
46- gK: longint;
47- gX: TItem;
48- gOk: boolean;
49-
50-function Rnd(n: longint): longint;
51-begin
52- seed := (seed * 1103515245 + 12345) and $7FFFFFFF;
53- Rnd := (seed shr 8) mod n;
54-end;
55-
56-function Flag: boolean;
57-begin
58- Flag := Rnd(2) = 0;
59-end;
60-
61-function Bit(f: boolean): longint;
62-begin
63- if f then Bit := 1 else Bit := 0;
64-end;
65-
66-function Pos: TPos;
67-var p: TPos;
68-begin
69- p.f := 0; p.a := Rnd(400); p.b := p.a + 1 + Rnd(12);
70- Pos := p;
71-end;
72-
73-function ConstVal: int64;
74-var x: longint; r: int64;
75-begin
76- x := Rnd(1 shl 30);
77- case Rnd(7) of
78- 0: r := x mod 10;
79- 1: r := -(x mod 100);
80- 2: r := int64(1) shl (x mod 20);
81- 3: r := x;
82- 4: r := int64(x) * 4096 * 4096 * 9 - 7;
83- 5: r := -int64(x) * 8;
84- else r := x mod 1000 - 500;
85- end;
86- ConstVal := r;
87-end;
88-
89-function InternStr(const s: shortstring): longint;
90-begin
91- InternStr := Intern(@s[1], length(s));
92-end;
93-
94-{ A name v00, v01, ... , interned }
95-function NameOf(i: longint): longint;
96-var s: string[3];
97-begin
98- s := 'v' + chr(48 + i div 10) + chr(48 + i mod 10);
99- NameOf := Intern(@s[1], 3);
100-end;
101-
102-function NewObjs(cls: TClass; t: PType; n: longint; step: int64; at: longint): PObj;
103-var first, o, last: PObj; i: longint;
104-begin
105- first := nil; last := nil;
106- for i := 0 to n - 1 do begin
107- o := NewObj(cls, NameOf(at + i), t);
108- o^.val := step * i;
109- if last = nil then first := o else last^.next := o;
110- last := o;
111- end;
112- NewObjs := first;
113-end;
114-
115-function ProcType(res: PType; params: PObj; n: longint): PType;
116-var t: PType;
117-begin
118- t := NewType(fProc, 8, 8);
119- t^.base := res;
120- t^.fields := params;
121- t^.len := n;
122- ProcType := t;
123-end;
124-
125-function Param(t: PType; isVar: boolean; at: longint): PObj;
126-var o: PObj;
127-begin
128- o := NewObj(oVar, NameOf(at), t);
129- o^.param := true;
130- o^.isVar := isVar;
131- Param := o;
132-end;
133-
134-procedure MakeTypes;
135-var t: PType; p, q, r: PObj; i: longint;
136-begin
137- ty[YInt] := tInt; ty[YI64] := tI64; ty[YI32] := tI32; ty[YU8] := tU8;
138- ty[YU16] := tU16; ty[YU32] := tU32; ty[YU64] := tU64; ty[YBool] := tBool;
139- ty[YReal] := tReal; ty[YF32] := tF32; ty[YI8] := tI8; ty[YErr] := tError;
140- ty[YBytes] := tBytes;
141- t := NewType(fEnum, 1, 1); t^.len := 5; ty[YEnum] := t;
142- t := NewType(fSet, 8, 8); t^.len := 5; t^.base := ty[YEnum]; ty[YSet] := t;
143- t := NewType(fPtr, 8, 8); t^.base := tI64; ty[YPtr] := t;
144- t := NewType(fPtr, 8, 8); t^.base := tI64; t^.vol := true; ty[YVptr] := t;
145- t := NewType(fArray, 48, 8); t^.base := tI64; t^.len := 6; ty[YArr] := t;
146- t := NewType(fPtr, 8, 8); t^.base := ty[YArr]; ty[YPtrArr] := t;
147- t := NewType(fPtr, 8, 8); t^.base := ty[YArr]; t^.vol := true; ty[YVarr] := t;
148- t := NewType(fArray, 8, 1); t^.base := tU8; t^.len := 8; ty[YArrU8] := t;
149- t := NewType(fSlice, 16, 8); t^.base := tI64; ty[YSlice] := t;
150- record3 := NewType(fRecord, 24, 8);
151- p := NewObj(oField, NameOf(40), tI64); p^.val := 0;
152- q := NewObj(oField, NameOf(41), tReal); q^.val := 8; p^.next := q;
153- r := NewObj(oField, NameOf(42), tI32); r^.val := 16; q^.next := r;
154- record3^.fields := p;
155- ty[YRec] := record3;
156- t := NewType(fPtr, 8, 8); t^.base := record3; ty[YPtrRec] := t;
157- t := NewType(fPtr, 8, 8); t^.base := record3; t^.vol := true; ty[YVrec] := t;
158- packedR := NewType(fRecord, 53, 1);
159- packedR^.packd := true;
160- p := NewObj(oField, NameOf(43), tU8); p^.val := 0;
161- q := NewObj(oField, NameOf(44), tI32); q^.val := 1; p^.next := q;
162- r := NewObj(oField, NameOf(46), ty[YArr]); r^.val := 5; q^.next := r;
163- packedR^.fields := p;
164- ty[YPacked] := packedR;
165- variantT := NewType(fVariant, 16, 8);
166- ty[YVariant] := variantT;
167- tuple2 := NewType(fRecord, 16, 8);
168- tuple2^.tuple := true; tuple2^.len := 2; tuple2^.fields := NewObjs(oVar, tInt, 2, 8, 45);
169- p := Param(tInt, false, 46); p^.next := Param(tReal, false, 47);
170- ty[YProc0] := ProcType(tInt, p, 2);
171- ty[YProc1] := ProcType(nil, nil, 0);
172- p := Param(tI64, true, 48); p^.next := Param(ty[YSlice], false, 49);
173- ty[YProc2] := ProcType(tuple2, p, 2);
174- results[0] := nil; results[1] := tInt; results[2] := tReal; results[3] := ty[YSlice];
175- results[4] := tuple2; results[5] := record3; results[6] := tF32; results[7] := tI16;
176- results[8] := ty[YBytes];
177- for i := 0 to NumT - 1 do
178- if ty[i] = nil then Fatal('a type is missing');
179-end;
180-
181-procedure MakeObjs;
182-var i, c: longint; o: PObj;
183-begin
184- New(mod0); mod0^.name := InternStr('Zero');
185- New(mod1); mod1^.name := InternStr('Other');
186- curModule := mod0;
187- for i := 0 to 5 do begin
188- o := NewObj(oProc, NameOf(50 + i), ty[YProc0 + i mod 3]);
189- o^.chunk := FirstProc + Rnd(NumProcs);
190- o^.ext := i >= 4;
191- o^.isCode := i = 3;
192- procs[i] := o;
193- end;
194- for i := 0 to 2 do begin
195- o := NewObj(oConst, NameOf(60 + i), tStr);
196- o^.val := 2 + 3 * i;
197- c := NewChunk(secRodata, -1, -1);
198- SetData(c, @Letters[1], o^.val + 1, 1);
199- o^.chunk := c;
200- strs[i] := o;
201- end;
202- arrConst := NewObj(oConst, NameOf(63), ty[YArr]);
203- arrConst^.chunk := NewChunk(secRodata, -1, -1);
204- SetData(arrConst^.chunk, @Letters[1], 8, 8);
205- typeObj := NewObj(oType, NameOf(64), ty[YRec]);
206- builtinObj := NewObj(oBuiltin, NameOf(65), tNone);
207- caseObj := NewObj(oCase, NameOf(66), variantT);
208- caseObj^.val := 3;
209- caseObj^.fields := NewObjs(oField, tInt, 2, 8, 67);
210- caseObj^.fields^.val := 8;
211-end;
212-
213-procedure MakeVars;
214-var i, k: longint; o: PObj; t: PType;
215-begin
216- for i := 0 to NumT - 1 do begin
217- t := ty[i];
218- o := NewObj(oVar, NameOf(i), t);
219- o^.lev := 1;
220- k := Rnd(9);
221- if k = 2 then begin
222- o^.lev := 0; o^.chunk := FirstGlob + Rnd(NumGlobs);
223- end else if k = 3 then begin
224- o^.ind := true; o^.val := AllocPerm(8, 8); o^.off := 8 * Rnd(3);
225- end else if k = 4 then begin
226- if (t^.form in [fInt, fPtr]) and (t^.size = 8) then
227- o^.reg := VarRegs[Rnd(5)]
228- else if t^.form = fReal then
229- o^.reg := XVarRegs[Rnd(4)]
230- else if t^.form = fSlice then begin
231- o^.reg := VarRegs[Rnd(3)]; o^.reg2 := VarRegs[3 + Rnd(2)];
232- end;
233- if o^.reg = 0 then o^.val := AllocPerm(t^.size, 8);
234- end else if k = 5 then begin
235- o^.lev := 0; o^.chunk := FirstGlob + Rnd(NumGlobs); o^.module := mod1;
236- end else if k = 6 then begin
237- o^.lev := 0; o^.chunk := FirstGlob + Rnd(NumGlobs); o^.ext := true;
238- end else
239- o^.val := AllocPerm(t^.size + 8, 8);
240- vars[i] := o;
241- end;
242-end;
243-
244-{ Operands }
245-
246-function IntType: PType;
247-begin
248- IntType := ty[IntTypes[Rnd(8)]];
249-end;
250-
251-procedure VarItem(var x: TItem; t: PType);
252-var i, k: longint;
253-begin
254- k := Rnd(NumT);
255- for i := 0 to NumT - 1 do
256- if ty[i] = t then k := i;
257- FillChar(x, SizeOf(x), 0);
258- x.pos := Pos;
259- MakeItem(x, vars[k]);
260-end;
261-
262-procedure Operand(var x: TItem; t: PType);
263-var k: longint; r: double; v: int64;
264-begin
265- FillChar(x, SizeOf(x), 0);
266- x.pos := Pos;
267- if t = nil then begin
268- case Rnd(14) of
269- 0: MakeConst(x, tConst, ConstVal);
270- 1: MakeConst(x, tConst, ConstVal mod 200);
271- 2: begin t := IntType; v := ConstVal mod 100; MakeConst(x, t, v) end;
272- 3: begin r := (ConstVal mod 1000) / 8.0; MakeReal(x, r) end;
273- 4: MakeConst(x, tBool, Rnd(2));
274- 5: MakeItem(x, strs[Rnd(3)]);
275- 6: MakeConst(x, tNil, 0);
276- 7: MakeItem(x, procs[Rnd(6)]);
277- 8: begin
278- if Rnd(4) = 0 then begin
279- case Rnd(3) of
280- 0: MakeItem(x, typeObj);
281- 1: MakeItem(x, builtinObj);
282- else MakeItem(x, caseObj);
283- end;
284- end else
285- MakeItem(x, arrConst);
286- end;
287- 13: begin MakeItem(x, vars[Rnd(NumT)]); Value(x) end;
288- else VarItem(x, ty[Rnd(NumT)]);
289- end;
290- exit;
291- end;
292- k := Rnd(10);
293- if IsInt(t) then begin
294- if k < 3 then begin MakeConst(x, tConst, ConstVal mod 100); exit end;
295- if k = 3 then begin MakeConst(x, t, ConstVal mod 100); exit end;
296- end else if t^.form = fReal then begin
297- if k < 3 then begin r := (ConstVal mod 1000) / 8.0; MakeReal(x, r); exit end;
298- end else if t^.form = fBool then begin
299- if k < 3 then begin MakeConst(x, tBool, Rnd(2)); exit end;
300- end else if t^.form = fPtr then begin
301- if k < 2 then begin MakeConst(x, tNil, 0); exit end;
302- end else if (t^.form = fSlice) and (t^.base = tU8) then begin
303- if k < 3 then begin MakeItem(x, strs[Rnd(3)]); exit end;
304- end;
305- VarItem(x, t);
306-end;
307-
308-procedure CondItem(var x: TItem);
309-var y: TItem; L: longint; op: TSym; t: PType;
310-begin
311- t := IntType;
312- op := Cmps[Rnd(6)];
313- Operand(x, t);
314- Op1(op, x, L);
315- Operand(y, t);
316- Op2(op, x, y, L);
317-end;
318-
319-procedure Place(var x: TItem);
320-var i, k: longint; f: PObj; y, lo, hi: TItem;
321-begin
322- VarItem(x, ty[Rnd(NumT)]);
323- for i := 1 to 3 do begin
324- if Rnd(3) <> 0 then begin
325- k := Rnd(6);
326- if (k = 0) or (x.typ^.form = fPtr) then
327- Deref(x)
328- else if x.typ^.form = fRecord then begin
329- f := x.typ^.fields;
330- k := Rnd(3);
331- while (k > 0) and (f^.next <> nil) do begin f := f^.next; dec(k) end;
332- Field(x, f);
333- end else if x.typ^.form in [fArray, fSlice, fStr] then begin
334- IndexPrep(x);
335- if k < 4 then begin
336- Operand(y, IntType);
337- Index(x, y);
338- end else begin
339- Operand(lo, IntType);
340- SliceLo(lo);
341- Operand(hi, IntType);
342- Slice(x, lo, hi);
343- end;
344- end;
345- end;
346- end;
347-end;
348-
349-procedure Dump(var x: TItem);
350-var name: shortstring; flags: longint;
351-begin
352- name := '-';
353- if x.typ <> nil then name := TypeName(x.typ);
354- flags := Bit(x.vol) + 2 * Bit(x.isVar) + 4 * Bit(x.odd) + 8 * Bit(x.ro) + 16 * Bit(x.deref);
355- write('I ', ord(x.mode), ' ', name, ' ', ord(x.rel), ' ', Bit(x.relSigned), ' ', x.fj, ' ', x.tj, ' ', x.val);
356- writeln(' ', ord(x.base), ' ', x.chunk, ' ', x.off, ' ', flags, ' depth ', depth, ' pushed ', pushed);
357-end;
358-
359-procedure DoCall(var x: TItem);
360-var f, a: TItem; p: PObj; n: longint;
361-begin
362- FillChar(f, SizeOf(f), 0);
363- f.pos := Pos;
364- if Rnd(5) = 0 then MakeItem(f, vars[YProc0 + Rnd(3)])
365- else MakeItem(f, procs[Rnd(6)]);
366- BeginCall(call, f);
367- p := call.param;
368- n := Rnd(4) - 1;
369- while (p <> nil) or (n > 0) do begin
370- if p <> nil then begin
371- if p^.isVar and (Rnd(2) = 0) then begin
372- VarItem(a, ty[YVptr]);
373- Deref(a);
374- end else if Rnd(6) = 0 then Operand(a, nil)
375- else Operand(a, p^.typ);
376- p := p^.next;
377- end else begin
378- Operand(a, nil);
379- n := n - 1;
380- end;
381- PassArg(call, a);
382- if (p = nil) and (n < 0) then n := 0;
383- if (p <> nil) and (n < 0) and (Rnd(4) = 0) then begin p := nil; n := 0 end;
384- end;
385- EndCall(call, x);
386-end;
387-
388-procedure Binary(var x: TItem);
389-var y: TItem; L, M: longint; op: TSym; t: PType;
390-begin
391- L := NoLabel;
392- M := NoLabel;
393- op := Ops[Rnd(20)];
394- case Rnd(8) of
395- 0, 1: t := IntType;
396- 2: t := ty[YReal + Rnd(2)];
397- 3: t := ty[YBool];
398- 4: t := ty[YEnum + Rnd(2)];
399- else t := ty[Rnd(NumT)];
400- end;
401- if Rnd(6) = 0 then begin
402- if Flag then op := sAnd else op := sOr;
403- CondItem(x);
404- Op1(op, x, L);
405- CondItem(y);
406- end else if op = sIn then begin
407- Operand(x, ty[YEnum]);
408- Op1(op, x, L);
409- Operand(y, ty[YSet]);
410- end else begin
411- Operand(x, t);
412- Op1(op, x, L);
413- if Rnd(5) = 0 then Operand(y, nil) else Operand(y, t);
414- end;
415- Op2(op, x, y, L);
416- if (x.mode = mCond) and (Rnd(3) <> 0) then begin
417- if Flag then CondJump(x, M) else CondJumpTrue(x, M);
418- Fix(M);
419- x.mode := mNone;
420- end;
421-end;
422-
423-procedure Unary(var x: TItem);
424-begin
425- Operand(x, nil);
426- case Rnd(3) of
427- 0: Neg(x);
428- 1: NotOp(x);
429- else Complement(x);
430- end;
431-end;
432-
433-procedure DoMatch(var x: TItem);
434-var p, lo, hi: int64; L: longint;
435-begin
436- L := NoLabel;
437- case Rnd(3) of
438- 0: VarItem(x, ty[YVariant]);
439- 1: VarItem(x, ty[YEnum]);
440- else Operand(x, nil);
441- end;
442- p := MatchBegin(x);
443- MatchTag(p, ConstVal mod 10, L);
444- lo := ConstVal mod 10;
445- hi := ConstVal mod 10 + 10;
446- MatchRange(p, lo, hi, L);
447- MatchRange(p, 3, 3, L);
448- Fix(L);
449-end;
450-
451-procedure DoFor(var x: TItem);
452-var o: PObj; lim: TItem; step: int64; exitL: longint;
453-begin
454- o := vars[IntTypes[Rnd(8)]];
455- step := ConstVal mod 5;
456- if step = 0 then step := 1;
457- if Rnd(2) = 0 then step := -step;
458- FillChar(lim, SizeOf(lim), 0);
459- lim.pos := Pos;
460- MakeConst(lim, o^.typ, ConstVal mod 50);
461- exitL := NoLabel;
462- ForStep(o, step);
463- ForNext(o, lim, step, exitL, pc, pc);
464- Fix(exitL);
465- x := lim;
466-end;
467-
468-procedure DoMisc(var x: TItem);
469-var y: TItem;
470-begin
471- case Rnd(5) of
472- 0: begin
473- Place(x);
474- Address(x);
475- Operand(y, x.typ);
476- IncDec(x, y, Flag);
477- end;
478- 1: begin
479- Place(x);
480- Pin(x);
481- end;
482- 2: begin
483- Place(x);
484- CopyDest(x);
485- Place(y);
486- CopyFrom(x, y);
487- end;
488- 3: begin
489- Operand(x, nil);
490- MakeStr(y);
491- Coerce(y, ty[YBytes]);
492- end;
493- else begin
494- Operand(x, nil);
495- NilTest(x);
496- UsesReals(x.pos);
497- Discard(x);
498- end;
499- end;
500-end;
501-
502-procedure DoTemp(var x: TItem);
503-var a: TItem; c, h, n: longint; f: PObj;
504-begin
505- FillChar(x, SizeOf(x), 0);
506- x.pos := Pos;
507- case Rnd(5) of
508- 0: ZeroTemp(x, ty[YVariant]);
509- 1: begin
510- Construct(x, caseObj);
511- f := caseObj^.fields;
512- Operand(a, f^.typ);
513- SetField(x, f, a);
514- end;
515- 2: begin
516- ZeroTemp(x, ty[YRec]);
517- f := ty[YRec]^.fields;
518- if Flag then f := f^.next;
519- Operand(a, f^.typ);
520- SetField(x, f, a);
521- end;
522- 3: begin
523- Operand(a, nil);
524- h := Rnd(3) - 1;
525- n := Rnd(3) - 1;
526- c := ErrorChunk(a, h, n);
527- MakeConst(x, tError, int64(c) + 1);
528- end;
529- else begin
530- Operand(x, ty[YErr]);
531- Msg(x);
532- end;
533- end;
534-end;
535-
536-procedure DoReturn(var x: TItem);
537-var f: PObj;
538-begin
539- if (curRes = 4) and Flag then begin
540- f := tuple2^.fields;
541- if Flag then f := f^.next;
542- if Flag then begin
543- Operand(x, f^.typ);
544- ReturnField(f, x);
545- exit;
546- end;
547- DoCall(x);
548- ReturnAll(x);
549- exit;
550- end;
551- if Rnd(4) = 0 then begin ReturnNone; exit end;
552- Operand(x, results[curRes]);
553- ReturnValue(x);
554-end;
555-
556-procedure Step(k: longint; var x: TItem);
557-var y: TItem;
558-begin
559- FillChar(x, SizeOf(x), 0);
560- case k of
561- 0: begin Operand(x, nil); Value(x) end;
562- 1: begin Operand(x, nil); Address(x) end;
563- 2: begin Operand(x, nil); Coerce(x, ty[Rnd(NumT)]) end;
564- 3: begin Operand(x, nil); CoerceExact(x, IntType, '') end;
565- 4: begin
566- Place(x);
567- Operand(y, x.typ);
568- Assign(x, y);
569- end;
570- 5: Unary(x);
571- 6: Binary(x);
572- 7: begin Operand(x, nil); Convert(x, ty[Rnd(NumT)]) end;
573- 8: Place(x);
574- 9: DoCall(x);
575- 10: DoMatch(x);
576- 11: DoFor(x);
577- 12: DoMisc(x);
578- 13: DoTemp(x);
579- 14: DoReturn(x);
580- else Binary(x);
581- end;
582-end;
583-
584-{ A step, and what it leaves, each a recovery point as the parser's
585- statements are }
586-procedure RunStep;
587-begin
588- gOk := false;
589- recovery := @jb;
590- if setjmp(jb) = 0 then begin
591- Step(gK, gX);
592- gOk := true;
593- end;
594- recovery := nil;
595-end;
596-
597-procedure RunDiscard;
598-begin
599- recovery := @jb;
600- if setjmp(jb) = 0 then Discard(gX);
601- recovery := nil;
602-end;
603-
604-procedure GenProc(c: longint);
605-var sig: PType; i, line: longint;
606-begin
607- curRes := Rnd(9);
608- sig := ProcType(results[curRes], nil, 0);
609- BeginProc(sig, nil);
610- for i := 0 to 5 do AllocPerm(8, 8);
611- MakeVars;
612- checks := Flag;
613- line := 1 + Rnd(40);
614- EnterBody(c, line);
615- for i := 1 to Steps do begin
616- if errors >= 19 then break;
617- gK := Rnd(17);
618- demoted := false;
619- RunStep;
620- if not gOk then
621- writeln('S ', c, ' ', gK, ' failed')
622- else begin
623- writeln('S ', c, ' ', gK, ' ok');
624- Dump(gX);
625- if (gK < 4) or ((gK >= 5) and (gK <= 9)) then RunDiscard;
626- end;
627- writeln('demoted ', Bit(demoted));
628- ResetStack(0, 0);
629- end;
630- EndProc(c, sig^.base <> nil);
631-end;
632-
633-function ChunkNameOf(i: longint): longint;
634-var s: string;
635-begin
636- s := 'p' + chr(48 + i div 10) + chr(48 + i mod 10);
637- ChunkNameOf := Intern(@s[1], 3);
638-end;
639-
640-var
641- i, c: longint; path: string;
642-begin
643- seed := 5;
644- for i := 1 to length(ParamStr(1)) do seed := seed * 10 + ord(ParamStr(1)[i]) - 48;
645- Letters := 'abcdefgh' + #0;
646- path := 'self/test/ItemDump.txt';
647- if Open(path) <> '' then Fatal('no file');
648- Next;
649- listing := true;
650- curFile := Intern(@path[1], length(path));
651- for i := 0 to NumProcs - 1 do begin c := NewChunk(secText, -1, ChunkNameOf(i)); chunks^[c].live := true end;
652- for i := 0 to NumGlobs - 1 do begin
653- c := NewChunk(secBss, -1, ChunkNameOf(NumProcs + i));
654- SetBss(c, 64, 8);
655- end;
656- MakeTypes;
657- MakeObjs;
658- for i := 0 to NumProcs - 1 do GenProc(FirstProc + i);
659- writeln('pc ', pc, ' fixups ', numFixups, ' lines ', numLines, ' said ', SaidCount);
660- for i := 0 to pc - 1 do write(HexStr(code^[i], 2));
661- writeln;
662- for i := 0 to numFixups - 1 do writeln('F ', fixups^[i].at, ' ', fixups^[i].chunk, ' ', fixups^[i].addend);
663- for i := 0 to numLines - 1 do writeln('L ', lines^[i].at, ' ', lines^[i].chunk, ' ', lines^[i].line, ' ', lines^[i].col);
664- List(-1);
665-end.

self/test/ItemDump.raz deleted +0 -679

@@ -1,679 +0,0 @@
1-(* Drives Item with a fixed pseudo-random script of operands and
2- operations, with mistakes among them, and prints what each step gave
3- (the item, or that it failed, whose message goes to standard error),
4- then the bytes, fixups, line notes and listing (raz -S) of the code
5- it made: self/Item.raz's side of a test against the seed's,
6- ItemDump.pas, which does and prints the same. The argument, a digit,
7- changes the script. A run ends at the 20th error, as a compile does,
8- so several scripts are run. *)
9-module ItemDump;
10-import Out, Fmt, Files, Heap, Diag, Scan, Sym, Chunk, X := X64, Gen, Item;
11-
12-const
13- FirstProc = 3; (* chunks 0 to 2 are Gen's own *)
14- NumProcs = 30;
15- FirstGlob = FirstProc + NumProcs;
16- NumGlobs = 4;
17- Steps = 14;
18- (* the types of the script, by number *)
19- YInt = 0; YI64 = 1; YI32 = 2; YU8 = 3; YU16 = 4; YU32 = 5; YU64 = 6; YBool = 7;
20- YReal = 8; YF32 = 9; YI8 = 10; YEnum = 11; YSet = 12; YPtr = 13; YVptr = 14;
21- YPtrArr = 15; YArr = 16; YArrU8 = 17; YSlice = 18; YBytes = 19; YRec = 20;
22- YPacked = 21; YVariant = 22; YProc0 = 23; YProc1 = 24; YProc2 = 25;
23- YPtrRec = 26; YErr = 27; YVrec = 28; YVarr = 29;
24- NumT = 30;
25- IntTypes: [8]INT = [YInt, YI64, YI32, YU8, YU16, YU32, YU64, YI8];
26- Ops: [20]Scan.Sym = [Scan.sPlus, Scan.sMinus, Scan.sTimes, Scan.sDiv, Scan.sMod,
27- Scan.sAmp, Scan.sBar, Scan.sXor, Scan.sShl, Scan.sShr,
28- Scan.sEql, Scan.sNeq, Scan.sLss, Scan.sLeq, Scan.sGtr, Scan.sGeq,
29- Scan.sSlash, Scan.sIn, Scan.sPlus, Scan.sMinus];
30- Cmps: [6]Scan.Sym = [Scan.sEql, Scan.sNeq, Scan.sLss, Scan.sLeq, Scan.sGtr, Scan.sGeq];
31-
32-var
33- Letters: []U8;
34- seed: I64;
35- ty: [NumT]^Sym.Type;
36- vars: [NumT]^Sym.Obj; (* a variable of each type, placed anew for each procedure *)
37- procs: [6]^Sym.Obj;
38- strs: [3]^Sym.Obj;
39- arrConst, typeObj, builtinObj, caseObj: ^Sym.Obj;
40- mod0, mod1: ^Sym.Module;
41- tuple2, record3, packedR, variantT: ^Sym.Type;
42- results: [9]^Sym.Type;
43- curRes: INT; (* the result of the procedure, an index of results *)
44- call: Gen.CallInfo;
45-
46-proc rnd(n: INT): INT;
47-begin
48- seed := (seed * 1103515245 + 12345) & 7FFFFFFFH;
49- return INT((seed shr 8) mod I64(n));
50-end;
51-
52-proc flag: BOOL;
53-begin
54- return rnd(2) = 0;
55-end;
56-
57-proc bit(f: BOOL): INT;
58-begin
59- if f then return 1; end;
60- return 0;
61-end;
62-
63-proc pos: Diag.Pos;
64-var p: Diag.Pos;
65-begin
66- p.f := 0; p.a := rnd(400); p.b := p.a + 1 + rnd(12);
67- return p;
68-end;
69-
70-proc constVal: I64;
71-var x: INT; r: I64;
72-begin
73- x := rnd(1 shl 30);
74- match rnd(7) of
75- | 0: r := x mod 10;
76- | 1: r := -(x mod 100);
77- | 2: r := I64(1) shl (x mod 20);
78- | 3: r := x;
79- | 4: r := I64(x) * 4096 * 4096 * 9 - 7;
80- | 5: r := -I64(x) * 8;
81- | else: r := x mod 1000 - 500;
82- end;
83- return r;
84-end;
85-
86-(* A name, interned *)
87-proc intern(s: []U8): INT;
88-begin
89- return Scan.intern(ADR(s[0]), LEN(s));
90-end;
91-
92-(* A name v00, v01, ... , interned *)
93-proc nameOf(i: INT): INT;
94-var s: [3]U8;
95-begin
96- s[0] := 'v'; s[1] := U8(48 + i div 10); s[2] := U8(48 + i mod 10);
97- return Scan.intern(ADR(s[0]), 3);
98-end;
99-
100-proc newObjs(cls: Sym.Class; t: ^Sym.Type; n: INT; step: I64; at: INT): ^Sym.Obj;
101-var first, o, last: ^Sym.Obj; i: INT;
102-begin
103- first := nil; last := nil;
104- for i := 0 to n - 1 do
105- o := Sym.newObj(cls, nameOf(at + i), t);
106- o^.val := step * I64(i);
107- if last = nil then first := o; else last^.next := o; end;
108- last := o;
109- end;
110- return first;
111-end;
112-
113-proc newType(form: Sym.Form; size, align: I64): ^Sym.Type;
114-begin
115- return Sym.newType(form, size, align);
116-end;
117-
118-proc procType(res: ^Sym.Type; params: ^Sym.Obj; n: INT): ^Sym.Type;
119-var t: ^Sym.Type;
120-begin
121- t := newType(Sym.fProc, 8, 8);
122- t^.base := res;
123- t^.fields := params;
124- t^.len := n;
125- return t;
126-end;
127-
128-proc param(t: ^Sym.Type; isVar: BOOL; at: INT): ^Sym.Obj;
129-var o: ^Sym.Obj;
130-begin
131- o := Sym.newObj(Sym.oVar, nameOf(at), t);
132- o^.param := true;
133- o^.isVar := isVar;
134- return o;
135-end;
136-
137-proc makeTypes;
138-var t: ^Sym.Type; p, q, r: ^Sym.Obj; i: INT;
139-begin
140- ty[YInt] := Sym.tInt; ty[YI64] := Sym.tI64; ty[YI32] := Sym.tI32; ty[YU8] := Sym.tU8;
141- ty[YU16] := Sym.tU16; ty[YU32] := Sym.tU32; ty[YU64] := Sym.tU64; ty[YBool] := Sym.tBool;
142- ty[YReal] := Sym.tReal; ty[YF32] := Sym.tF32; ty[YI8] := Sym.tI8; ty[YErr] := Sym.tError;
143- ty[YBytes] := Sym.tBytes;
144- t := newType(Sym.fEnum, 1, 1); t^.len := 5; ty[YEnum] := t;
145- t := newType(Sym.fSet, 8, 8); t^.len := 5; t^.base := ty[YEnum]; ty[YSet] := t;
146- t := newType(Sym.fPtr, 8, 8); t^.base := Sym.tI64; ty[YPtr] := t;
147- t := newType(Sym.fPtr, 8, 8); t^.base := Sym.tI64; t^.vol := true; ty[YVptr] := t;
148- t := newType(Sym.fArray, 48, 8); t^.base := Sym.tI64; t^.len := 6; ty[YArr] := t;
149- t := newType(Sym.fPtr, 8, 8); t^.base := ty[YArr]; ty[YPtrArr] := t;
150- t := newType(Sym.fPtr, 8, 8); t^.base := ty[YArr]; t^.vol := true; ty[YVarr] := t;
151- t := newType(Sym.fArray, 8, 1); t^.base := Sym.tU8; t^.len := 8; ty[YArrU8] := t;
152- t := newType(Sym.fSlice, 16, 8); t^.base := Sym.tI64; ty[YSlice] := t;
153- (* a record of an I64, an F64 and an I32 *)
154- record3 := newType(Sym.fRecord, 24, 8);
155- p := Sym.newObj(Sym.oField, nameOf(40), Sym.tI64); p^.val := 0;
156- q := Sym.newObj(Sym.oField, nameOf(41), Sym.tReal); q^.val := 8; p^.next := q;
157- r := Sym.newObj(Sym.oField, nameOf(42), Sym.tI32); r^.val := 16; q^.next := r;
158- record3^.fields := p;
159- ty[YRec] := record3;
160- t := newType(Sym.fPtr, 8, 8); t^.base := record3; ty[YPtrRec] := t;
161- t := newType(Sym.fPtr, 8, 8); t^.base := record3; t^.vol := true; ty[YVrec] := t;
162- (* a packed record: a byte, then an I32 that may be misaligned *)
163- packedR := newType(Sym.fRecord, 53, 1);
164- packedR^.packd := true;
165- p := Sym.newObj(Sym.oField, nameOf(43), Sym.tU8); p^.val := 0;
166- q := Sym.newObj(Sym.oField, nameOf(44), Sym.tI32); q^.val := 1; p^.next := q;
167- r := Sym.newObj(Sym.oField, nameOf(46), ty[YArr]); r^.val := 5; q^.next := r;
168- packedR^.fields := p;
169- ty[YPacked] := packedR;
170- variantT := newType(Sym.fVariant, 16, 8);
171- ty[YVariant] := variantT;
172- tuple2 := newType(Sym.fRecord, 16, 8);
173- tuple2^.tuple := true; tuple2^.len := 2; tuple2^.fields := newObjs(Sym.oVar, Sym.tInt, 2, 8, 45);
174- (* procedures: (I64, F64) I64; (); (var I64, []I64) of two results *)
175- p := param(Sym.tInt, false, 46); p^.next := param(Sym.tReal, false, 47);
176- ty[YProc0] := procType(Sym.tInt, p, 2);
177- ty[YProc1] := procType(nil, nil, 0);
178- p := param(Sym.tI64, true, 48); p^.next := param(ty[YSlice], false, 49);
179- ty[YProc2] := procType(tuple2, p, 2);
180- results[0] := nil; results[1] := Sym.tInt; results[2] := Sym.tReal; results[3] := ty[YSlice];
181- results[4] := tuple2; results[5] := record3; results[6] := Sym.tF32; results[7] := Sym.tI16;
182- results[8] := ty[YBytes];
183- for i := 0 to NumT - 1 do
184- if ty[i] = nil then Diag.fatal("a type is missing"); end;
185- end;
186-end;
187-
188-(* The objects named by the script: procedures, strings, constants of
189- an array, a type, a built-in, a case of a variant *)
190-proc makeObjs;
191-var i, c: INT; o: ^Sym.Obj;
192-begin
193- NEW(mod0, Heap.heap); mod0^.name := intern("Zero");
194- NEW(mod1, Heap.heap); mod1^.name := intern("Other");
195- Sym.setCurModule(mod0);
196- for i := 0 to 5 do
197- o := Sym.newObj(Sym.oProc, nameOf(50 + i), ty[YProc0 + i mod 3]);
198- o^.chunk := FirstProc + rnd(NumProcs);
199- o^.ext := i >= 4;
200- o^.isCode := i = 3;
201- procs[i] := o;
202- end;
203- for i := 0 to 2 do
204- o := Sym.newObj(Sym.oConst, nameOf(60 + i), Sym.tStr);
205- o^.val := 2 + 3 * i;
206- c := Chunk.newChunk(Chunk.secRodata, -1, -1);
207- Chunk.setData(c, ADR(Letters[0]), INT(o^.val) + 1, 1);
208- o^.chunk := c;
209- strs[i] := o;
210- end;
211- arrConst := Sym.newObj(Sym.oConst, nameOf(63), ty[YArr]);
212- arrConst^.chunk := Chunk.newChunk(Chunk.secRodata, -1, -1);
213- Chunk.setData(arrConst^.chunk, ADR(Letters[0]), 8, 8);
214- typeObj := Sym.newObj(Sym.oType, nameOf(64), ty[YRec]);
215- builtinObj := Sym.newObj(Sym.oBuiltin, nameOf(65), Sym.tNone);
216- caseObj := Sym.newObj(Sym.oCase, nameOf(66), variantT);
217- caseObj^.val := 3;
218- caseObj^.fields := newObjs(Sym.oField, Sym.tInt, 2, 8, 67);
219- caseObj^.fields^.val := 8;
220-end;
221-
222-(* The variable of each type, in the frame, a chunk, a slot, a register,
223- another module or C's, as the procedure compiled has them *)
224-proc makeVars;
225-var i, k: INT; o: ^Sym.Obj; t: ^Sym.Type;
226-begin
227- for i := 0 to NumT - 1 do
228- t := ty[i];
229- o := Sym.newObj(Sym.oVar, nameOf(i), t);
230- o^.lev := 1;
231- k := rnd(9);
232- if k = 2 then
233- o^.lev := 0; o^.chunk := FirstGlob + rnd(NumGlobs);
234- elsif k = 3 then
235- o^.ind := true; o^.val := Gen.allocPerm(8, 8); o^.off := 8 * rnd(3);
236- elsif k = 4 then
237- if (t^.form in {Sym.fInt, Sym.fPtr}) and (t^.size = 8) then
238- o^.reg := Gen.VarRegs[rnd(5)];
239- elsif t^.form = Sym.fReal then
240- o^.reg := Gen.XVarRegs[rnd(4)];
241- elsif t^.form = Sym.fSlice then
242- o^.reg := Gen.VarRegs[rnd(3)]; o^.reg2 := Gen.VarRegs[3 + rnd(2)];
243- end;
244- if o^.reg = 0 then o^.val := Gen.allocPerm(t^.size, 8); end;
245- elsif k = 5 then
246- o^.lev := 0; o^.chunk := FirstGlob + rnd(NumGlobs); o^.home := mod1;
247- elsif k = 6 then
248- o^.lev := 0; o^.chunk := FirstGlob + rnd(NumGlobs); o^.ext := true;
249- else
250- o^.val := Gen.allocPerm(t^.size + 8, 8);
251- end;
252- vars[i] := o;
253- end;
254-end;
255-
256-(* Operands *)
257-
258-proc intType: ^Sym.Type;
259-begin
260- return ty[IntTypes[rnd(8)]];
261-end;
262-
263-proc varItem(var x: Item.Item; t: ^Sym.Type): ERROR;
264-var i, k: INT;
265-begin
266- k := rnd(NumT);
267- for i := 0 to NumT - 1 do
268- if ty[i] = t then k := i; end;
269- end;
270- x := {};
271- x.pos := pos();
272- return Item.makeItem(x, vars[k]);
273-end;
274-
275-(* An operand of type t, or of any if t is nil *)
276-proc operand(var x: Item.Item; t: ^Sym.Type): ERROR;
277-var k: INT; r: F64; v: I64;
278-begin
279- x := {};
280- x.pos := pos();
281- if t = nil then
282- match rnd(14) of
283- | 0: Item.makeConst(x, Sym.tConst, constVal());
284- | 1: Item.makeConst(x, Sym.tConst, constVal() mod 200);
285- | 2: t := intType(); v := constVal() mod 100; Item.makeConst(x, t, v);
286- | 3: r := F64(constVal() mod 1000) / 8.0; Item.makeReal(x, r);
287- | 4: Item.makeConst(x, Sym.tBool, I64(rnd(2)));
288- | 5: return Item.makeItem(x, strs[rnd(3)]);
289- | 6: Item.makeConst(x, Sym.tNil, 0);
290- | 7: return Item.makeItem(x, procs[rnd(6)]);
291- | 8: if rnd(4) = 0 then
292- match rnd(3) of
293- | 0: return Item.makeItem(x, typeObj);
294- | 1: return Item.makeItem(x, builtinObj);
295- | else: return Item.makeItem(x, caseObj);
296- end;
297- end;
298- return Item.makeItem(x, arrConst);
299- | 13: try Item.makeItem(x, vars[rnd(NumT)]); return Item.value(x);
300- | else: return varItem(x, ty[rnd(NumT)]);
301- end;
302- return nil;
303- end;
304- k := rnd(10);
305- if Sym.isInt(t) then
306- if k < 3 then Item.makeConst(x, Sym.tConst, constVal() mod 100); return nil; end;
307- if k = 3 then Item.makeConst(x, t, constVal() mod 100); return nil; end;
308- elsif t^.form = Sym.fReal then
309- if k < 3 then r := F64(constVal() mod 1000) / 8.0; Item.makeReal(x, r); return nil; end;
310- elsif t^.form = Sym.fBool then
311- if k < 3 then Item.makeConst(x, Sym.tBool, I64(rnd(2))); return nil; end;
312- elsif t^.form = Sym.fPtr then
313- if k < 2 then Item.makeConst(x, Sym.tNil, 0); return nil; end;
314- elsif (t^.form = Sym.fSlice) and (t^.base = Sym.tU8) then
315- if k < 3 then return Item.makeItem(x, strs[rnd(3)]); end;
316- end;
317- return varItem(x, t);
318-end;
319-
320-(* A condition, left as one: a comparison of two integers *)
321-proc condItem(var x: Item.Item): ERROR;
322-var y: Item.Item; L: INT; op: Scan.Sym; t: ^Sym.Type;
323-begin
324- t := intType();
325- op := Cmps[rnd(6)];
326- try operand(x, t);
327- try Item.op1(op, x, L);
328- try operand(y, t);
329- return Item.op2(op, x, y, L);
330-end;
331-
332-(* A variable, or part of one: through a pointer, a field, an element, a slice *)
333-proc place(var x: Item.Item): ERROR;
334-var i, k: INT; f: ^Sym.Obj; y, lo, hi: Item.Item;
335-begin
336- try varItem(x, ty[rnd(NumT)]);
337- for i := 1 to 3 do
338- if rnd(3) # 0 then
339- k := rnd(6);
340- if (k = 0) or (x.typ^.form = Sym.fPtr) then
341- try Item.deref(x);
342- elsif x.typ^.form = Sym.fRecord then
343- f := x.typ^.fields;
344- k := rnd(3);
345- while (k > 0) and (f^.next # nil) do f := f^.next; DEC(k); end;
346- try Item.field(x, f);
347- elsif (x.typ^.form in {Sym.fArray, Sym.fSlice, Sym.fStr}) then
348- try Item.indexPrep(x);
349- if k < 4 then
350- try operand(y, intType());
351- try Item.index(x, y);
352- else
353- try operand(lo, intType());
354- try Item.sliceLo(lo);
355- try operand(hi, intType());
356- try Item.slice(x, lo, hi);
357- end;
358- end;
359- end;
360- end;
361- return nil;
362-end;
363-
364-(* The state of an item *)
365-proc dump(var x: Item.Item);
366-var name: []U8; flags: INT;
367-begin
368- name := "-";
369- if x.typ # nil then name := Sym.typeName(x.typ); end;
370- flags := bit(x.vol) + 2 * bit(x.isVar) + 4 * bit(x.odd) + 8 * bit(x.ro) + 16 * bit(x.deref);
371- Fmt.print("I {} {} {} {} {} {} {}", [Fmt.int(INT(x.mode)), Fmt.str(name), Fmt.int(INT(x.rel)),
372- Fmt.int(bit(x.relSigned)), Fmt.int(x.fj), Fmt.int(x.tj), Fmt.int(x.val)]);
373- Fmt.print(" {} {} {} {} depth {} pushed {}\n", [Fmt.int(INT(x.base)), Fmt.int(x.chunk), Fmt.int(x.off),
374- Fmt.int(flags), Fmt.int(Gen.depth), Fmt.int(Gen.pushed)]);
375-end;
376-
377-(* A call: of a procedure of the script or a variable of a procedure
378- type, with arguments that mostly fit its parameters *)
379-proc doCall(var x: Item.Item): ERROR;
380-var f, a: Item.Item; p: ^Sym.Obj; n: INT;
381-begin
382- f := {};
383- f.pos := pos();
384- if rnd(5) = 0 then try Item.makeItem(f, vars[YProc0 + rnd(3)]);
385- else try Item.makeItem(f, procs[rnd(6)]); end;
386- try Item.beginCall(call, f);
387- p := call.param;
388- n := rnd(4) - 1;
389- while (p # nil) or (n > 0) do
390- if p # nil then
391- if p^.isVar and (rnd(2) = 0) then
392- try varItem(a, ty[YVptr]);
393- try Item.deref(a);
394- elsif rnd(6) = 0 then try operand(a, nil);
395- else try operand(a, p^.typ); end;
396- p := p^.next;
397- else
398- try operand(a, nil);
399- n := n - 1;
400- end;
401- try Item.passArg(call, a);
402- if (p = nil) and (n < 0) then n := 0; end;
403- if (p # nil) and (n < 0) and (rnd(4) = 0) then p := nil; n := 0; end;
404- end;
405- return Item.endCall(call, x);
406-end;
407-
408-(* A binary operation, with a condition's jumps made after it, sometimes *)
409-proc binary(var x: Item.Item): ERROR;
410-var y: Item.Item; L, M: INT; op: Scan.Sym; t: ^Sym.Type;
411-begin
412- L := Gen.NoLabel;
413- M := Gen.NoLabel;
414- op := Ops[rnd(20)];
415- match rnd(8) of
416- | 0, 1: t := intType();
417- | 2: t := ty[YReal + rnd(2)];
418- | 3: t := ty[YBool];
419- | 4: t := ty[YEnum + rnd(2)];
420- | else: t := ty[rnd(NumT)];
421- end;
422- if rnd(6) = 0 then
423- (* and, or *)
424- if flag() then op := Scan.sAnd; else op := Scan.sOr; end;
425- try condItem(x);
426- try Item.op1(op, x, L);
427- try condItem(y);
428- elsif op = Scan.sIn then
429- try operand(x, ty[YEnum]);
430- try Item.op1(op, x, L);
431- try operand(y, ty[YSet]);
432- else
433- try operand(x, t);
434- try Item.op1(op, x, L);
435- if rnd(5) = 0 then try operand(y, nil); else try operand(y, t); end;
436- end;
437- try Item.op2(op, x, y, L);
438- if (x.mode = Item.mCond) and (rnd(3) # 0) then
439- if flag() then try Item.condJump(x, M); else try Item.condJumpTrue(x, M); end;
440- Gen.fix(M);
441- x.mode := Item.mNone; (* its values are used *)
442- end;
443- return nil;
444-end;
445-
446-proc unary(var x: Item.Item): ERROR;
447-begin
448- try operand(x, nil);
449- match rnd(3) of
450- | 0: return Item.neg(x);
451- | 1: return Item.notOp(x);
452- | else: return Item.complement(x);
453- end;
454-end;
455-
456-(* match: the slot of a variant, an enumeration or an integer, and
457- tests of it *)
458-proc doMatch(var x: Item.Item): ERROR;
459-var p, lo, hi: I64; L: INT;
460-begin
461- L := Gen.NoLabel;
462- match rnd(3) of
463- | 0: try varItem(x, ty[YVariant]);
464- | 1: try varItem(x, ty[YEnum]);
465- | else: try operand(x, nil);
466- end;
467- p := try Item.matchBegin(x);
468- Item.matchTag(p, constVal() mod 10, L);
469- lo := constVal() mod 10;
470- hi := constVal() mod 10 + 10;
471- Item.matchRange(p, lo, hi, L);
472- Item.matchRange(p, 3, 3, L);
473- Gen.fix(L);
474- return nil;
475-end;
476-
477-(* A for loop's variable stepped and tested *)
478-proc doFor(var x: Item.Item): ERROR;
479-var o: ^Sym.Obj; lim: Item.Item; step: I64; exitL: INT;
480-begin
481- o := vars[IntTypes[rnd(8)]];
482- step := constVal() mod 5;
483- if step = 0 then step := 1; end;
484- if rnd(2) = 0 then step := -step; end;
485- lim := {};
486- lim.pos := pos();
487- Item.makeConst(lim, o^.typ, constVal() mod 50);
488- exitL := Gen.NoLabel;
489- try Item.forStep(o, step);
490- try Item.forNext(o, lim, step, exitL, Chunk.pc, Chunk.pc);
491- Gen.fix(exitL);
492- x := lim;
493- return nil;
494-end;
495-
496-(* INC and DEC, pin, COPY *)
497-proc doMisc(var x: Item.Item): ERROR;
498-var y: Item.Item;
499-begin
500- match rnd(5) of
501- | 0:
502- try place(x);
503- try Item.address(x);
504- try operand(y, x.typ);
505- return Item.incDec(x, y, flag());
506- | 1:
507- try place(x);
508- return Item.pin(x);
509- | 2:
510- try place(x);
511- try Item.copyDest(x);
512- try place(y);
513- return Item.copyFrom(x, y);
514- | 3:
515- try operand(x, nil);
516- Item.makeStr(y);
517- return Item.coerce(y, ty[YBytes]);
518- | else:
519- try operand(x, nil);
520- Item.nilTest(x);
521- Item.usesReals(x.pos);
522- return Item.discard(x);
523- end;
524-end;
525-
526-(* A variant, a record's fields, an error's chunk, the message of one *)
527-proc doTemp(var x: Item.Item): ERROR;
528-var a: Item.Item; c, h, n: INT; f: ^Sym.Obj;
529-begin
530- x := {};
531- x.pos := pos();
532- match rnd(5) of
533- | 0: Item.zeroTemp(x, ty[YVariant]);
534- | 1:
535- Item.construct(x, caseObj);
536- f := caseObj^.fields;
537- try operand(a, f^.typ);
538- return Item.setField(x, f, a);
539- | 2:
540- Item.zeroTemp(x, ty[YRec]);
541- f := ty[YRec]^.fields;
542- if flag() then f := f^.next; end;
543- try operand(a, f^.typ);
544- return Item.setField(x, f, a);
545- | 3:
546- try operand(a, nil);
547- h := rnd(3) - 1;
548- n := rnd(3) - 1;
549- c := try Item.errorChunk(a, h, n);
550- Item.makeConst(x, Sym.tError, I64(c) + 1);
551- return nil;
552- | else:
553- try operand(x, ty[YErr]);
554- return Item.msg(x);
555- end;
556- return nil;
557-end;
558-
559-proc doReturn(var x: Item.Item): ERROR;
560-var f: ^Sym.Obj;
561-begin
562- if (curRes = 4) and flag() then
563- (* several results *)
564- f := tuple2^.fields;
565- if flag() then f := f^.next; end;
566- if flag() then
567- try operand(x, f^.typ);
568- return Item.returnField(f, x);
569- end;
570- try doCall(x);
571- return Item.returnAll(x);
572- end;
573- if rnd(4) = 0 then return Item.returnNone(); end;
574- try operand(x, results[curRes]);
575- return Item.returnValue(x);
576-end;
577-
578-(* One step of the script, whose item is x *)
579-proc step(k: INT; var x: Item.Item): ERROR;
580-var y: Item.Item;
581-begin
582- x := {};
583- match k of
584- | 0: try operand(x, nil); return Item.value(x);
585- | 1: try operand(x, nil); return Item.address(x);
586- | 2: try operand(x, nil); return Item.coerce(x, ty[rnd(NumT)]);
587- | 3: try operand(x, nil); return Item.coerceExact(x, intType(), "");
588- | 4:
589- try place(x);
590- try operand(y, x.typ);
591- return Item.assign(x, y);
592- | 5: return unary(x);
593- | 6: return binary(x);
594- | 7: try operand(x, nil); return Item.convert(x, ty[rnd(NumT)]);
595- | 8: return place(x);
596- | 9: return doCall(x);
597- | 10: return doMatch(x);
598- | 11: return doFor(x);
599- | 12: return doMisc(x);
600- | 13: return doTemp(x);
601- | 14: return doReturn(x);
602- | else: return binary(x);
603- end;
604-end;
605-
606-(* One procedure of Steps steps *)
607-proc genProc(c: INT);
608-var
609- sig: ^Sym.Type; i, k, line: INT; x: Item.Item; err: ERROR;
610-begin
611- curRes := rnd(9);
612- sig := procType(results[curRes], nil, 0);
613- Item.beginProc(sig, nil);
614- for i := 0 to 5 do _ := Gen.allocPerm(8, 8); end;
615- makeVars();
616- Item.setChecks(flag());
617- line := 1 + rnd(40);
618- Gen.enterBody(c, line);
619- for i := 1 to Steps do
620- if Diag.errors >= 19 then break; end; (* the 20th would end the run *)
621- k := rnd(17);
622- Item.setDemoted(false);
623- err := step(k, x);
624- if err # nil then
625- Fmt.print("S {} {} failed\n", [Fmt.int(c), Fmt.int(k)]);
626- else
627- Fmt.print("S {} {} ok\n", [Fmt.int(c), Fmt.int(k)]);
628- dump(x);
629- (* the items of these steps are as an operand is, on the stack *)
630- if (k < 4) or ((k >= 5) and (k <= 9)) then _ := Item.discard(x); end;
631- end;
632- Fmt.print("demoted {}\n", [Fmt.int(bit(Item.demoted))]);
633- Gen.resetStack(0, 0);
634- end;
635- _ := Gen.endProc(c, sig^.base # nil);
636-end;
637-
638-proc chunkNameOf(i: INT): INT;
639-var s: [3]U8;
640-begin
641- s[0] := 'p'; s[1] := U8(48 + i div 10); s[2] := U8(48 + i mod 10);
642- return Scan.intern(ADR(s[0]), 3);
643-end;
644-
645-proc main*;
646-var i, c: INT; path: []U8; arg: []U8;
647-begin
648- arg := Files.arg(1);
649- seed := 5;
650- for i := 0 to LEN(arg) - 1 do seed := seed * 10 + I64(arg[i]) - 48; end;
651- Letters := "abcdefgh\0";
652- path := "self/test/ItemDump.txt";
653- if LEN(Scan.open(path)) # 0 then Diag.fatal("no file"); end;
654- Scan.next; (* the string the file starts with *)
655- X.setListing(true);
656- Chunk.setCurFile(Scan.intern(ADR(path[0]), LEN(path)));
657- for i := 0 to NumProcs - 1 do c := Chunk.newChunk(Chunk.secText, -1, chunkNameOf(i)); Chunk.setLive(c); end;
658- for i := 0 to NumGlobs - 1 do
659- c := Chunk.newChunk(Chunk.secBss, -1, chunkNameOf(NumProcs + i));
660- Chunk.setBss(c, 64, 8);
661- end;
662- makeTypes();
663- makeObjs();
664- for i := 0 to NumProcs - 1 do genProc(FirstProc + i); end;
665- Fmt.print("pc {} fixups {} lines {} said {}\n", [Fmt.int(Chunk.pc),
666- Fmt.int(Chunk.numFixups), Fmt.int(Chunk.numLines), Fmt.int(X.saidCount())]);
667- for i := 0 to Chunk.pc - 1 do Out.hex(U64(Chunk.text[i]), 2); end;
668- Out.ln;
669- for i := 0 to Chunk.numFixups - 1 do
670- Fmt.print("F {} {} {}\n", [Fmt.int(Chunk.fixups[i].at), Fmt.int(Chunk.fixups[i].chunk), Fmt.int(Chunk.fixups[i].addend)]);
671- end;
672- for i := 0 to Chunk.numLines - 1 do
673- Fmt.print("L {} {} {} {}\n", [Fmt.int(Chunk.lines[i].at), Fmt.int(Chunk.lines[i].chunk),
674- Fmt.int(Chunk.lines[i].line), Fmt.int(Chunk.lines[i].col)]);
675- end;
676- X.list(-1);
677-end;
678-
679-end ItemDump.

self/test/ItemDump.txt deleted +0 -41

@@ -1,41 +0,0 @@
1-"item test"
2- x value sum alpha beta;
3- next beta items len alpha next count alpha beta;
4- value beta count beta next value;
5- len beta count;
6- sum len alpha len len value alpha count;
7- next x n;
8- x next beta len n next;
9- sum x beta len len sum count items beta;
10- tmp beta len alpha len count p;
11- next value items p len p items n;
12- x tmp count beta;
13- n next p items tmp p n;
14- beta beta next value x items x;
15- value alpha sum beta next len;
16- items items tmp items len p len p beta;
17- beta n p tmp sum beta alpha tmp tmp;
18- sum len sum p n;
19- value sum items alpha p items x len;
20- p alpha count;
21- n x tmp count value value p beta x;
22- value next n x value next;
23- tmp value items sum value;
24- x beta x x;
25- sum count alpha p;
26- len x n n alpha x value next items;
27- len items x tmp next len sum;
28- tmp alpha p sum next value value value;
29- beta p sum value alpha count;
30- count p x;
31- items len alpha;
32- alpha len x;
33- beta items len alpha beta count len;
34- x sum n items len items;
35- beta beta p p p p;
36- beta x beta tmp items;
37- n p tmp x next alpha count next;
38- x tmp next alpha next;
39- sum beta tmp n next;
40- x items count next next;
41- next items sum count len count count value tmp;

self/test/LinkDump.pas deleted +0 -91

@@ -1,91 +0,0 @@
1-{ Makes a program of chunks by a fixed pseudo-random script, links it and
2- writes it as an executable to the file of the second argument, in the
3- way the first says (0 static, 1 dynamic, 2 stripped): the seed's side
4- of a test of self/Link.raz and self/Elf.raz, whose LinkDump.raz does
5- the same and writes the same file. }
6-program linkdump;
7-{$mode objfpc}{$H-}
8-uses diag, scan, chunk, link, elf;
9-const NumC = 200;
10-var
11- seed: int64;
12- names: array[0..7] of longint;
13- i, j, k, kind, n, x, y, z, mode: longint;
14- b: array[0..63] of byte;
15-
16-function Rnd(n: longint): longint;
17-begin
18- seed := (seed * 1103515245 + 12345) and $7FFFFFFF;
19- Rnd := (seed shr 8) mod n;
20-end;
21-
22-var c, e, line, col: longint;
23-begin
24- seed := 5;
25- mode := ord(ParamStr(1)[1]) - 48;
26- for i := 0 to 7 do begin b[0] := 97 + i; names[i] := Intern(@b[0], 1) end;
27- placesChunk := NewChunk(secRodata, -1, -1);
28- SetData(placesChunk, @b[0], 0, 8);
29- for i := 0 to NumC - 1 do begin
30- if i = 0 then kind := 0 else kind := Rnd(10);
31- x := Rnd(4); y := Rnd(8);
32- case kind of
33- 0..5: begin
34- c := NewChunk(secText, x - 1, y);
35- BeginChunk(c);
36- z := Rnd(3); curFile := names[z];
37- line := Rnd(300); col := Rnd(60);
38- NoteLine(line, col);
39- if i = 0 then begin AddFixup(pc, placesChunk, 0); Put4(0) end;
40- n := 2 + Rnd(10);
41- for j := 1 to n do begin
42- z := Rnd(5);
43- if z <= 1 then begin
44- e := Rnd(NumC); y := Rnd(8);
45- AddFixup(pc, e, y);
46- Put4(0);
47- end else if z = 2 then begin
48- z := Rnd(3); curFile := names[z];
49- line := Rnd(300); col := Rnd(60);
50- NoteLine(line, col);
51- end else begin x := Rnd(1 shl 30); Put4(x); x := Rnd(256); Put1(x) end;
52- end;
53- EndChunk(c);
54- n := Rnd(3);
55- for j := 1 to n do begin
56- x := Rnd(8); y := Rnd(200); z := Rnd(6);
57- NoteVar(c, names[x], y - 100, z);
58- end;
59- end;
60- 6, 7: begin
61- c := NewChunk(secRodata, x - 1, y);
62- n := 8 * (1 + Rnd(4));
63- for j := 0 to n - 1 do b[j] := Rnd(256);
64- SetData(c, @b[0], n, 8);
65- for j := 0 to n div 8 - 1 do begin
66- z := Rnd(2);
67- if z = 0 then begin e := Rnd(NumC); y := Rnd(8); AddDataFixup(c, j * 8, e, y) end;
68- end;
69- end;
70- 8: begin
71- c := NewChunk(secBss, x - 1, y);
72- z := Rnd(200); e := Rnd(4);
73- SetBss(c, 1 + z, 1 shl e);
74- end;
75- 9: begin z := Rnd(8); c := ExternChunk(names[z]) end;
76- end;
77- end;
78- { every chunk a fixup names must exist, and be defined if it is reached }
79- while numChunks < NumC do begin c := NewChunk(secBss, -1, -1); SetBss(c, 8, 8) end;
80- for i := 0 to numChunks - 1 do
81- if chunks^[i].size < 0 then SetBss(i, 8, 8);
82- mainPath := 'some/main.raz';
83- if mode = 1 then begin
84- numNeeded := 2;
85- needed[0] := names[0]; needed[1] := names[1];
86- end;
87- stripped := mode = 2;
88- if mode = 2 then placesChunk := -1;
89- MarkLive(1);
90- WriteElf(ParamStr(2), 1);
91-end.

self/test/LinkDump.raz deleted +0 -103

@@ -1,103 +0,0 @@
1-(* Makes a program of chunks by a fixed pseudo-random script, links it
2- and writes it as an executable to the file of the second argument,
3- in the way the first says (0 static, 1 dynamic, 2 stripped):
4- self/Link.raz's and self/Elf.raz's side of a test against the seed's,
5- LinkDump.pas, which writes the same file. *)
6-module LinkDump;
7-import Files, Diag, Scan, Chunk, Link, Elf;
8-
9-const NumC = 200;
10-
11-var seed: I64;
12-
13-proc rnd(n: INT): INT;
14-begin
15- seed := (seed * 1103515245 + 12345) & 7FFFFFFFH;
16- return INT((seed shr 8) mod I64(n));
17-end;
18-
19-(* a library that must be taken *)
20-proc ok(taken: BOOL);
21-begin
22- if not taken then Diag.fatal("too many libraries"); end;
23-end;
24-
25-proc main*;
26-var
27- names: [8]INT; b: [64]U8; arg: []U8;
28- i, j, kind, n, x, y, z, c, e, line, col, mode: INT;
29-begin
30- seed := 5;
31- arg := Files.arg(1);
32- mode := INT(arg[0]) - 48;
33- for i := 0 to 7 do b[0] := U8(97 + i); names[i] := Scan.intern(ADR(b[0]), 1); end;
34- Link.setPlaces(Chunk.newChunk(Chunk.secRodata, -1, -1));
35- Chunk.setData(Link.placesChunk, ADR(b[0]), 0, 8);
36- for i := 0 to NumC - 1 do
37- if i = 0 then kind := 0; else kind := rnd(10); end;
38- x := rnd(4); y := rnd(8);
39- match kind of
40- | 0..5:
41- c := Chunk.newChunk(Chunk.secText, x - 1, y);
42- Chunk.beginChunk(c);
43- z := rnd(3); Chunk.setCurFile(names[z]);
44- line := rnd(300); col := rnd(60);
45- Chunk.noteLine(line, col);
46- if i = 0 then Chunk.addFixup(Chunk.pc, Link.placesChunk, 0); Chunk.put4(0); end;
47- n := 2 + rnd(10);
48- for j := 1 to n do
49- z := rnd(5);
50- if z <= 1 then
51- e := rnd(NumC); y := rnd(8);
52- Chunk.addFixup(Chunk.pc, e, y);
53- Chunk.put4(0);
54- elsif z = 2 then
55- z := rnd(3); Chunk.setCurFile(names[z]);
56- line := rnd(300); col := rnd(60);
57- Chunk.noteLine(line, col);
58- else
59- x := rnd(1 shl 30); Chunk.put4(x); x := rnd(256); Chunk.put1(x);
60- end;
61- end;
62- Chunk.endChunk(c);
63- n := rnd(3);
64- for j := 1 to n do
65- x := rnd(8); y := rnd(200); z := rnd(6);
66- Chunk.noteVar(c, names[x], y - 100, z);
67- end;
68- | 6, 7:
69- c := Chunk.newChunk(Chunk.secRodata, x - 1, y);
70- n := 8 * (1 + rnd(4));
71- for j := 0 to n - 1 do b[j] := U8(rnd(256)); end;
72- Chunk.setData(c, ADR(b[0]), n, 8);
73- for j := 0 to n div 8 - 1 do
74- z := rnd(2);
75- if z = 0 then e := rnd(NumC); y := rnd(8); Chunk.addDataFixup(c, j * 8, e, y); end;
76- end;
77- | 8:
78- c := Chunk.newChunk(Chunk.secBss, x - 1, y);
79- z := rnd(200); e := rnd(4);
80- Chunk.setBss(c, 1 + z, 1 shl e);
81- | else: z := rnd(8); c := Chunk.externChunk(names[z]);
82- end;
83- end;
84- (* every chunk a fixup names must exist, and be defined if it is reached *)
85- while Chunk.numChunks < NumC do
86- c := Chunk.newChunk(Chunk.secBss, -1, -1);
87- Chunk.setBss(c, 8, 8);
88- end;
89- for i := 0 to Chunk.numChunks - 1 do
90- if Chunk.chunks[i].size < 0 then Chunk.setBss(i, 8, 8); end;
91- end;
92- Elf.setMainPath("some/main.raz");
93- if mode = 1 then
94- ok(Elf.needLib(names[0]));
95- ok(Elf.needLib(names[1]));
96- end;
97- Elf.setStripped(mode = 2);
98- if mode = 2 then Link.setPlaces(-1); end;
99- Link.markLive(1);
100- Elf.writeElf(Files.arg(2), 1);
101-end;
102-
103-end LinkDump.

self/test/Recover.raz deleted +0 -38

@@ -1,38 +0,0 @@
1-(* Tests going on after an error, as the parser does with try: a driver
2- reads a file's symbols and reports each name `bad` as an error,
3- several calls deep; the error comes back up through them, and the
4- driver reads on from the next symbol. *)
5-module Recover;
6-import Out, Files, Diag, Scan;
7-
8-var failed, names: INT;
9-
10-proc deep(n: INT): ERROR;
11-begin
12- if n > 0 then
13- try deep(n - 1);
14- return nil;
15- end;
16- return Scan.mark("a bad name");
17-end;
18-
19-proc main*;
20-var err: ERROR;
21-begin
22- if LEN(Scan.open(Files.arg(1))) # 0 then Diag.fatal("no file"); end;
23- while Scan.tok # Scan.sEof do
24- Scan.next;
25- if Scan.tok = Scan.sIdent then
26- INC(names);
27- if Scan.nameOf(Scan.id) = "bad" then
28- err := deep(5);
29- if err # nil then INC(failed); end;
30- end;
31- end;
32- end;
33- Out.int(names); Out.str(" names, "); Out.int(failed); Out.str(" failed, ");
34- Out.int(Diag.errors); Out.str(" errors\n");
35- Diag.finish;
36-end;
37-
38-end Recover.

self/test/ScanBench.pas deleted +0 -12

@@ -1,12 +0,0 @@
1-{ Counts the symbols of a file and nothing else, for timing scan.pas
2- against self/Scan.raz (ScanBench.raz). }
3-program scanbench;
4-{$mode objfpc}{$H-}
5-uses diag, scan;
6-var n: longint;
7-begin
8- if Open(ParamStr(1)) <> '' then Fatal('no file');
9- n := 0;
10- repeat Next; inc(n) until tok = sEof;
11- writeln(n, ' symbols');
12-end.

self/test/ScanBench.raz deleted +0 -15

@@ -1,15 +0,0 @@
1-(* Counts the symbols of a file and nothing else, for timing Scan.raz
2- against the seed's scan.pas (ScanBench.pas). *)
3-module ScanBench;
4-import Out, Files, Diag, Scan;
5-
6-proc main*;
7-var n: INT;
8-begin
9- if LEN(Scan.open(Files.arg(1))) # 0 then Diag.fatal("no file"); end;
10- n := 0;
11- repeat Scan.next; INC(n); until Scan.tok = Scan.sEof;
12- Out.int(n); Out.str(" symbols\n");
13-end;
14-
15-end ScanBench.

self/test/ScanDump.pas deleted +0 -21

@@ -1,21 +0,0 @@
1-{ Prints the symbols of a file, one per line: the seed's side of a test
2- of self/Scan.raz, which prints the same. A real is shown by its bits,
3- so that no formatting library decides what is the same. }
4-program scandump;
5-{$mode objfpc}{$H-}
6-uses diag, scan;
7-var i: longint; bits: int64;
8-begin
9- if Open(ParamStr(1)) <> '' then Fatal('no file');
10- repeat
11- Next;
12- write(LineOf(TokPos), ':', TokPos.a, ':', TokPos.b, ' ', CurLine, ':', CurCol, ' ', ord(tok));
13- case tok of
14- sIdent: write(' ', NameOf(id), ' ', id);
15- sInt, sChar: write(' ', ival);
16- sReal: begin Move(rval, bits, 8); write(' ', HexStr(bits, 16)) end;
17- sString: begin write(' "'); for i := 0 to slen - 1 do write(sbuf[i], ','); write('"') end;
18- end;
19- writeln;
20- until tok = sEof;
21-end.

self/test/ScanDump.raz deleted +0 -35

@@ -1,35 +0,0 @@
1-(* Prints the symbols of a file, one per line: self/Scan.raz's side of a
2- test against the seed's, ScanDump.pas, which prints the same. *)
3-module ScanDump;
4-import Out, Fmt, Files, Diag, Scan;
5-
6-proc main*;
7-var p: Diag.Pos; bits: ^U64; i: INT; str: []U8; r: F64;
8-begin
9- if LEN(Scan.open(Files.arg(1))) # 0 then Diag.fatal("no file"); end;
10- repeat
11- Scan.next;
12- p := Scan.tokPos();
13- Fmt.print("{}:{}:{} {}:{} {}", [Fmt.int(Diag.lineOf(p)), Fmt.int(p.a), Fmt.int(p.b),
14- Fmt.int(Scan.curLine()), Fmt.int(Scan.curCol()), Fmt.int(INT(Scan.tok))]);
15- match Scan.tok of
16- | sIdent: Fmt.print(" {} {}", [Fmt.str(Scan.nameOf(Scan.id)), Fmt.int(Scan.id)]);
17- | sInt: Fmt.print(" {}", [Fmt.int(Scan.ival)]);
18- | sChar: Fmt.print(" {}", [Fmt.int(Scan.ival)]);
19- | sReal:
20- r := Scan.rval;
21- bits := ^U64(ADR(r));
22- Out.str(" ");
23- Out.hex(bits^, 16);
24- | sString:
25- Out.str(" \"");
26- str := Scan.strBytes();
27- for i := 0 to LEN(str) - 1 do Fmt.print("{},", [Fmt.int(INT(str[i]))]); end;
28- Out.str("\"");
29- | else:
30- end;
31- Out.ln;
32- until Scan.tok = Scan.sEof;
33-end;
34-
35-end ScanDump.

self/test/SymDump.pas deleted +0 -185

@@ -1,185 +0,0 @@
1-{ Builds types and objects by a fixed pseudo-random script, asks of them
2- what the parser asks of sym, and prints the answers: the seed's side
3- of a test of self/Sym.raz, whose SymDump.raz does the same and prints
4- the same. With the argument dup or deep it ends in the error of a name
5- declared twice, or of too many scopes. }
6-program symdump;
7-{$mode objfpc}{$H-}
8-uses diag, scan, sym;
9-const
10- Words: array[0..19] of string = ('alpha', 'alpho', 'beta', 'bet', 'gamma', 'gama', 'delta', 'Delta',
11- 'eps', 'zeta', 'eta', 'theta', 'iota', 'kappa', 'lambda', 'mu', 'nu', 'xi', 'omicron', 'pi');
12-var
13- seed: int64;
14- names: array[0..19] of longint;
15- mods: array[0..2] of PModule;
16- base: array[0..11] of PType;
17- pool: array[0..299] of PType;
18- objs: array[0..299] of PObj;
19- numPool, numObjs, i, k, n, op, x, y, z: longint;
20- t, o2: PType;
21- o: PObj;
22- saved: array[0..MaxDepth - 1] of longint;
23- d: longint;
24- v: int64;
25-
26-function Rnd(n: longint): longint;
27-begin
28- seed := (seed * 1103515245 + 12345) and $7FFFFFFF;
29- Rnd := (seed shr 8) mod n;
30-end;
31-
32-function Fields(m: longint; allowVar: boolean): PObj;
33-var f, first, last: PObj; j, x, y, z: longint;
34-begin
35- first := nil; last := nil;
36- for j := 1 to m do begin
37- x := Rnd(20); y := Rnd(numPool);
38- f := NewObj(oField, names[x], pool[y]);
39- z := Rnd(2); f^.exported := z = 0;
40- z := Rnd(3); f^.isVar := allowVar and (z = 0);
41- f^.val := j * 8;
42- if first = nil then first := f else last^.next := f;
43- last := f;
44- end;
45- Fields := first;
46-end;
47-
48-procedure Add(t: PType);
49-begin
50- if numPool <= High(pool) then begin pool[numPool] := t; inc(numPool) end;
51-end;
52-
53-procedure MakeType;
54-var t: PType; r, m, x: longint; f: PObj;
55-begin
56- r := Rnd(11);
57- case r of
58- 0: t := NewType(fPtr, 8, 8);
59- 1: t := NewType(fArray, 0, 1);
60- 2: t := NewType(fSlice, 16, 8);
61- 3: t := NewType(fRecord, 0, 8);
62- 4: t := NewType(fProc, 8, 8);
63- 5: t := NewType(fSet, 8, 8);
64- 6: t := NewType(fVariant, 16, 8);
65- 7: t := NewType(fEnum, 1, 1);
66- 8: t := NewType(fRecord, 16, 8);
67- 9: t := NewType(fProc, 8, 8);
68- else t := NewType(fPtr, 8, 8);
69- end;
70- x := Rnd(numPool); t^.base := pool[x];
71- t^.len := Rnd(5);
72- x := Rnd(4); t^.vol := x = 0;
73- x := Rnd(4); t^.variadic := (t^.form = fProc) and (x = 0);
74- x := Rnd(2); t^.tuple := (t^.form = fRecord) and (x = 0);
75- if t^.form in [fRecord, fProc, fVariant] then begin
76- m := Rnd(4);
77- t^.fields := Fields(m, t^.form = fProc);
78- t^.len := m;
79- if t^.form = fRecord then t^.base := nil;
80- x := Rnd(2);
81- if (t^.form = fProc) and (x = 0) then t^.base := nil;
82- if t^.form = fVariant then begin
83- f := t^.fields;
84- while f <> nil do begin f^.cls := oCase; x := Rnd(3); f^.fields := Fields(x, false); f := f^.next end;
85- end;
86- end;
87- x := Rnd(3);
88- if x = 0 then begin
89- x := Rnd(20); t^.obj := NewObj(oType, names[x], t);
90- x := Rnd(3); t^.obj^.module := mods[x];
91- end;
92- Add(t);
93-end;
94-
95-begin
96- seed := 11;
97- for i := 0 to 19 do names[i] := Intern(@Words[i][1], length(Words[i]));
98- for i := 0 to 2 do begin
99- New(mods[i]); FillChar(mods[i]^, SizeOf(TModule), 0);
100- mods[i]^.sname := names[i * 5];
101- end;
102- curModule := mods[0];
103- base[0] := tI8; base[1] := tI16; base[2] := tI32; base[3] := tI64; base[4] := tU8;
104- base[5] := tU16; base[6] := tU32; base[7] := tU64; base[8] := tBool; base[9] := tF32;
105- base[10] := tReal; base[11] := tInt;
106- for i := 0 to 11 do Add(base[i]);
107- if ParamCount >= 1 then begin if Open('lib/Rt.raz') <> '' then Fatal('no file'); Next; Next end;
108- numObjs := 0;
109- for k := 1 to 4000 do begin
110- op := Rnd(14);
111- case op of
112- 0, 1, 2: MakeType;
113- 3, 4: if numObjs <= High(objs) then begin
114- x := Rnd(8); y := Rnd(20);
115- if Find(x, names[y]) = nil then begin
116- z := Rnd(8); n := Rnd(numPool);
117- o := NewObj(TClass(z), names[y], pool[n]);
118- z := Rnd(2); o^.exported := z = 0;
119- z := Rnd(3); o^.module := mods[z];
120- Insert(o, x);
121- objs[numObjs] := o; inc(numObjs);
122- writeln('I ', x, ' ', NameOf(names[y]), ' ', o^.scope);
123- end;
124- end;
125- 5: begin x := Rnd(8); y := Rnd(20); o := Find(x, names[y]);
126- write('F ', x, ' ', NameOf(names[y]), ' ');
127- if o = nil then writeln('-') else writeln(ord(o^.cls), ' ', o^.scope);
128- end;
129- 6: begin
130- x := Rnd(8); y := Rnd(20);
131- if ScopeDepth < 6 then OpenScope(x);
132- o := Lookup(names[y]);
133- write('L ', ScopeDepth, ' ', NameOf(names[y]), ' ');
134- if o = nil then writeln('-') else writeln(ord(o^.cls), ' ', o^.scope);
135- z := Rnd(2);
136- if (ScopeDepth > 1) and (z = 0) then CloseScope;
137- end;
138- 7: begin
139- y := Rnd(20); x := Rnd(9) - 1; z := Rnd(3); curModule := mods[z];
140- o := Closest(names[y], x);
141- write('C ', NameOf(names[y]), ' ', x, ' ');
142- if o = nil then writeln('-') else writeln(NameOf(o^.name), ' ', o^.scope);
143- end;
144- 8: begin
145- x := Rnd(numPool); z := Rnd(3); curModule := mods[z];
146- writeln('T ', TypeName(pool[x]));
147- end;
148- 9: begin
149- x := Rnd(numPool); y := Rnd(numPool);
150- writeln('S ', ord(Same(pool[x], pool[y])), ' ', ord(Same(pool[x], pool[x])));
151- t := NewType(fPtr, 8, 8); t^.base := pool[x];
152- o2 := t; t := NewType(fPtr, 8, 8); t^.base := pool[x];
153- writeln('S ', ord(Same(o2, t)));
154- end;
155- 10: if numObjs > 0 then begin x := Rnd(numObjs); writeln('P ', HexStr(Fingerprint(objs[x]), 16)) end;
156- 11: begin
157- x := Rnd(numPool); y := Rnd(1 shl 20); z := Rnd(2); n := Rnd(2);
158- v := int64(y) * 4096 * z - y * n;
159- t := pool[x];
160- writeln('B ', ord(Fits(v, t)), ' ', ord(IsInt(t)), ' ', ord(IsScalar(t)), ' ', ord(IsAggregate(t)), ' ',
161- ord(InTwoRegs(t)), ' ', ord(BehindPointer(t)), ' ', AlignUp(y, 1 shl z));
162- end;
163- 12: if (ScopeDepth > 1) and (ScopeDepth < 6) then begin
164- d := ScopeDepth; SaveScopes(d, saved);
165- writeln('V ', ScopeDepth, ' ', TopScope);
166- RestoreScopes(d, saved);
167- writeln('V ', ScopeDepth, ' ', TopScope);
168- x := NewScope; writeln('N ', x);
169- end;
170- 13: begin x := ScopeDepth; if x > 3 then CutScopes(2); writeln('X ', x, ' ', ScopeDepth) end;
171- end;
172- end;
173- { the universe, and the sizes it made }
174- for i := 0 to 11 do writeln('U ', ord(base[i]^.form), ' ', base[i]^.size, ' ', ord(base[i]^.signed), ' ', NameOf(base[i]^.obj^.name));
175- if ParamCount >= 1 then begin
176- if ParamStr(1) = 'dup' then begin
177- o := NewObj(oVar, names[3], tI8);
178- Insert(o, 100); Insert(o, 100);
179- end;
180- if ParamStr(1) = 'deep' then begin
181- CutScopes(1);
182- for i := 1 to MaxDepth + 1 do OpenScope(i);
183- end;
184- end;
185-end.

self/test/SymDump.raz deleted +0 -225

@@ -1,225 +0,0 @@
1-(* Builds types and objects by a fixed pseudo-random script, asks of them
2- what the parser asks of Sym, and prints the answers: self/Sym.raz's
3- side of a test against the seed's, SymDump.pas, which prints the same.
4- With the argument dup or deep it ends in the error of a name declared
5- twice, or of too many scopes. *)
6-module SymDump;
7-import Out, Fmt, Files, Heap, Diag, Scan, Sym;
8-
9-const
10- Words: [20][]U8 = ["alpha", "alpho", "beta", "bet", "gamma", "gama", "delta", "Delta",
11- "eps", "zeta", "eta", "theta", "iota", "kappa", "lambda", "mu", "nu", "xi", "omicron", "pi"];
12-
13-var
14- seed: I64;
15- names: [20]INT;
16- mods: [3]^Sym.Module;
17- base: [12]^Sym.Type;
18- pool: [300]^Sym.Type;
19- objs: [300]^Sym.Obj;
20- classes: [8]Sym.Class;
21- numPool, numObjs: INT;
22-
23-proc rnd(n: INT): INT;
24-begin
25- seed := (seed * 1103515245 + 12345) & 7FFFFFFFH;
26- return INT((seed shr 8) mod I64(n));
27-end;
28-
29-proc bit(f: BOOL): INT;
30-begin
31- if f then return 1; end;
32- return 0;
33-end;
34-
35-proc nm(i: INT): []U8;
36-begin
37- return Scan.nameOf(names[i]);
38-end;
39-
40-(* The result of a call that must succeed *)
41-proc ok(e: ERROR);
42-begin
43- if e # nil then Diag.finish; end;
44-end;
45-
46-proc fields(m: INT; allowVar: BOOL): ^Sym.Obj;
47-var f, first, last: ^Sym.Obj; j, x, y, z: INT;
48-begin
49- first := nil; last := nil;
50- for j := 1 to m do
51- x := rnd(20); y := rnd(numPool);
52- f := Sym.newObj(Sym.oField, names[x], pool[y]);
53- z := rnd(2); f^.exported := z = 0;
54- z := rnd(3); f^.isVar := allowVar and (z = 0);
55- f^.val := j * 8;
56- if first = nil then first := f; else last^.next := f; end;
57- last := f;
58- end;
59- return first;
60-end;
61-
62-proc add(t: ^Sym.Type);
63-begin
64- if numPool < 300 then pool[numPool] := t; INC(numPool); end;
65-end;
66-
67-proc makeType;
68-var t: ^Sym.Type; r, m, x: INT; f: ^Sym.Obj;
69-begin
70- r := rnd(11);
71- match r of
72- | 0: t := Sym.newType(Sym.fPtr, 8, 8);
73- | 1: t := Sym.newType(Sym.fArray, 0, 1);
74- | 2: t := Sym.newType(Sym.fSlice, 16, 8);
75- | 3: t := Sym.newType(Sym.fRecord, 0, 8);
76- | 4: t := Sym.newType(Sym.fProc, 8, 8);
77- | 5: t := Sym.newType(Sym.fSet, 8, 8);
78- | 6: t := Sym.newType(Sym.fVariant, 16, 8);
79- | 7: t := Sym.newType(Sym.fEnum, 1, 1);
80- | 8: t := Sym.newType(Sym.fRecord, 16, 8);
81- | 9: t := Sym.newType(Sym.fProc, 8, 8);
82- | else: t := Sym.newType(Sym.fPtr, 8, 8);
83- end;
84- x := rnd(numPool); t^.base := pool[x];
85- t^.len := rnd(5);
86- x := rnd(4); t^.vol := x = 0;
87- x := rnd(4); t^.variadic := (t^.form = Sym.fProc) and (x = 0);
88- x := rnd(2); t^.tuple := (t^.form = Sym.fRecord) and (x = 0);
89- if (t^.form = Sym.fRecord) or (t^.form = Sym.fProc) or (t^.form = Sym.fVariant) then
90- m := rnd(4);
91- t^.fields := fields(m, t^.form = Sym.fProc);
92- t^.len := m;
93- if t^.form = Sym.fRecord then t^.base := nil; end;
94- x := rnd(2);
95- if (t^.form = Sym.fProc) and (x = 0) then t^.base := nil; end;
96- if t^.form = Sym.fVariant then
97- f := t^.fields;
98- while f # nil do
99- f^.cls := Sym.oCase;
100- x := rnd(3); f^.fields := fields(x, false);
101- f := f^.next;
102- end;
103- end;
104- end;
105- x := rnd(3);
106- if x = 0 then
107- x := rnd(20); t^.obj := Sym.newObj(Sym.oType, names[x], t);
108- x := rnd(3); t^.obj^.home := mods[x];
109- end;
110- add(t);
111-end;
112-
113-proc main*;
114-var
115- i, k, op, x, y, z, n, d: INT; t, o2: ^Sym.Type; o: ^Sym.Obj; v: I64;
116- saved: [Sym.MaxDepth]INT; arg: []U8;
117-begin
118- seed := 11;
119- classes := [Sym.oConst, Sym.oType, Sym.oVar, Sym.oProc, Sym.oModule, Sym.oField, Sym.oCase, Sym.oBuiltin];
120- for i := 0 to 19 do names[i] := Scan.intern(ADR(Words[i][0]), LEN(Words[i])); end;
121- for i := 0 to 2 do
122- NEW(mods[i], Heap.heap);
123- mods[i]^.sname := names[i * 5];
124- end;
125- Sym.setCurModule(mods[0]);
126- base[0] := Sym.tI8; base[1] := Sym.tI16; base[2] := Sym.tI32; base[3] := Sym.tI64; base[4] := Sym.tU8;
127- base[5] := Sym.tU16; base[6] := Sym.tU32; base[7] := Sym.tU64; base[8] := Sym.tBool; base[9] := Sym.tF32;
128- base[10] := Sym.tReal; base[11] := Sym.tInt;
129- for i := 0 to 11 do add(base[i]); end;
130- arg := "";
131- if ARGC > 1 then arg := Files.arg(1); end;
132- if LEN(arg) > 0 then
133- if LEN(Scan.open("lib/Rt.raz")) # 0 then Diag.fatal("no file"); end;
134- Scan.next; Scan.next;
135- end;
136- numObjs := 0;
137- for k := 1 to 4000 do
138- op := rnd(14);
139- match op of
140- | 0, 1, 2: makeType;
141- | 3, 4:
142- if numObjs < 300 then
143- x := rnd(8); y := rnd(20);
144- if Sym.find(x, names[y]) = nil then
145- z := rnd(8); n := rnd(numPool);
146- o := Sym.newObj(classes[z], names[y], pool[n]);
147- z := rnd(2); o^.exported := z = 0;
148- z := rnd(3); o^.home := mods[z];
149- ok(Sym.insert(o, x));
150- objs[numObjs] := o; INC(numObjs);
151- Fmt.print("I {} {} {}\n", [Fmt.int(x), Fmt.str(nm(y)), Fmt.int(o^.scope)]);
152- end;
153- end;
154- | 5:
155- x := rnd(8); y := rnd(20); o := Sym.find(x, names[y]);
156- Fmt.print("F {} {} ", [Fmt.int(x), Fmt.str(nm(y))]);
157- if o = nil then Out.str("-\n");
158- else Fmt.print("{} {}\n", [Fmt.int(INT(o^.cls)), Fmt.int(o^.scope)]); end;
159- | 6:
160- x := rnd(8); y := rnd(20);
161- if Sym.scopeDepth() < 6 then ok(Sym.openScope(x)); end;
162- o := Sym.lookup(names[y]);
163- Fmt.print("L {} {} ", [Fmt.int(Sym.scopeDepth()), Fmt.str(nm(y))]);
164- if o = nil then Out.str("-\n");
165- else Fmt.print("{} {}\n", [Fmt.int(INT(o^.cls)), Fmt.int(o^.scope)]); end;
166- z := rnd(2);
167- if (Sym.scopeDepth() > 1) and (z = 0) then Sym.closeScope; end;
168- | 7:
169- y := rnd(20); x := rnd(9) - 1; z := rnd(3); Sym.setCurModule(mods[z]);
170- o := Sym.closest(names[y], x);
171- Fmt.print("C {} {} ", [Fmt.str(nm(y)), Fmt.int(x)]);
172- if o = nil then Out.str("-\n");
173- else Fmt.print("{} {}\n", [Fmt.str(Scan.nameOf(o^.name)), Fmt.int(o^.scope)]); end;
174- | 8:
175- x := rnd(numPool); z := rnd(3); Sym.setCurModule(mods[z]);
176- Fmt.print("T {}\n", [Fmt.str(Sym.typeName(pool[x]))]);
177- | 9:
178- x := rnd(numPool); y := rnd(numPool);
179- Fmt.print("S {} {}\n", [Fmt.int(bit(Sym.same(pool[x], pool[y]))), Fmt.int(bit(Sym.same(pool[x], pool[x])))]);
180- t := Sym.newType(Sym.fPtr, 8, 8); t^.base := pool[x];
181- o2 := t; t := Sym.newType(Sym.fPtr, 8, 8); t^.base := pool[x];
182- Fmt.print("S {}\n", [Fmt.int(bit(Sym.same(o2, t)))]);
183- | 10:
184- if numObjs > 0 then
185- x := rnd(numObjs);
186- Out.str("P "); Out.hex(Sym.fingerprint(objs[x]), 16); Out.ln;
187- end;
188- | 11:
189- x := rnd(numPool); y := rnd(1 shl 20); z := rnd(2); n := rnd(2);
190- v := I64(y) * 4096 * I64(z) - I64(y) * I64(n);
191- t := pool[x];
192- Fmt.print("B {} {} {} {} {} {} {}\n", [Fmt.int(bit(Sym.fits(v, t))), Fmt.int(bit(Sym.isInt(t))),
193- Fmt.int(bit(Sym.isScalar(t))), Fmt.int(bit(Sym.isAggregate(t))), Fmt.int(bit(Sym.inTwoRegs(t))),
194- Fmt.int(bit(Sym.behindPointer(t))), Fmt.int(Sym.alignUp(y, 1 shl z))]);
195- | 12:
196- if (Sym.scopeDepth() > 1) and (Sym.scopeDepth() < 6) then
197- d := Sym.saveScopes(saved);
198- Fmt.print("V {} {}\n", [Fmt.int(Sym.scopeDepth()), Fmt.int(Sym.topScope())]);
199- Sym.restoreScopes(d, saved);
200- Fmt.print("V {} {}\n", [Fmt.int(Sym.scopeDepth()), Fmt.int(Sym.topScope())]);
201- x := Sym.newScope();
202- Fmt.print("N {}\n", [Fmt.int(x)]);
203- end;
204- | else:
205- x := Sym.scopeDepth();
206- if x > 3 then Sym.cutScopes(2); end;
207- Fmt.print("X {} {}\n", [Fmt.int(x), Fmt.int(Sym.scopeDepth())]);
208- end;
209- end;
210- for i := 0 to 11 do
211- Fmt.print("U {} {} {} {}\n", [Fmt.int(INT(base[i]^.form)), Fmt.int(base[i]^.size),
212- Fmt.int(bit(base[i]^.signed)), Fmt.str(Scan.nameOf(base[i]^.obj^.name))]);
213- end;
214- if arg = "dup" then
215- o := Sym.newObj(Sym.oVar, names[3], Sym.tI8);
216- ok(Sym.insert(o, 100));
217- ok(Sym.insert(o, 100));
218- end;
219- if arg = "deep" then
220- Sym.cutScopes(1);
221- for i := 1 to Sym.MaxDepth + 1 do ok(Sym.openScope(i)); end;
222- end;
223-end;
224-
225-end SymDump.

self/test/X64Dump.pas deleted +0 -160

@@ -1,160 +0,0 @@
1-{ Writes every instruction the encoder makes, with operands drawn by a
2- fixed pseudo-random script, then prints the bytes, the fixups and the
3- listing (raz -S) of what it made: the seed's side of a test of
4- self/X64.raz, whose X64Dump.raz does the same and prints the same. }
5-program x64dump;
6-{$mode objfpc}{$H-}
7-uses diag, scan, chunk, x64;
8-var
9- seed: int64;
10- i, k, op, a, b, c, d, lab1, lab2: longint;
11- m: TMem;
12- path: string;
13-
14-function Rnd(n: longint): longint;
15-begin
16- seed := (seed * 1103515245 + 12345) and $7FFFFFFF;
17- Rnd := (seed shr 8) mod n;
18-end;
19-
20-{ a register, with the stack and base pointers and the high ones often enough }
21-function Reg: longint;
22-begin
23- Reg := Rnd(16);
24-end;
25-
26-{ a size of 1, 2, 4 or 8 bytes }
27-function Size: longint;
28-begin
29- Size := 1 shl Rnd(4);
30-end;
31-
32-{ a value that fits size bytes, of 8 as 32 bits }
33-function Imm(sz: longint): longint;
34-var x: longint;
35-begin
36- x := Rnd(1 shl 30);
37- case Rnd(3) of
38- 0: Imm := x mod 100 - 50;
39- 1: Imm := x - (1 shl 29);
40- else Imm := x mod 20000 - 10000;
41- end;
42- if sz = 1 then Imm := Imm mod 128
43- else if sz = 2 then Imm := Imm mod 32768;
44-end;
45-
46-function RandMem: TMem;
47-var kind, base, idx, sc, disp, x: longint;
48-begin
49- kind := Rnd(6);
50- base := Reg; idx := Reg; sc := 1 shl Rnd(4); x := Rnd(5);
51- case x of
52- 0: disp := 0;
53- 1: disp := Rnd(250) - 125;
54- 2: disp := Rnd(1 shl 20) - (1 shl 19);
55- 3: disp := 127 + Rnd(3) - 1;
56- else disp := -128 + Rnd(3) - 1;
57- end;
58- case kind of
59- 0, 1: RandMem := Mem(base, disp);
60- 2: RandMem := MemRip(Rnd(5), disp);
61- 3, 4: RandMem := MemIdx(base, idx, sc, disp);
62- else RandMem := Mem(base, 0);
63- end;
64-end;
65-
66-begin
67- seed := 3;
68- path := 'lib/Rt.raz';
69- if Open(path) <> '' then Fatal('no file');
70- listing := true;
71- for i := 0 to 4 do NewChunk(secText, i - 1, i);
72- curFile := Intern(@path[1], length(path));
73- BeginChunk(0);
74- lab1 := NoLabel; lab2 := NoLabel;
75- for k := 1 to 3000 do begin
76- if k mod 7 = 0 then begin a := Rnd(300); b := Rnd(60); NoteLine(1 + a, b) end;
77- op := Rnd(50);
78- case op of
79- 0: begin a := Reg; b := Reg; MovRR(a, b) end;
80- 1: begin
81- a := Reg; b := Rnd(6); c := Rnd(1 shl 30);
82- case b of
83- 0: MovRI(a, 0);
84- 1: MovRI(a, c);
85- 2: MovRI(a, -c);
86- 3: MovRI(a, int64(c) * 8 + 5);
87- 4: MovRI(a, int64(c) * 4096 * 4096 * 9 - 7);
88- else MovRI(a, 0);
89- end;
90- end;
91- 2: begin a := Rnd(8); m := RandMem; b := Size; c := Imm(b); AluMI(a, m, c, b) end;
92- 3: begin m := RandMem; b := Size; c := Imm(b); StoreI(m, c, b) end;
93- 4: begin a := Reg; m := RandMem; b := Size; c := Rnd(2); Load(a, m, b, c = 0) end;
94- 5: begin m := RandMem; a := Reg; b := Size; Store(m, a, b) end;
95- 6: begin a := Reg; m := RandMem; Lea(a, m) end;
96- 7: begin a := Rnd(8); b := Reg; c := Reg; Alu(a, b, c) end;
97- 8: begin a := Rnd(8); b := Reg; c := Imm(8); AluI(a, b, c) end;
98- 9: begin a := Rnd(8); b := Reg; m := RandMem; AluM(a, b, m) end;
99- 10: begin a := Reg; b := Reg; Imul(a, b) end;
100- 11: begin a := Reg; c := Imm(8); ImulI(a, c) end;
101- 12: begin a := Rnd(3); b := Reg; if a = 0 then a := shShl else if a = 1 then a := shShr else a := shSar; Shift(a, b) end;
102- 13: begin a := Rnd(3); b := Reg; c := Rnd(64); if a = 0 then a := shShl else if a = 1 then a := shShr else a := shSar; ShiftI(a, b, c) end;
103- 14: begin a := Rnd(4); b := Reg; if a < 2 then a := a + 2 else a := a + 4; Unary(a, b) end;
104- 15: Cqo;
105- 16: begin a := Reg; b := 1 shl Rnd(3); c := Rnd(2); Extend(a, b, c = 0) end;
106- 17: begin a := Rnd(16); b := Reg; SetCC(a, b) end;
107- 18: begin a := Reg; b := Reg; TestRR(a, b) end;
108- 19: begin a := Reg; Push(a) end;
109- 20: begin a := Reg; Pop(a) end;
110- 21: begin a := Rnd(5); CallChunk(a) end;
111- 22: begin a := Rnd(1000); CallBack(a) end;
112- 23: begin a := Reg; CallR(a) end;
113- 24: begin a := Reg; JmpR(a) end;
114- 25: begin m := RandMem; CallM(m) end;
115- 26: begin a := Rnd(5); case a of 0: Ret; 1: Leave; 2: Syscall; 3: Mfence; else Ud2 end end;
116- 27: begin a := 8 shl Rnd(3); Align(a) end;
117- 28: begin a := Rnd(5); case a of 0: RepMovsb; 1: Std; 2: Cld; 3: RepStosb; else RepeCmpsb end end;
118- 29: begin m := RandMem; a := Reg; LockCmpxchg(m, a) end;
119- 30: begin m := RandMem; a := Reg; Xchg(m, a) end;
120- 31: begin m := RandMem; a := Reg; LockXadd(m, a) end;
121- 32: begin a := Reg; b := Reg; MovqXR(a, b) end;
122- 33: begin a := Reg; b := Reg; MovqRX(a, b) end;
123- 34: begin a := Reg; b := Reg; MovX(a, b) end;
124- 35: begin a := Reg; m := RandMem; b := Rnd(2); MovsXM(a, m, b = 0) end;
125- 36: begin m := RandMem; a := Reg; b := Rnd(2); MovsMX(m, a, b = 0) end;
126- 37: begin
127- d := Rnd(5); a := Reg; b := Reg; c := Rnd(2);
128- case d of 0: d := $58; 1: d := $59; 2: d := $5C; 3: d := $5E; else d := $5A end;
129- Sse(d, a, b, c = 0);
130- end;
131- 38: begin
132- d := Rnd(5); a := Reg; m := RandMem; c := Rnd(2);
133- case d of 0: d := $58; 1: d := $59; 2: d := $5C; 3: d := $5E; else d := $5A end;
134- SseM(d, a, m, c = 0);
135- end;
136- 39: begin a := Reg; b := Reg; c := Rnd(2); Ucomis(a, b, c = 0) end;
137- 40: begin a := Reg; b := Reg; c := Rnd(2); Cvtsi2s(a, b, c = 0) end;
138- 41: begin a := Reg; b := Reg; c := Rnd(2); Cvtts2si(a, b, c = 0) end;
139- 42: begin a := Reg; b := Rnd(64); Btc(a, b) end;
140- 43: begin
141- a := Rnd(16); b := Rnd(2);
142- if b = 0 then Jmp(lab1) else Jcc(a, lab2);
143- end;
144- 44: begin a := Rnd(16); b := Rnd(2); c := pc - Rnd(200); if b = 0 then JmpBack(c) else JccBack(a, c) end;
145- 45: if Rnd(3) = 0 then begin FixLink(lab1); lab1 := NoLabel end
146- else begin FixLinkTo(lab2, pc - 20); lab2 := NoLabel end;
147- 46: begin Jmp(lab1); DropJumpTo(lab1) end;
148- 47: begin a := JoinLinks(lab1, lab2); lab1 := a; lab2 := NoLabel end;
149- else begin a := Rnd(256); Put1(a) end;
150- end;
151- end;
152- FixLink(lab1); FixLink(lab2);
153- EndChunk(0);
154- chunks^[0].live := true;
155- writeln('pc ', pc, ' fixups ', numFixups, ' lines ', numLines, ' said ', SaidCount);
156- for i := 0 to pc - 1 do write(HexStr(code^[i], 2));
157- writeln;
158- for i := 0 to numFixups - 1 do writeln('F ', fixups^[i].at, ' ', fixups^[i].chunk, ' ', fixups^[i].addend);
159- List(-1);
160-end.

self/test/X64Dump.raz deleted +0 -208

@@ -1,208 +0,0 @@
1-(* Writes every instruction the encoder makes, with operands drawn by a
2- fixed pseudo-random script, then prints the bytes, the fixups and the
3- listing (raz -S) of what it made: self/X64.raz's side of a test
4- against the seed's, X64Dump.pas, which prints the same. *)
5-module X64Dump;
6-import Out, Fmt, Diag, Scan, Chunk, X64;
7-
8-var seed: I64;
9-
10-proc rnd(n: INT): INT;
11-begin
12- seed := (seed * 1103515245 + 12345) & 7FFFFFFFH;
13- return INT((seed shr 8) mod I64(n));
14-end;
15-
16-(* a register *)
17-proc reg: INT;
18-begin
19- return rnd(16);
20-end;
21-
22-(* a size of 1, 2, 4 or 8 bytes *)
23-proc size: INT;
24-begin
25- return 1 shl rnd(4);
26-end;
27-
28-(* a value that fits sz bytes, of 8 as 32 bits *)
29-proc imm(sz: INT): INT;
30-var x, r: INT;
31-begin
32- x := rnd(1 shl 30);
33- match rnd(3) of
34- | 0: r := x mod 100 - 50;
35- | 1: r := x - (1 shl 29);
36- | else: r := x mod 20000 - 10000;
37- end;
38- if sz = 1 then
39- r := r mod 128;
40- elsif sz = 2 then
41- r := r mod 32768;
42- end;
43- return r;
44-end;
45-
46-proc randMem: X64.Mem;
47-var kind, base, idx, sc, disp, x: INT;
48-begin
49- kind := rnd(6);
50- base := reg(); idx := reg(); sc := 1 shl rnd(4); x := rnd(5);
51- match x of
52- | 0: disp := 0;
53- | 1: disp := rnd(250) - 125;
54- | 2: disp := rnd(1 shl 20) - (1 shl 19);
55- | 3: disp := 127 + rnd(3) - 1;
56- | else: disp := -128 + rnd(3) - 1;
57- end;
58- match kind of
59- | 0, 1: return X64.mem(base, disp);
60- | 2: return X64.memRip(rnd(5), disp);
61- | 3, 4: return X64.memIdx(base, idx, sc, disp);
62- | else: return X64.mem(base, 0);
63- end;
64-end;
65-
66-proc main*;
67-var
68- i, k, op, a, b, c, d, lab1, lab2: INT; m: X64.Mem; path: []U8;
69-begin
70- seed := 3;
71- path := "lib/Rt.raz";
72- if LEN(Scan.open(path)) # 0 then Diag.fatal("no file"); end;
73- X64.setListing(true);
74- for i := 0 to 4 do c := Chunk.newChunk(Chunk.secText, i - 1, i); end;
75- Chunk.setCurFile(Scan.intern(ADR(path[0]), LEN(path)));
76- Chunk.beginChunk(0);
77- lab1 := X64.NoLabel; lab2 := X64.NoLabel;
78- for k := 1 to 3000 do
79- if k mod 7 = 0 then a := rnd(300); b := rnd(60); Chunk.noteLine(1 + a, b); end;
80- op := rnd(50);
81- match op of
82- | 0: a := reg(); b := reg(); X64.movRR(a, b);
83- | 1:
84- a := reg(); b := rnd(6); c := rnd(1 shl 30);
85- match b of
86- | 0: X64.movRI(a, 0);
87- | 1: X64.movRI(a, c);
88- | 2: X64.movRI(a, -c);
89- | 3: X64.movRI(a, I64(c) * 8 + 5);
90- | 4: X64.movRI(a, I64(c) * 4096 * 4096 * 9 - 7);
91- | else: X64.movRI(a, 0);
92- end;
93- | 2: a := rnd(8); m := randMem(); b := size(); c := imm(b); X64.aluMI(a, m, c, b);
94- | 3: m := randMem(); b := size(); c := imm(b); X64.storeI(m, c, b);
95- | 4: a := reg(); m := randMem(); b := size(); c := rnd(2); X64.load(a, m, b, c = 0);
96- | 5: m := randMem(); a := reg(); b := size(); X64.store(m, a, b);
97- | 6: a := reg(); m := randMem(); X64.lea(a, m);
98- | 7: a := rnd(8); b := reg(); c := reg(); X64.alu(a, b, c);
99- | 8: a := rnd(8); b := reg(); c := imm(8); X64.aluI(a, b, c);
100- | 9: a := rnd(8); b := reg(); m := randMem(); X64.aluM(a, b, m);
101- | 10: a := reg(); b := reg(); X64.imul(a, b);
102- | 11: a := reg(); c := imm(8); X64.imulI(a, c);
103- | 12:
104- a := rnd(3); b := reg();
105- if a = 0 then a := X64.shShl; elsif a = 1 then a := X64.shShr; else a := X64.shSar; end;
106- X64.shift(a, b);
107- | 13:
108- a := rnd(3); b := reg(); c := rnd(64);
109- if a = 0 then a := X64.shShl; elsif a = 1 then a := X64.shShr; else a := X64.shSar; end;
110- X64.shiftI(a, b, c);
111- | 14:
112- a := rnd(4); b := reg();
113- if a < 2 then a := a + 2; else a := a + 4; end;
114- X64.unary(a, b);
115- | 15: X64.cqo;
116- | 16: a := reg(); b := 1 shl rnd(3); c := rnd(2); X64.extend(a, b, c = 0);
117- | 17: a := rnd(16); b := reg(); X64.setCC(a, b);
118- | 18: a := reg(); b := reg(); X64.testRR(a, b);
119- | 19: a := reg(); X64.push(a);
120- | 20: a := reg(); X64.pop(a);
121- | 21: a := rnd(5); X64.callChunk(a);
122- | 22: a := rnd(1000); X64.callBack(a);
123- | 23: a := reg(); X64.callR(a);
124- | 24: a := reg(); X64.jmpR(a);
125- | 25: m := randMem(); X64.callM(m);
126- | 26:
127- a := rnd(5);
128- match a of
129- | 0: X64.ret;
130- | 1: X64.leave;
131- | 2: X64.syscall;
132- | 3: X64.mfence;
133- | else: X64.ud2;
134- end;
135- | 27: a := 8 shl rnd(3); X64.align(a);
136- | 28:
137- a := rnd(5);
138- match a of
139- | 0: X64.repMovsb;
140- | 1: X64.std;
141- | 2: X64.cld;
142- | 3: X64.repStosb;
143- | else: X64.repeCmpsb;
144- end;
145- | 29: m := randMem(); a := reg(); X64.lockCmpxchg(m, a);
146- | 30: m := randMem(); a := reg(); X64.xchg(m, a);
147- | 31: m := randMem(); a := reg(); X64.lockXadd(m, a);
148- | 32: a := reg(); b := reg(); X64.movqXR(a, b);
149- | 33: a := reg(); b := reg(); X64.movqRX(a, b);
150- | 34: a := reg(); b := reg(); X64.movX(a, b);
151- | 35: a := reg(); m := randMem(); b := rnd(2); X64.movsXM(a, m, b = 0);
152- | 36: m := randMem(); a := reg(); b := rnd(2); X64.movsMX(m, a, b = 0);
153- | 37:
154- d := rnd(5); a := reg(); b := reg(); c := rnd(2);
155- match d of
156- | 0: d := 58H;
157- | 1: d := 59H;
158- | 2: d := 5CH;
159- | 3: d := 5EH;
160- | else: d := 5AH;
161- end;
162- X64.sse(d, a, b, c = 0);
163- | 38:
164- d := rnd(5); a := reg(); m := randMem(); c := rnd(2);
165- match d of
166- | 0: d := 58H;
167- | 1: d := 59H;
168- | 2: d := 5CH;
169- | 3: d := 5EH;
170- | else: d := 5AH;
171- end;
172- X64.sseM(d, a, m, c = 0);
173- | 39: a := reg(); b := reg(); c := rnd(2); X64.ucomis(a, b, c = 0);
174- | 40: a := reg(); b := reg(); c := rnd(2); X64.cvtsi2s(a, b, c = 0);
175- | 41: a := reg(); b := reg(); c := rnd(2); X64.cvtts2si(a, b, c = 0);
176- | 42: a := reg(); b := rnd(64); X64.btc(a, b);
177- | 43:
178- a := rnd(16); b := rnd(2);
179- if b = 0 then X64.jmp(lab1); else X64.jcc(a, lab2); end;
180- | 44:
181- a := rnd(16); b := rnd(2); c := Chunk.pc - rnd(200);
182- if b = 0 then X64.jmpBack(c); else X64.jccBack(a, c); end;
183- | 45:
184- a := rnd(3);
185- if a = 0 then
186- X64.fixLink(lab1); lab1 := X64.NoLabel;
187- else
188- X64.fixLinkTo(lab2, Chunk.pc - 20); lab2 := X64.NoLabel;
189- end;
190- | 46: X64.jmp(lab1); X64.dropJumpTo(lab1);
191- | 47: a := X64.joinLinks(lab1, lab2); lab1 := a; lab2 := X64.NoLabel;
192- | else: a := rnd(256); Chunk.put1(a);
193- end;
194- end;
195- X64.fixLink(lab1); X64.fixLink(lab2);
196- Chunk.endChunk(0);
197- Chunk.setLive(0);
198- Fmt.print("pc {} fixups {} lines {} said {}\n", [Fmt.int(Chunk.pc), Fmt.int(Chunk.numFixups),
199- Fmt.int(Chunk.numLines), Fmt.int(X64.saidCount())]);
200- for i := 0 to Chunk.pc - 1 do Out.hex(U64(Chunk.text[i]), 2); end;
201- Out.ln;
202- for i := 0 to Chunk.numFixups - 1 do
203- Fmt.print("F {} {} {}\n", [Fmt.int(Chunk.fixups[i].at), Fmt.int(Chunk.fixups[i].chunk), Fmt.int(Chunk.fixups[i].addend)]);
204- end;
205- X64.list(-1);
206-end;
207-
208-end X64Dump.

self/test/genasm.py deleted +0 -244

@@ -1,244 +0,0 @@
1-#!/usr/bin/env python3
2-"""Writes the files the assembler of X64 is tested on, into the directory
3-given: valid.raz, a long run of instructions of every kind the assembler
4-knows, and one small file for each error it reports. Each ends in `end`,
5-as a code procedure's body does. Fixed seed: the same files each run."""
6-import random, sys, os
7-
8-random.seed(7)
9-out = sys.argv[1]
10-os.makedirs(out, exist_ok=True)
11-
12-R64 = "rax rcx rdx rbx rsp rbp rsi rdi r8 r9 r10 r11 r12 r13 r14 r15".split()
13-R32 = "eax ecx edx ebx esp ebp esi edi r8d r9d r10d r11d r12d r13d r14d r15d".split()
14-R16 = "ax cx dx bx sp bp si di r8w r9w r10w r11w r12w r13w r14w r15w".split()
15-R8 = "al cl dl bl spl bpl sil dil r8b r9b r10b r11b r12b r13b r14b r15b".split()
16-BY = {8: R64, 4: R32, 2: R16, 1: R8}
17-PRE = {8: "qword ", 4: "dword ", 2: "word ", 1: "byte "}
18-XM = ["xmm%d" % i for i in range(16)]
19-CC = "o no b ae e ne be a s ns p np l ge le g c nae nc nb z nz na nbe nge nl ng nle".split()
20-
21-
22-def reg(size=8):
23- return random.choice(BY[size])
24-
25-
26-def mem(size=0):
27- k = random.randrange(8)
28- b = random.choice(R64)
29- i = random.choice([r for r in R64 if r != "rsp"])
30- d = random.choice([0, 8, -8, 127, -128, 128, 4096, -4096, 100000])
31- s = random.choice([1, 2, 4, 8])
32- p = PRE[size] if size else ""
33- if k == 0:
34- t = "[%s]" % b
35- elif k == 1:
36- t = "[%s + %d]" % (b, abs(d)) if d >= 0 else "[%s - %d]" % (b, -d)
37- elif k == 2:
38- t = "[%s + %s * %d]" % (b, i, s)
39- elif k == 3:
40- t = "[%s + %s * %d + %d]" % (b, i, s, abs(d)) if d >= 0 else "[%s + %s * %d - %d]" % (b, i, s, -d)
41- elif k == 4:
42- t = "[%s + %s]" % (b, i)
43- elif k == 5:
44- t = "[%s + 0]" % b
45- elif k == 6:
46- t = "[rsp + %d]" % abs(d)
47- else:
48- t = "[%s - %d]" % (b, abs(d) + 1)
49- return p + t
50-
51-
52-def imm(size):
53- if size == 1:
54- return str(random.choice([0, 1, -1, 127, 255, -128, 77]))
55- if size == 2:
56- return str(random.choice([0, 1, -1, 300, 32767, -32768, 255, 65535]))
57- return str(random.choice([0, 1, -1, 127, 128, -128, -129, 100000, -100000, 2147483647, -2147483648, 4294967295]))
58-
59-
60-def size():
61- return random.choice([1, 2, 4, 8])
62-
63-
64-lines = []
65-
66-
67-def emit(s):
68- lines.append(" " + s + ";")
69-
70-
71-for n in range(900):
72- k = random.randrange(40)
73- sz = size()
74- if k < 6:
75- op = random.choice("add or adc sbb and sub xor cmp".split())
76- f = random.randrange(5)
77- if f == 0:
78- emit("%s %s, %s" % (op, reg(sz), reg(sz)))
79- elif f == 1:
80- emit("%s %s, %s" % (op, reg(sz), mem(sz if random.random() < .5 else 0)))
81- elif f == 2:
82- emit("%s %s, %s" % (op, mem(sz if random.random() < .5 else 0), reg(sz)))
83- elif f == 3:
84- emit("%s %s, %s" % (op, reg(sz), imm(sz)))
85- else:
86- emit("%s %s, %s" % (op, mem(sz), imm(sz)))
87- elif k < 10:
88- f = random.randrange(5)
89- if f == 0:
90- emit("mov %s, %s" % (reg(sz), reg(sz)))
91- elif f == 1:
92- emit("mov %s, %s" % (reg(sz), mem()))
93- elif f == 2:
94- emit("mov %s, %s" % (mem(), reg(sz)))
95- elif f == 3:
96- v = random.choice([0, 5, -5, 2147483647, 4294967295, 4294967296, -2147483649, 123456789012345])
97- emit("mov %s, %d" % (reg(8 if sz >= 4 else sz) if sz >= 4 else reg(sz), v if sz == 8 else (v % 65536 if sz == 2 else v % 256 if sz == 1 else v % 4294967296)))
98- else:
99- emit("mov %s, %s" % (mem(sz), imm(sz)))
100- elif k == 10:
101- emit("test %s, %s" % (reg(sz), random.choice([reg(sz), imm(sz) if sz != 1 else "1"])))
102- elif k == 11:
103- emit("xchg %s, %s" % (random.choice([reg(sz), mem()]), reg(sz)))
104- elif k == 12:
105- emit("%slock %s %s, %s" % ("", random.choice(["cmpxchg", "xadd"]), mem(), reg(sz)))
106- elif k == 13:
107- emit("lea %s, %s" % (reg(random.choice([2, 4, 8])), mem()))
108- elif k == 14:
109- op = random.choice(["movzx", "movsx"])
110- emit("%s %s, %s" % (op, reg(random.choice([2, 4, 8])), random.choice([mem(random.choice([1, 2])), reg(random.choice([1, 2]))])))
111- elif k == 15:
112- emit("movsxd %s, %s" % (reg(8), random.choice([mem(4), reg(4)])))
113- elif k == 16:
114- emit("%s %s" % (random.choice("not neg mul imul div idiv inc dec".split()), random.choice([reg(sz), mem(sz)])))
115- elif k == 17:
116- emit("imul %s" % ", ".join([reg(sz if sz > 1 else 4), random.choice([reg(sz if sz > 1 else 4)] * 1 + [mem()])] + ([imm(sz if sz > 1 else 4)] if random.random() < .4 else [])).replace("%", "%"))
117- elif k == 18:
118- op = random.choice("rol ror rcl rcr shl shr sal sar".split())
119- emit("%s %s, %s" % (op, random.choice([reg(sz), mem(sz)]), random.choice([str(random.randrange(64)), "cl"])))
120- elif k == 19:
121- emit("%s %s" % (random.choice(["push", "pop"]), reg(8)))
122- elif k == 20:
123- op = random.choice(["call", "jmp"])
124- emit("%s %s" % (op, random.choice([reg(8), mem()]) if op == "call" else mem()))
125- elif k == 21:
126- emit("set%s %s" % (random.choice(CC), random.choice([reg(1), mem(1)])))
127- elif k == 22:
128- emit("cmov%s %s, %s" % (random.choice(CC), reg(random.choice([2, 4, 8])), random.choice([reg(8), mem()])))
129- elif k == 23:
130- op = random.choice("sqrt add mul sub min div max".split()) + random.choice(["sd", "ss"])
131- emit("%s %s, %s" % (op, random.choice(XM), random.choice([random.choice(XM), mem()])))
132- elif k == 24:
133- op = random.choice("punpcklbw punpcklwd pcmpeqb pand pandn por pxor paddb psubb".split())
134- emit("%s %s, %s" % (op, random.choice(XM), random.choice([random.choice(XM), mem()])))
135- elif k == 25:
136- emit("pshufd %s, %s, %d" % (random.choice(XM), random.choice([random.choice(XM), mem()]), random.randrange(256)))
137- elif k == 26:
138- op = random.choice(["movdqu", "movdqa"])
139- if random.random() < .5:
140- emit("%s %s, %s" % (op, random.choice(XM), random.choice([random.choice(XM), mem()])))
141- else:
142- emit("%s %s, %s" % (op, mem(), random.choice(XM)))
143- elif k == 27:
144- emit("pmovmskb %s, %s" % (reg(4), random.choice(XM)))
145- elif k == 28:
146- emit("%s %s, %s" % (random.choice("bsf bsr tzcnt lzcnt popcnt".split()), reg(random.choice([4, 8])), random.choice([reg(8), mem()])))
147- elif k == 29:
148- op = random.choice(["movsd", "movss"])
149- if random.random() < .5:
150- emit("%s %s, %s" % (op, random.choice(XM), random.choice([random.choice(XM), mem()])))
151- else:
152- emit("%s %s, %s" % (op, mem(), random.choice(XM)))
153- elif k == 30:
154- op = random.choice(["movq", "movd"])
155- if random.random() < .5:
156- emit("%s %s, %s" % (op, random.choice(XM), random.choice([reg(8), mem()])))
157- else:
158- emit("%s %s, %s" % (op, random.choice([reg(8), mem()]), random.choice(XM)))
159- elif k == 31:
160- emit("%s %s, %s" % (random.choice(["ucomisd", "ucomiss"]), random.choice(XM), random.choice([random.choice(XM), mem()])))
161- elif k == 32:
162- emit("%s %s, %s" % (random.choice(["cvtsi2sd", "cvtsi2ss"]), random.choice(XM), random.choice([reg(random.choice([4, 8])), mem(random.choice([4, 8]))])))
163- elif k == 33:
164- emit("%s %s, %s" % (random.choice(["cvttsd2si", "cvttss2si"]), reg(random.choice([4, 8])), random.choice([random.choice(XM), mem()])))
165- elif k == 34:
166- emit("%s %s, %s" % (random.choice(["cvtsd2ss", "cvtss2sd"]), random.choice(XM), random.choice([random.choice(XM), mem()])))
167- elif k == 35:
168- emit(random.choice("ret leave syscall cpuid rdtsc pause nop ud2 int3 hlt cqo cdq mfence lfence sfence".split()))
169- elif k == 36:
170- emit("db " + ", ".join(str(random.choice([0, 1, 255, 128, 77, -1, -128])) for _ in range(random.randrange(1, 6))))
171- elif k == 37:
172- lines.append(" L%d:" % n)
173- lines.append(" add rax, 1;")
174- lines.append(" j%s L%d;" % (random.choice(CC), n))
175- lines.append(" jmp L%d;" % n)
176- elif k == 38:
177- lines.append(" jmp F%d;" % n)
178- lines.append(" nop;")
179- lines.append(" j%s F%d;" % (random.choice(CC), n))
180- lines.append(" F%d:" % n)
181- else:
182- emit("lock add %s, %s" % (mem(sz), reg(sz)))
183-
184-open(os.path.join(out, "valid.raz"), "w").write("\n".join(lines) + "\n end\n")
185-
186-errors = {
187- "empty": "",
188- "badop": "foo rax;",
189- "noinsn": "42;",
190- "nosemi": "nop",
191- "undefined": "jmp nowhere;",
192- "twice": "a: nop; a: nop;",
193- "toomany": "add rax, rbx, rcx, rdx;",
194- "movimm": "mov 1, 2;",
195- "movmm": "mov [rax], [rbx];",
196- "addimm": "add 1, rax;",
197- "pushmem": "push [rax];",
198- "pushsmall": "push eax;",
199- "badmem": "mov rax, [rsi * 4];",
200- "badscale": "mov rax, [rsi + rdi * 3];",
201- "nomem": "mov rax, [];",
202- "unclosed": "mov rax, [rbx;",
203- "shiftcl": "shl rax, dl;",
204- "shiftimm": "shl 3, 1;",
205- "lea": "lea rax, rbx;",
206- "movzx": "movzx rax, rbx;",
207- "movzx4": "movzx rax, dword [rbx];",
208- "setsize": "sete rax;",
209- "cmovimm": "cmove rax, 5;",
210- "sse": "addsd rax, xmm1;",
211- "sse1": "addsd xmm1;",
212- "pshufd": "pshufd xmm1, xmm2;",
213- "pand3": "pand xmm1, xmm2, 3;",
214- "movdq": "movdqu rax, xmm1;",
215- "pmov": "pmovmskb xmm1, rax;",
216- "bits": "popcnt ax, bx;",
217- "movsd": "movsd rax, xmm1;",
218- "movq": "movq rax, rbx;",
219- "ucomi": "ucomisd rax, xmm1;",
220- "cvtsi": "cvtsi2sd rax, xmm1;",
221- "cvtt": "cvttsd2si xmm1, xmm2;",
222- "cvtss": "cvtss2sd rax, xmm1;",
223- "plainops": "ret rax;",
224- "dbrange": "db 256;",
225- "dbneg": "db -129;",
226- "imul1": "imul rax, 5;",
227- "imulmem": "imul [rax], rbx;",
228- "unary2": "not rax, rbx;",
229- "unaryimm": "neg 5;",
230- "inc": "inc 5;",
231- "xchgimm": "xchg rax, 5;",
232- "cmpxchg": "cmpxchg rax, 5;",
233- "calli": "call 5;",
234- "jmpimm": "jmp 5;",
235- "labels65": "".join("l%d: nop; " % i for i in range(65)),
236- "xmm16": "addsd xmm16, xmm1;",
237- "noend": None,
238-}
239-for name, body in errors.items():
240- if body is None:
241- text = " nop;\n"
242- else:
243- text = " " + body + "\n end\n"
244- open(os.path.join(out, "err_%s.raz" % name), "w").write(text)

self/test/genlex.py deleted +0 -29

@@ -1,29 +0,0 @@
1-# Writes into the directory given a file for each message the scanner
2-# makes, with the places diag shows them in: after a tab, in a long
3-# line, after characters of several bytes, in a CRLF file.
4-import sys
5-d = sys.argv[1]
6-cases = {
7- "slip1": "x == y;\n", "slip2": "a && b;\n", "slip3": "a || b;\n", "slip4": "a != b;\n", "slip5": "!a;\n",
8- "str": "x := \"abc\n", "chr": "x := 'a\n", "chr2": "x := 'ab';\n", "chr3": "x := '';\n",
9- "esc": "x := \"\\q\";\n", "esc2": "x := 'a\\x41';\n", "esc3": "x := \"\\x4\";\n",
10- "esc4": "x := \"\\u41\";\n", "esc5": "x := \"\\u{110000}\";\n", "esc6": "x := \"\\u{D800}\";\n",
11- "esc7": "x := \"\\u{1234567}\";\n", "esc8": "x := \"\\u{}\";\n", "esc9": "x := \"\\u{41\";\n",
12- "esc10": "x := \"\\u{1F600}\\u{e9}\\x00\\xff\\n\\t\\r\\0\\\\\\'\\\"\";\n",
13- "cmt": "x := 1; (* open (* nested *)\n", "nul": "x := 1;\0 y;\n", "hexbad": "x := 12AB;\n",
14- "hexbig": "x := 1FFFFFFFFFFFFFFFFH;\n", "hexok": "x := 0FFFFFFFFFFFFFFFFH; y := 7FFFFFFFFFFFFFFFH;\n",
15- "decbig": "x := 9223372036854775808;\n", "decmax": "x := 9223372036854775807;\n",
16- "realhex": "x := 1A.5;\n", "realexp": "x := 1.5E;\n", "realexp2": "x := 1.5E+;\n", "realbig": "x := 1.0E309;\n",
17- "realmax": "x := 1.7976931348623159E308;\n", "reallong": "x := " + "1" * 254 + ".5;\n",
18- "digname": "x := 12abc;\n", "uni": "x := \u00e9;\n", "badutf": b"x := \"a\xc3(\";\n", "badutf2": b"x := \"\xed\xa0\x80\";\n",
19- "badutf3": b"x := \"\xc0\x80\";\n", "badutf4": b"x := \"\xf5\x80\x80\x80\";\n", "badutf5": b"x := \"\xe2\x82\";\n",
20- "okutf": "x := \"h\u00e9llo \u20ac \U0001F600\"; y := '\u00e9'; (* \u00e9 *)\n",
21- "unexp": "x := @;\n", "long": "x := " + "a + " * 60 + "@;\n", "longmid": "x := " + "a + " * 40 + "@ " + "+ b" * 40 + ";\n",
22- "tab": "\t\tx := @;\n", "multi": "x := \"\u00e9\u00e9\u00e9\" + @;\n", "ident64": "x" * 64 + ";\n", "ident63": "x" * 63 + ";\n",
23- "bigstr": "x := \"" + "a" * 70000 + "\";\n", "empty": "", "nonl": "x := y",
24- "ops": "+ - * / = # < <= > >= := : ; , . .. ... ( ) [ ] { } ^ & ~ | _ __ _a\n",
25- "words": "and begin break by code const defer div do else elsif end extern for forward if import in link match mod module not of or packed proc record repeat return set shl shr then to try type until var variant VOLATILE while xor Volatile\n",
26-}
27-for k, v in cases.items():
28- open(f"{d}/{k}.raz", "wb").write(v.encode("utf-8", "surrogateescape") if isinstance(v, str) else v)
29-open(f"{d}/crlf.raz", "wb").write(b"x := 1;\r\ny := @;\r\n")

self/test/genreals.py deleted +0 -19

@@ -1,19 +0,0 @@
1-# Prints a raz module of reals that are hard to read exactly: the
2-# extremes, halves between neighbours, and many random ones.
3-import random
4-random.seed(7)
5-v = ["0.0", "1.0", "0.1", "4.9E-324", "2.4703282292062327E-324", "2.4703282292062328E-324",
6- "2.2250738585072014E-308", "2.2250738585072011E-308", "1.7976931348623157E308",
7- "9007199254740993.0", "9007199254740992.5", "9007199254740993.5", "0.000001E+3",
8- "123456789012345678901234567890.0E-10", "1.0E-400", "0.5E1", "5.0E-1"]
9-for _ in range(3000):
10- d = random.randint(1, 10 ** random.randint(1, 30))
11- e = random.randint(-320, 300)
12- s = str(d)
13- v.append(s[0] + "." + (s[1:] or "0") + "E" + ("%+d" % e if random.random() < .5 else str(e)))
14-for _ in range(500):
15- v.append("%d.%d" % (random.randint(0, 10 ** 6), random.randint(0, 10 ** 12)))
16-print("module Reals;\nvar x: F64;\nbegin")
17-for s in v:
18- print(" x := " + s + ";")
19-print("end Reals.")

src/Chunk.raz (history) added +354 -0

@@ -0,0 +1,354 @@
1+(* Chunk: the compiled program, before it is linked.
2+
3+ The code of a program is a set of chunks: one per procedure, module
4+ variable and string. A chunk's bytes go in one of three sections:
5+ text (code), rodata (strings and other constants), bss (variables,
6+ which are all zero). A reference from code to another chunk (a call,
7+ or an address) is a fixup, patched once the linker has placed every
8+ chunk. Line notes say which place in the source the code from each
9+ point on is for.
10+
11+ Nothing here depends on the machine: text is bytes, written by the
12+ encoder for the target (X64).
13+
14+ Depends on: Scan, for names and memory; Diag, for positions.
15+ Leaves out: the instructions; that is X64.
16+
17+ Exported variables can't be set from outside, so the setters at the
18+ end do what the seed's other units do to these. *)
19+module Chunk;
20+import Fmt, Diag, Scan;
21+
22+type
23+ Section* = (secText, secRodata, secBss);
24+
25+ Chunk* = record
26+ sec*: Section;
27+ start*, size*, align*: INT; (* in its section's buffer *)
28+ firstFix*, numFix*: INT; (* its fixups: text's in fixups, rodata's in dataFixups *)
29+ home*, name*: INT; (* its module and its name, for the symbol table; -1 if none *)
30+ adr*: INT; (* its address, set by the linker *)
31+ live*: BOOL; (* reached from the entry point *)
32+ ext*: BOOL; (* bss: the address of a C symbol, its name *)
33+ reals*: BOOL; (* code: computes with reals, first at realsAt *)
34+ realsAt*: Diag.Pos;
35+ saveMask*: INT; (* code: the registers of variables it saves, as bits of Gen's VarRegs *)
36+ saveAt*: INT; (* ... at this offset from the frame, one quadword each *)
37+ end;
38+
39+ (* A place in the source whose code starts at a place in text: for
40+ gdb, and for Rt to say where a failed check or a signal was *)
41+ Line* = record
42+ at*, chunk*: INT; (* the place in text, and its chunk *)
43+ path*, line*, col*: INT; (* the file's path, interned, the line and column *)
44+ end;
45+
46+ (* A variable of a procedure, for the trap report: Rt shows it, by
47+ kind, from its place in the frame *)
48+ VarNote* = record
49+ chunk*, name*: INT;
50+ off*: INT; (* from the frame pointer *)
51+ kind*: INT; (* how Rt shows it: see Link *)
52+ end;
53+
54+ Fixup* = record
55+ at*: INT; (* the 32-bit field, as an offset in text; in
56+ dataFixups, the 64-bit one, from its chunk's start *)
57+ chunk*: INT; (* the chunk it refers to *)
58+ addend*: INT; (* added to the chunk's address *)
59+ end;
60+
61+var
62+ text*: ^U8; (* text *)
63+ pc*: INT; (* its length *)
64+ rodata*: ^U8;
65+ rolen*: INT;
66+ chunks*: ^Chunk;
67+ numChunks*: INT;
68+ fixups*: ^Fixup;
69+ numFixups*: INT;
70+ (* Addresses in read-only data, as in an array constant of strings:
71+ each 8 bytes, the chunk's absolute address, since the executable
72+ is loaded where the linker placed it *)
73+ dataFixups*: ^Fixup;
74+ numDataFixups*: INT;
75+ lines*: ^Line;
76+ numLines*: INT;
77+ curFile: INT; (* the file being compiled, for noteLine *)
78+ curChunk*: INT; (* the chunk of code being written *)
79+ varNotes*: ^VarNote;
80+ numVarNotes*: INT;
81+
82+ codeCap, roCap, chunkCap, fixCap, dataFixCap, lineCap, noteCap: INT;
83+
84+(* Room for n more bytes of code *)
85+proc room(n: INT);
86+begin
87+ if pc + n > codeCap then
88+ text := Scan.regrab(text, pc, codeCap * 2 + n);
89+ codeCap := codeCap * 2 + n;
90+ end;
91+end;
92+
93+proc put1*(b: INT);
94+begin
95+ if pc + 16 > codeCap then room(16); end;
96+ text[pc] := U8(b & 0FFH);
97+ INC(pc);
98+end;
99+
100+(* The low 32 bits of v, least significant byte first *)
101+proc put4*(v: INT);
102+var i: INT;
103+begin
104+ if pc + 16 > codeCap then room(16); end;
105+ for i := 0 to 3 do text[pc + i] := U8((v shr (8 * i)) & 0FFH); end;
106+ INC(pc, 4);
107+end;
108+
109+proc put4At*(at, v: INT);
110+var i: INT;
111+begin
112+ for i := 0 to 3 do text[at + i] := U8((v shr (8 * i)) & 0FFH); end;
113+end;
114+
115+(* The 32 bits at at, as a signed number *)
116+proc get4At*(at: INT): INT;
117+var u, i: INT;
118+begin
119+ u := 0;
120+ for i := 0 to 3 do u := u * 256 + INT(text[at + 3 - i]); end;
121+ if u >= 80000000H then u := u - 100000000H; end;
122+ return u;
123+end;
124+
125+(* The last n bytes of code taken back. A line noted past the new end
126+ now starts there, in place of one noted there before, as noteLine
127+ would have it. *)
128+proc takeBack*(n: INT);
129+begin
130+ DEC(pc, n);
131+ if (numLines > 0) and (lines[numLines - 1].at > pc) then
132+ lines[numLines - 1].at := pc;
133+ if (numLines > 1) and (lines[numLines - 2].at = pc) then
134+ lines[numLines - 2] := lines[numLines - 1];
135+ DEC(numLines);
136+ end;
137+ end;
138+end;
139+
140+proc put8*(v: I64);
141+begin
142+ put4(INT(v & 0FFFFFFFFH));
143+ put4(INT((v shr 32) & 0FFFFFFFFH));
144+end;
145+
146+proc newChunk*(sec: Section; home, name: INT): INT;
147+var c: ^Chunk;
148+begin
149+ if numChunks = chunkCap then
150+ chunks := ^Chunk(Scan.regrab(^U8(chunks), numChunks * SIZE(Chunk), chunkCap * 2 * SIZE(Chunk)));
151+ chunkCap := chunkCap * 2;
152+ end;
153+ c := ADR(chunks[numChunks]);
154+ c^ := {};
155+ c^.sec := sec;
156+ c^.home := home;
157+ c^.name := name;
158+ c^.align := 1;
159+ c^.size := -1; (* not yet defined *)
160+ INC(numChunks);
161+ return numChunks - 1;
162+end;
163+
164+proc beginChunk*(c: INT);
165+begin
166+ (* code is aligned to 32 bytes, the windows in which x86 fetches and
167+ caches it, so that a procedure's loops sit in them the same way
168+ whatever comes before: rat ran 5% slower at 16, by where its loops
169+ fell. Padded with CC, x86's int3: a trap if it were ever run *)
170+ while pc & 31 # 0 do put1(0CCH); end;
171+ curChunk := c;
172+ chunks[c].start := pc;
173+ chunks[c].align := 32;
174+ chunks[c].firstFix := numFixups;
175+end;
176+
177+proc endChunk*(c: INT);
178+begin
179+ chunks[c].size := pc - chunks[c].start;
180+ chunks[c].numFix := numFixups - chunks[c].firstFix;
181+end;
182+
183+(* The n bytes at p are the data of rodata chunk c *)
184+proc setData*(c: INT; p: ^U8; n, align: INT);
185+begin
186+ if rolen + n > roCap then
187+ rodata := Scan.regrab(rodata, rolen, roCap * 2 + n);
188+ roCap := roCap * 2 + n;
189+ end;
190+ COPY(rodata[rolen..rolen + n], p[0..n]);
191+ chunks[c].firstFix := numDataFixups;
192+ chunks[c].numFix := 0;
193+ chunks[c].start := rolen;
194+ chunks[c].size := n;
195+ chunks[c].align := align;
196+ INC(rolen, n);
197+end;
198+
199+proc setBss*(c: INT; size, align: INT);
200+begin
201+ chunks[c].size := size;
202+ chunks[c].align := align;
203+end;
204+
205+(* The code from here on is for line and column of the current file. A
206+ place with no code of its own gives way to the next. *)
207+proc noteLine*(line, col: INT);
208+begin
209+ if (numLines > 0) and (lines[numLines - 1].at = pc) then DEC(numLines); end;
210+ if (numLines > 0) and (lines[numLines - 1].chunk = curChunk) and (lines[numLines - 1].line = line)
211+ and (lines[numLines - 1].col = col) and (lines[numLines - 1].path = curFile) then
212+ return;
213+ end;
214+ if numLines = lineCap then
215+ lines := ^Line(Scan.regrab(^U8(lines), numLines * SIZE(Line), lineCap * 2 * SIZE(Line)));
216+ lineCap := lineCap * 2;
217+ end;
218+ lines[numLines].at := pc;
219+ lines[numLines].chunk := curChunk;
220+ lines[numLines].path := curFile;
221+ lines[numLines].line := line;
222+ lines[numLines].col := col;
223+ INC(numLines);
224+end;
225+
226+(* The quadword that holds the address of C's symbol name, filled in
227+ when the program starts; one for each name. *)
228+proc externChunk*(name: INT): INT;
229+var c: INT;
230+begin
231+ for c := 0 to numChunks - 1 do
232+ if chunks[c].ext and (chunks[c].name = name) then return c; end;
233+ end;
234+ c := newChunk(secBss, -1, name);
235+ setBss(c, 8, 8);
236+ chunks[c].ext := true;
237+ return c;
238+end;
239+
240+proc addFixup*(at, chunk, addend: INT);
241+begin
242+ if numFixups = fixCap then
243+ fixups := ^Fixup(Scan.regrab(^U8(fixups), numFixups * SIZE(Fixup), fixCap * 2 * SIZE(Fixup)));
244+ fixCap := fixCap * 2;
245+ end;
246+ fixups[numFixups].at := at;
247+ fixups[numFixups].chunk := chunk;
248+ fixups[numFixups].addend := addend;
249+ INC(numFixups);
250+end;
251+
252+(* The address of chunk, plus addend, at offset at of rodata chunk c,
253+ whose data is set: its fixups follow one another. *)
254+proc addDataFixup*(c, at, chunk, addend: INT);
255+begin
256+ if numDataFixups = dataFixCap then
257+ dataFixups := ^Fixup(Scan.regrab(^U8(dataFixups), numDataFixups * SIZE(Fixup), dataFixCap * 2 * SIZE(Fixup)));
258+ dataFixCap := dataFixCap * 2;
259+ end;
260+ dataFixups[numDataFixups].at := at;
261+ dataFixups[numDataFixups].chunk := chunk;
262+ dataFixups[numDataFixups].addend := addend;
263+ INC(numDataFixups);
264+ INC(chunks[c].numFix);
265+end;
266+
267+proc noteVar*(chunk, name, off, kind: INT);
268+begin
269+ if numVarNotes = noteCap then
270+ varNotes := ^VarNote(Scan.regrab(^U8(varNotes), numVarNotes * SIZE(VarNote), noteCap * 2 * SIZE(VarNote)));
271+ noteCap := noteCap * 2;
272+ end;
273+ varNotes[numVarNotes].chunk := chunk;
274+ varNotes[numVarNotes].name := name;
275+ varNotes[numVarNotes].off := off;
276+ varNotes[numVarNotes].kind := kind;
277+ INC(numVarNotes);
278+end;
279+
280+(* The name of chunk c: its module's and its own, or literal and its
281+ number for a literal *)
282+proc chunkName*(c: INT): []U8;
283+begin
284+ if chunks[c].name < 0 then return Diag.say("literal{}", [Fmt.int(c)]); end;
285+ if chunks[c].home < 0 then return Scan.nameOf(chunks[c].name); end;
286+ return Diag.say("{}.{}", [Fmt.str(Scan.nameOf(chunks[c].home)), Fmt.str(Scan.nameOf(chunks[c].name))]);
287+end;
288+
289+(* What Gen's Redo and Rewind put back: the code, fixups and lines made
290+ since are forgotten *)
291+proc rewindTo*(atPc, atFixups, atLines: INT);
292+begin
293+ pc := atPc;
294+ numFixups := atFixups;
295+ numLines := atLines;
296+end;
297+
298+(* The file the code is being made from, as its path interned *)
299+proc setCurFile*(path: INT);
300+begin
301+ curFile := path;
302+end;
303+
304+proc curFilePath*: INT;
305+begin
306+ return curFile;
307+end;
308+
309+proc setLive*(c: INT);
310+begin
311+ chunks[c].live := true;
312+end;
313+
314+proc setAdr*(c: INT; a: INT);
315+begin
316+ chunks[c].adr := a;
317+end;
318+
319+(* Chunk c computes with reals, the first of them at p *)
320+proc setReals*(c: INT; p: Diag.Pos);
321+begin
322+ chunks[c].reals := true;
323+ chunks[c].realsAt := p;
324+end;
325+
326+proc setSaves*(c, mask, at: INT);
327+begin
328+ chunks[c].saveMask := mask;
329+ chunks[c].saveAt := at;
330+end;
331+
332+begin
333+ codeCap := 1 shl 20;
334+ text := Scan.grab(codeCap);
335+ pc := 0;
336+ roCap := 1 shl 16;
337+ rodata := Scan.grab(roCap);
338+ rolen := 0;
339+ chunkCap := 1 shl 10;
340+ chunks := ^Chunk(Scan.grab(chunkCap * SIZE(Chunk)));
341+ numChunks := 0;
342+ fixCap := 1 shl 12;
343+ fixups := ^Fixup(Scan.grab(fixCap * SIZE(Fixup)));
344+ numFixups := 0;
345+ dataFixCap := 1 shl 8;
346+ dataFixups := ^Fixup(Scan.grab(dataFixCap * SIZE(Fixup)));
347+ numDataFixups := 0;
348+ lineCap := 1 shl 12;
349+ lines := ^Line(Scan.grab(lineCap * SIZE(Line)));
350+ numLines := 0;
351+ noteCap := 1 shl 8;
352+ varNotes := ^VarNote(Scan.grab(noteCap * SIZE(VarNote)));
353+ numVarNotes := 0;
354+end Chunk.

src/Diag.raz (history) added +410 -0

@@ -0,0 +1,410 @@
1+(* Diag: messages.
2+
3+ The one place the compiler's messages are made. A message is an
4+ error or a warning at a position, which it shows as the file, line
5+ and column, then the line of source with the position underlined;
6+ notes, each at a position of its own, and help, a line of advice,
7+ may follow it. Colour is used when standard error is a terminal and
8+ NO_COLOR isn't set. Diag keeps every source file it is given, so
9+ that a note can show a line of a module compiled earlier.
10+
11+ Depends on: Sys, to write and to ask about the terminal; Buf and Fmt,
12+ to build what it writes.
13+ Leaves out: wording. The callers say what is wrong, with say; a
14+ message is at most 255 characters, which every message so far keeps
15+ well within. A message made by say is kept for good, since it is
16+ made only where it is about to be shown. *)
17+module Diag;
18+import Sys, Rt, Heap, Mem, Buf, Fmt, Str;
19+
20+type
21+ (* A stretch of a source file: bytes a up to but not including b.
22+ a = b marks the place between two characters. *)
23+ Pos* = record f*, a*, b*: INT; end;
24+
25+ File = record
26+ path: []U8;
27+ buf: ^U8;
28+ len: INT;
29+ end;
30+
31+const
32+ MaxErrors* = 20;
33+ Bold = "\x1B[1m"; Red = "\x1B[1;31m"; Yellow = "\x1B[1;33m";
34+ Cyan = "\x1B[1;36m"; Green = "\x1B[1;32m"; Blue = "\x1B[1;34m";
35+ Plain = "\x1B[0m";
36+ (* A long line is shown cut to this many bytes around the place, its
37+ cut ends marked ... *)
38+ ShownBytes = 100;
39+
40+var
41+ errors*, warnings*: INT;
42+ werror*: BOOL; (* -Werror: a warning counts as an error *)
43+ (* The construct being read uses a name already reported as not
44+ declared: its errors follow from that one, and aren't shown. *)
45+ quiet*: BOOL;
46+
47+ files: ^File; (* numFiles of them, in room for cap *)
48+ numFiles, cap: INT;
49+ colour, colourKnown, cwdKnown: BOOL;
50+ cwd: Buf.Buf; (* the working directory and a /, or empty if unknown *)
51+ out: Buf.Buf; (* the message being made *)
52+ lastError: Pos; (* where the last error was *)
53+ shown: BOOL; (* whether it was shown: its notes and help are only then *)
54+
55+(* Exported variables can't be set from outside, so these do it. *)
56+proc setWerror*(yes: BOOL);
57+begin
58+ werror := yes;
59+end;
60+
61+proc setQuiet*(yes: BOOL);
62+begin
63+ quiet := yes;
64+end;
65+
66+(* Paths are shown from the working directory where they are under it,
67+ so messages read the same wherever the compiler or its library is. *)
68+proc shownPath*(path: []U8): []U8;
69+var d: []U8; err: INT; c: []U8;
70+begin
71+ if not cwdKnown then
72+ d, err := Sys.workDir();
73+ if err = 0 then
74+ Buf.str(ADR(cwd), d);
75+ Buf.add(ADR(cwd), '/');
76+ end;
77+ cwdKnown := true;
78+ end;
79+ c := Buf.bytes(ADR(cwd));
80+ if (LEN(c) > 0) and Str.hasPrefix(path, c) then return path[LEN(c)..LEN(path)]; end;
81+ return path;
82+end;
83+
84+proc fatal*(msg: []U8); forward;
85+
86+(* Memory, or the end of the compile when there is none *)
87+proc grab(size: INT): ^U8;
88+var p: ^U8;
89+begin
90+ p := Mem.alloc(Heap.heap, size, 8);
91+ if p = nil then fatal("out of memory"); end;
92+ return p;
93+end;
94+
95+(* Keeps buf, len bytes of a file, under a number, which it gives back;
96+ buf stays as it is, and its path is copied. *)
97+proc addFile*(path: []U8; buf: ^U8; len: INT): INT;
98+var more: ^File; i: INT; p: []U8; ok: BOOL;
99+begin
100+ if numFiles = cap then
101+ more := ^File(grab((2 * cap + 8) * SIZE(File)));
102+ for i := 0 to numFiles - 1 do more[i] := files[i]; end;
103+ if files # nil then Mem.free(Heap.heap, ^U8(files)); end;
104+ files := more;
105+ cap := 2 * cap + 8;
106+ end;
107+ p, ok := Str.copy(Heap.heap, shownPath(path));
108+ if not ok then fatal("out of memory"); end;
109+ files[numFiles] := {path: p, buf: buf, len: len};
110+ INC(numFiles);
111+ return numFiles - 1;
112+end;
113+
114+proc pathOf*(f: INT): []U8;
115+begin
116+ return files[f].path;
117+end;
118+
119+(* Writing *)
120+
121+(* Whether NO_COLOR is set. The library can't tell it set to nothing
122+ from not set, so that counts as not set, as no-color.org has it. *)
123+proc noColour: BOOL;
124+begin
125+ return LEN(Sys.env("NO_COLOR")) > 0;
126+end;
127+
128+proc put(s: []U8);
129+begin
130+ Buf.str(ADR(out), s);
131+end;
132+
133+proc putc(c: U8);
134+begin
135+ Buf.add(ADR(out), c);
136+end;
137+
138+proc putNum(n: INT);
139+begin
140+ Fmt.write(ADR(out), "{}", [Fmt.int(n)]);
141+end;
142+
143+(* The text of a number *)
144+proc say*(f: []U8; args: []Fmt.Arg): []U8;
145+var b: ^Buf.Buf;
146+begin
147+ b := ^Buf.Buf(grab(SIZE(Buf.Buf)));
148+ Buf.init(b, Heap.heap);
149+ Fmt.write(b, f, args);
150+ return Buf.bytes(b);
151+end;
152+
153+(* c, when colour is on *)
154+proc paintOn(c: []U8);
155+begin
156+ if not colourKnown then
157+ colour := Sys.isTerminal(2) and not noColour();
158+ colourKnown := true;
159+ end;
160+ if colour then put(c); end;
161+end;
162+
163+(* s in colour c, when colour is on *)
164+proc paint(c, s: []U8);
165+begin
166+ paintOn(c);
167+ put(s);
168+ paintOn(Plain);
169+end;
170+
171+(* What has been made, written to standard error *)
172+proc flush;
173+var s: []U8; n: INT;
174+begin
175+ s := Buf.bytes(ADR(out));
176+ while LEN(s) > 0 do
177+ n := Sys.write(Sys.stderr, s);
178+ if n <= 0 then break; end;
179+ s := s[n..LEN(s)];
180+ end;
181+ Buf.reset(ADR(out));
182+end;
183+
184+(* Positions *)
185+
186+(* The line of p, and the byte where it starts. Lines are counted from
187+ the start of the file, which is slow only next to compiling it. *)
188+proc locate(p: Pos): (INT, INT);
189+var i, line, start: INT; buf: ^U8;
190+begin
191+ buf := files[p.f].buf;
192+ line := 1;
193+ start := 0;
194+ for i := 0 to p.a - 1 do
195+ if buf[i] = 10 then INC(line); start := i + 1; end;
196+ end;
197+ return line, start;
198+end;
199+
200+proc lineOf*(p: Pos): INT;
201+var line: INT;
202+begin
203+ line, _ := locate(p);
204+ return line;
205+end;
206+
207+(* A byte that starts a character: every one but a UTF-8 continuation *)
208+proc starts(c: U8): BOOL;
209+begin
210+ return (c & 0C0H) # 80H;
211+end;
212+
213+(* Characters from byte i to byte j of buf *)
214+proc chars(buf: ^U8; i, j: INT): INT;
215+var n: INT;
216+begin
217+ n := 0;
218+ while i < j do
219+ if starts(buf[i]) then INC(n); end;
220+ INC(i);
221+ end;
222+ return n;
223+end;
224+
225+(* "file:line:col: kind: msg", then the line with p underlined. A tab
226+ before p is copied into the underline, so that the two line up
227+ whatever the terminal makes of tabs. *)
228+proc show(p: Pos; kind, kindColour, msg: []U8);
229+var line, start, stop, lo, hi, i, n: INT; buf: ^U8; f: ^File; digits: []U8;
230+begin
231+ if p.f >= numFiles then
232+ (* about no place in a file, as for Rt, which the compiler
233+ imports before it reads one *)
234+ paint(Bold, "raz:");
235+ put(" ");
236+ paintOn(kindColour); put(kind); put(":"); paintOn(Plain);
237+ put(" ");
238+ paint(Bold, msg);
239+ putc('\n');
240+ flush;
241+ return;
242+ end;
243+ line, start := locate(p);
244+ f := ADR(files[p.f]);
245+ buf := f^.buf;
246+ paintOn(Bold);
247+ put(f^.path); put(":"); putNum(line); put(":"); putNum(chars(buf, start, p.a) + 1); put(":");
248+ paintOn(Plain);
249+ put(" ");
250+ paintOn(kindColour); put(kind); put(":"); paintOn(Plain);
251+ put(" ");
252+ paint(Bold, msg);
253+ putc('\n');
254+ stop := start;
255+ while (stop < f^.len) and (buf[stop] # 10) do INC(stop); end;
256+ lo := start;
257+ hi := stop;
258+ if hi - lo > ShownBytes then
259+ if p.a - lo > ShownBytes div 2 then lo := p.a - ShownBytes div 2; end;
260+ while not starts(buf[lo]) do INC(lo); end;
261+ if hi - lo > ShownBytes then hi := lo + ShownBytes; end;
262+ while (hi < stop) and not starts(buf[hi]) do INC(hi); end;
263+ end;
264+ paintOn(Blue);
265+ digits := say("{}", [Fmt.int(line)]);
266+ for i := LEN(digits) to 4 do put(" "); end;
267+ put(digits); put(" |");
268+ paintOn(Plain);
269+ put(" ");
270+ if lo > start then put("..."); end;
271+ put(buf[lo..hi]);
272+ if hi < stop then put("..."); end;
273+ putc('\n');
274+ paint(Blue, " |");
275+ put(" ");
276+ if lo > start then put(" "); end;
277+ for i := lo to p.a - 1 do
278+ if buf[i] = '\t' then putc('\t'); elsif starts(buf[i]) then putc(' '); end;
279+ end;
280+ if p.b < hi then n := chars(buf, p.a, p.b); else n := chars(buf, p.a, hi); end;
281+ if n < 1 then n := 1; end;
282+ paintOn(kindColour);
283+ for i := 1 to n do putc('^'); end;
284+ paintOn(Plain);
285+ putc('\n');
286+ flush;
287+end;
288+
289+(* From the start of p to the end of q *)
290+proc join*(p, q: Pos): Pos;
291+begin
292+ p.b := q.b;
293+ return p;
294+end;
295+
296+(* The text at p, at most the 255 bytes a message can hold *)
297+proc source*(p: Pos): []U8;
298+var n: INT;
299+begin
300+ n := p.b - p.a;
301+ if n > 255 then n := 255; end;
302+ return files[p.f].buf[p.a..p.a + n];
303+end;
304+
305+(* Messages *)
306+
307+(* Line line of the file at path, as written, to at most 255 bytes *)
308+proc lineText*(path: []U8; line: INT): []U8;
309+var i, k, n, j: INT; f: ^File; want: []U8;
310+begin
311+ want := shownPath(path);
312+ for i := 0 to numFiles - 1 do
313+ f := ADR(files[i]);
314+ if f^.path = want then
315+ k := 0;
316+ n := 1;
317+ while (n < line) and (k < f^.len) do
318+ if f^.buf[k] = 10 then INC(n); end;
319+ INC(k);
320+ end;
321+ j := k;
322+ while (j < f^.len) and (f^.buf[j] # 10) and (j - k < 255) do INC(j); end;
323+ return f^.buf[k..j];
324+ end;
325+ end;
326+ return "";
327+end;
328+
329+proc error*(p: Pos; msg: []U8);
330+begin
331+ (* a second error at one place follows from the first: when a symbol
332+ ends a construct with an error, the one around it may stop there too *)
333+ shown := not quiet and not ((errors > 0) and (p.f = lastError.f) and (p.a = lastError.a));
334+ if not shown then return; end;
335+ lastError := p;
336+ show(p, "error", Red, msg);
337+ INC(errors);
338+ if errors >= MaxErrors then
339+ put("raz: stopping after ");
340+ putNum(MaxErrors);
341+ put(" errors\n");
342+ flush;
343+ Rt.exit(1);
344+ end;
345+end;
346+
347+proc warning*(p: Pos; msg: []U8);
348+begin
349+ if werror then
350+ error(p, msg);
351+ else
352+ show(p, "warning", Yellow, msg);
353+ shown := true;
354+ INC(warnings);
355+ end;
356+end;
357+
358+(* Notes and help follow an error or a warning, and are shown with it *)
359+proc note*(p: Pos; msg: []U8);
360+begin
361+ if shown then show(p, "note", Cyan, msg); end;
362+end;
363+
364+proc help*(msg: []U8);
365+begin
366+ if shown then
367+ paint(Green, "help:");
368+ put(" ");
369+ put(msg);
370+ putc('\n');
371+ flush;
372+ end;
373+end;
374+
375+(* An error with no place in the source, such as a file that can't be
376+ read: it stops the compiler at once. *)
377+proc fatal*(msg: []U8);
378+begin
379+ put("raz: ");
380+ put(msg);
381+ putc('\n');
382+ flush;
383+ Rt.exit(1);
384+end;
385+
386+proc count(n: INT; what: []U8): []U8;
387+begin
388+ if n = 1 then return say("1 {}", [Fmt.str(what)]); end;
389+ return say("{} {}s", [Fmt.int(n), Fmt.str(what)]);
390+end;
391+
392+(* Says how many errors and warnings there were, and stops the compiler
393+ if there were errors. *)
394+proc finish*;
395+begin
396+ if (errors > 0) and (warnings > 0) then
397+ put("raz: "); put(count(errors, "error")); put(", "); put(count(warnings, "warning")); putc('\n');
398+ elsif errors > 0 then
399+ put("raz: "); put(count(errors, "error")); putc('\n');
400+ elsif warnings > 0 then
401+ put("raz: "); put(count(warnings, "warning")); putc('\n');
402+ end;
403+ flush;
404+ if errors > 0 then Rt.exit(1); end;
405+end;
406+
407+begin
408+ Buf.init(ADR(cwd), Heap.heap);
409+ Buf.init(ADR(out), Heap.heap);
410+end Diag.

src/Elf.raz added +431 -0

@@ -0,0 +1,431 @@
1+(* Elf: the executable file.
2+
3+ Writes an ELF64 executable for x86-64 Linux: the ELF header, the
4+ program headers, the linked text and rodata, and section headers
5+ with a symbol table, so that objdump and gdb can name each procedure
6+ and variable. For gdb's line numbers there is DWARF 4: a line table
7+ (.debug_line), and the one compile unit that points to it
8+ (.debug_info, .debug_abbrev). There are no types or variables.
9+
10+ A program that uses C is linked dynamically, in the least way the
11+ loader accepts: it names its loader and libraries, and each C symbol
12+ it uses is a quadword the loader fills in with the symbol's address
13+ (a GLOB_DAT relocation), which the code calls or reads through.
14+ There is no PLT and no lazy binding, and the program exports nothing.
15+
16+ Depends on: Link for the images and addresses, Chunk for the chunks,
17+ Scan for names and memory, Diag for errors, Sys and Files to write
18+ the file.
19+ Leaves out: position independent executables, symbol versions, the
20+ rest of DWARF.
21+
22+ Exported variables can't be set from outside, so needLib, setMainPath
23+ and setStripped do it. *)
24+module Elf;
25+import Sys, Files, Fmt, Diag, Scan, Chunk, Link;
26+
27+var
28+ needed: [32]INT; (* the libraries to load, names interned *)
29+ numNeeded*: INT; (* none: a static program *)
30+ mainPath: []U8; (* the main module's file, for gdb *)
31+ stripped*: BOOL; (* -s: no symbols and no line numbers; the sections are there, empty *)
32+
33+ buf: ^U8;
34+ len, cap: INT;
35+
36+(* The library name, to be loaded, unless it is already: false if there
37+ are too many *)
38+proc needLib*(name: INT): BOOL;
39+var i: INT;
40+begin
41+ for i := 0 to numNeeded - 1 do
42+ if needed[i] = name then return true; end;
43+ end;
44+ if numNeeded = 32 then return false; end;
45+ needed[numNeeded] := name;
46+ INC(numNeeded);
47+ return true;
48+end;
49+
50+(* A static program again *)
51+proc noLibs*;
52+begin
53+ numNeeded := 0;
54+end;
55+
56+proc setMainPath*(path: []U8);
57+begin
58+ mainPath := path;
59+end;
60+
61+proc setStripped*(yes: BOOL);
62+begin
63+ stripped := yes;
64+end;
65+
66+proc room(n: INT);
67+begin
68+ if len + n > cap then
69+ buf := Scan.regrab(buf, len, cap * 2 + n);
70+ cap := cap * 2 + n;
71+ end;
72+end;
73+
74+(* The n low bytes of v, least significant first *)
75+proc putN(v: INT; n: INT);
76+var i: INT;
77+begin
78+ room(n);
79+ for i := 0 to n - 1 do
80+ buf[len] := U8(v & 0FFH);
81+ v := v shr 8;
82+ INC(len);
83+ end;
84+end;
85+
86+proc putBytes(p: ^U8; n: INT);
87+begin
88+ room(n);
89+ if n > 0 then COPY(buf[len..len + n], p[0..n]); end;
90+ len := len + n;
91+end;
92+
93+proc padTo(off: INT);
94+begin
95+ while len < off do putN(0, 1); end;
96+end;
97+
98+proc patch(at: INT; v: INT; n: INT);
99+var i: INT;
100+begin
101+ for i := 0 to n - 1 do
102+ buf[at + i] := U8(v & 0FFH);
103+ v := v shr 8;
104+ end;
105+end;
106+
107+proc phdr(typ, flags: INT; off, adr, filesz, memsz, align: INT);
108+begin
109+ putN(typ, 4);
110+ putN(flags, 4);
111+ putN(off, 8);
112+ putN(adr, 8);
113+ putN(adr, 8);
114+ putN(filesz, 8);
115+ putN(memsz, 8);
116+ putN(align, 8);
117+end;
118+
119+const
120+ (* the section names, in .shstrtab; a section header names its own *)
121+ ShNames = "\0.text\0.rodata\0.bss\0.symtab\0.strtab\0.shstrtab\0.dynamic\0.dynstr\0.dynsym\0.debug_line\0.debug_info\0.debug_abbrev\0";
122+
123+(* Where in ShNames the name is: the byte after a zero that starts it and
124+ is followed by one; the empty name, found nowhere, is 0 *)
125+proc nameAt(name: []U8): INT;
126+var i, k: INT; same: BOOL;
127+begin
128+ for i := 1 to LEN(ShNames) - LEN(name) - 1 do
129+ if ShNames[i - 1] = 0 then
130+ same := ShNames[i + LEN(name)] = 0;
131+ for k := 0 to LEN(name) - 1 do
132+ if ShNames[i + k] # name[k] then same := false; end;
133+ end;
134+ if same and (LEN(name) > 0) then return i; end;
135+ end;
136+ end;
137+ return 0;
138+end;
139+
140+(* A section header. Its name is stored as its offset in ShNames. *)
141+proc shdr(name: []U8; typ: INT; flags, adr, off, size: INT; lnk, info: INT; align, entsize: INT);
142+begin
143+ putN(nameAt(name), 4); putN(typ, 4); putN(flags, 8); putN(adr, 8);
144+ putN(off, 8); putN(size, 8); putN(lnk, 4); putN(info, 4);
145+ putN(align, 8); putN(entsize, 8);
146+end;
147+
148+proc putStr(s: []U8);
149+begin
150+ putBytes(ADR(s[0]), LEN(s));
151+ putN(0, 1);
152+end;
153+
154+(* LEB128, unsigned *)
155+proc putU(v: INT);
156+begin
157+ while v >= 80H do
158+ putN(v & 7FH | 80H, 1);
159+ v := v shr 7;
160+ end;
161+ putN(v, 1);
162+end;
163+
164+(* The compile unit, which names the line table, and its abbreviation;
165+ the table itself is in the places, in rodata (Link). Section
166+ offsets go in off, sizes in size: line, info, abbrev. *)
167+proc putDebug(off, size: []INT);
168+var cwd: []U8; err: INT;
169+begin
170+ off[0] := Chunk.chunks[Link.placesChunk].adr - Link.roAdr + Link.roOff + Link.linesOff;
171+ size[0] := Link.linesSize;
172+ off[1] := len;
173+ putN(0, 4); putN(4, 2); putN(0, 4); putN(8, 1); (* length, version, abbrev, address size *)
174+ putU(1);
175+ putStr(mainPath);
176+ cwd, err := Sys.workDir();
177+ if err # 0 then cwd := ""; end;
178+ putStr(cwd);
179+ putStr("raz");
180+ putN(0, 4); (* the line table, at 0 *)
181+ putN(Link.Base + Link.textOff, 8); putN(Link.textSize, 8); (* the code, all of it *)
182+ patch(off[1], len - off[1] - 4, 4);
183+ size[1] := len - off[1];
184+
185+ off[2] := len;
186+ putU(1); putU(11H); putN(0, 1); (* 1: a compile unit, no children *)
187+ putU(03H); putU(08H); (* name, a string *)
188+ putU(1BH); putU(08H); (* comp_dir, a string *)
189+ putU(25H); putU(08H); (* producer, a string *)
190+ putU(10H); putU(17H); (* stmt_list, a section offset *)
191+ putU(11H); putU(01H); (* low_pc, an address *)
192+ putU(12H); putU(07H); (* high_pc, a length in 8 bytes *)
193+ putN(0, 2); putN(0, 1);
194+ size[2] := len - off[2];
195+end;
196+
197+const
198+ Interp = "/lib64/ld-linux-x86-64.so.2";
199+ (* program header types *)
200+ PtLoad = 1; PtDynamic = 2; PtInterp = 3; PtGnuStack = 6474E551H;
201+
202+var
203+ (* in the room at the end of rodata: where each of the loader's
204+ tables starts, from extraAdr *)
205+ symAt, relaAt, hashAt, strAt: INT;
206+ nsym, strLen: INT;
207+
208+(* Whether chunk c is a C symbol the program uses *)
209+proc isExt(c: INT): BOOL;
210+begin
211+ return Chunk.chunks[c].live and Chunk.chunks[c].ext;
212+end;
213+
214+(* The sizes of the loader's tables: what linkAll must leave room for. *)
215+proc sizeTables(roExtra, dynSize: ^INT);
216+var c, i: INT;
217+begin
218+ nsym := 1;
219+ strLen := 1;
220+ for i := 0 to numNeeded - 1 do strLen := strLen + LEN(Scan.nameOf(needed[i])) + 1; end;
221+ for c := 0 to Chunk.numChunks - 1 do
222+ if isExt(c) then
223+ INC(nsym);
224+ strLen := strLen + LEN(Scan.nameOf(Chunk.chunks[c].name)) + 1;
225+ end;
226+ end;
227+ symAt := (LEN(Interp) + 1 + 7) div 8 * 8;
228+ relaAt := symAt + nsym * 24;
229+ hashAt := relaAt + (nsym - 1) * 24;
230+ strAt := hashAt + 4 * (3 + nsym);
231+ roExtra^ := strAt + strLen;
232+ dynSize^ := (numNeeded + 10) * 16;
233+end;
234+
235+(* The loader's tables in the room at the end of rodata, which the
236+ buffer already holds as zeros: the loader's name; the symbols, one
237+ for each C symbol used; a GLOB_DAT relocation for each, at its
238+ quadword; a hash table of one bucket; and their names. *)
239+proc putTables;
240+var c, k, i, at, name: INT;
241+begin
242+ len := Link.extraAdr - Link.roAdr + Link.roOff;
243+ putStr(Interp);
244+ padTo(Link.extraAdr - Link.roAdr + Link.roOff + symAt);
245+ putN(0, 24);
246+ name := strLen;
247+ for c := Chunk.numChunks - 1 to 0 by -1 do (* names go last in the string table *)
248+ if isExt(c) then name := name - LEN(Scan.nameOf(Chunk.chunks[c].name)) - 1; end;
249+ end;
250+ for c := 0 to Chunk.numChunks - 1 do
251+ if isExt(c) then
252+ putN(name, 4); putN(10H, 1); putN(0, 1); putN(0, 2); (* global, undefined *)
253+ putN(0, 8); putN(0, 8);
254+ name := name + LEN(Scan.nameOf(Chunk.chunks[c].name)) + 1;
255+ end;
256+ end;
257+ k := 1;
258+ for c := 0 to Chunk.numChunks - 1 do
259+ if isExt(c) then
260+ putN(Chunk.chunks[c].adr, 8);
261+ putN((k shl 32) | 6, 8); (* R_X86_64_GLOB_DAT *)
262+ putN(0, 8);
263+ INC(k);
264+ end;
265+ end;
266+ putN(1, 4); putN(nsym, 4); putN(nsym - 1, 4); (* the bucket chains every symbol *)
267+ putN(0, 4);
268+ for i := 1 to nsym - 1 do putN(i - 1, 4); end;
269+ putN(0, 1);
270+ for i := 0 to numNeeded - 1 do putStr(Scan.nameOf(needed[i])); end;
271+ for c := 0 to Chunk.numChunks - 1 do
272+ if isExt(c) then putStr(Scan.nameOf(Chunk.chunks[c].name)); end;
273+ end;
274+ len := Link.roOff + Link.roSize;
275+
276+ (* the dynamic table, at the start of the writable segment *)
277+ padTo(Link.bssOff);
278+ at := 1;
279+ for i := 0 to numNeeded - 1 do
280+ putN(1, 8); putN(at, 8); (* DT_NEEDED *)
281+ at := at + LEN(Scan.nameOf(needed[i])) + 1;
282+ end;
283+ putN(4, 8); putN(Link.extraAdr + hashAt, 8); (* DT_HASH *)
284+ putN(5, 8); putN(Link.extraAdr + strAt, 8); (* DT_STRTAB *)
285+ putN(6, 8); putN(Link.extraAdr + symAt, 8); (* DT_SYMTAB *)
286+ putN(10, 8); putN(strLen, 8); (* DT_STRSZ *)
287+ putN(11, 8); putN(24, 8); (* DT_SYMENT *)
288+ putN(7, 8); putN(Link.extraAdr + relaAt, 8); (* DT_RELA *)
289+ putN(8, 8); putN((nsym - 1) * 24, 8); (* DT_RELASZ *)
290+ putN(9, 8); putN(24, 8); (* DT_RELAENT *)
291+ putN(21, 8); putN(0, 8); (* DT_DEBUG, for gdb *)
292+ putN(0, 16); (* DT_NULL *)
293+end;
294+
295+proc writeElf*(path: []U8; entry: INT);
296+var
297+ nph, nsh, c, nsyms, sec, strsCap: INT;
298+ roExtra, dynSize, symOff, strOff, shstrOff, shOff, strsLen: INT;
299+ dbgOff, dbgSize: [3]INT;
300+ strs: ^U8;
301+ s: []U8;
302+ dyn: BOOL;
303+begin
304+ cap := 1 shl 16;
305+ buf := Scan.grab(cap);
306+ len := 0;
307+ dyn := numNeeded > 0;
308+ roExtra := 0; dynSize := 0;
309+ if dyn then sizeTables(ADR(roExtra), ADR(dynSize)); end;
310+ (* room for the most program headers either kind of program has *)
311+ Link.linkAll(64 + 6 * 56, roExtra, dynSize);
312+ if dyn then
313+ nph := 6;
314+ else
315+ nph := 2;
316+ if Link.roSize > 0 then INC(nph); end;
317+ if Link.bssSize > 0 then INC(nph); end;
318+ end;
319+
320+ (* ELF header *)
321+ putN(464C457FH, 4); (* #127 'ELF' *)
322+ putN(2, 1); putN(1, 1); putN(1, 1); putN(0, 9); (* 64-bit, little-endian, version 1 *)
323+ putN(2, 2); (* ET_EXEC *)
324+ putN(62, 2); (* EM_X86_64 *)
325+ putN(1, 4);
326+ putN(Chunk.chunks[entry].adr, 8);
327+ putN(64, 8); (* program headers follow *)
328+ putN(0, 8); (* section headers: patched below *)
329+ putN(0, 4);
330+ nsh := 10;
331+ if dyn then nsh := 13; end;
332+ putN(64, 2); putN(56, 2); putN(nph, 2);
333+ putN(64, 2); putN(nsh, 2); putN(6, 2); (* .shstrtab is section 6 *)
334+
335+ (* flags: 4 read, 5 read and run, 6 read and write *)
336+ if dyn then
337+ phdr(PtInterp, 4, Link.extraAdr - Link.roAdr + Link.roOff, Link.extraAdr, LEN(Interp) + 1, LEN(Interp) + 1, 1);
338+ end;
339+ (* the first segment maps the headers too, so text can follow them *)
340+ phdr(PtLoad, 5, 0, Link.Base, Link.textOff + Link.textSize, Link.textOff + Link.textSize, Link.Page);
341+ if Link.roSize > 0 then phdr(PtLoad, 4, Link.roOff, Link.roAdr, Link.roSize, Link.roSize, Link.Page); end;
342+ if dyn then
343+ phdr(PtLoad, 6, Link.bssOff, Link.bssAdr, dynSize, Link.bssSize, Link.Page);
344+ phdr(PtDynamic, 6, Link.bssOff, Link.bssAdr, dynSize, dynSize, 8);
345+ elsif Link.bssSize > 0 then
346+ phdr(PtLoad, 6, 0, Link.bssAdr, 0, Link.bssSize, Link.Page);
347+ end;
348+ phdr(PtGnuStack, 6, 0, 0, 0, 0, 16); (* a stack that can't run code *)
349+
350+ padTo(Link.textOff);
351+ putBytes(Link.textImg, Link.textSize);
352+ padTo(Link.roOff); (* even when empty, so that every section lies in the file *)
353+ putBytes(Link.roImg, Link.roSize);
354+ if dyn then putTables; end;
355+
356+ (* the symbol table: one local symbol for each named live chunk *)
357+ padTo((len + 7) div 8 * 8);
358+ symOff := len;
359+ strsCap := 1 shl 16;
360+ strs := Scan.grab(strsCap);
361+ strsLen := 1;
362+ strs[0] := 0;
363+ putN(0, 24);
364+ nsyms := 1;
365+ for c := 0 to Chunk.numChunks - 1 do
366+ if not stripped and Chunk.chunks[c].live and (Chunk.chunks[c].name >= 0) and not Chunk.chunks[c].ext then
367+ s := Chunk.chunkName(c);
368+ if strsLen + LEN(s) + 1 > strsCap then
369+ strs := Scan.regrab(strs, strsLen, strsLen * 2 + 256);
370+ strsCap := strsLen * 2 + 256;
371+ end;
372+ COPY(strs[strsLen..strsLen + LEN(s)], s);
373+ strs[strsLen + LEN(s)] := 0;
374+ if Chunk.chunks[c].sec = Chunk.secText then (* the section's index in the headers below *)
375+ sec := 1;
376+ elsif Chunk.chunks[c].sec = Chunk.secRodata then
377+ sec := 2;
378+ else
379+ sec := 3;
380+ end;
381+ putN(strsLen, 4);
382+ if sec = 1 then putN(2, 1); else putN(1, 1); end; (* STT_FUNC, STT_OBJECT *)
383+ putN(0, 1);
384+ putN(sec, 2);
385+ putN(Chunk.chunks[c].adr, 8);
386+ putN(Chunk.chunks[c].size, 8);
387+ strsLen := strsLen + LEN(s) + 1;
388+ INC(nsyms);
389+ end;
390+ end;
391+ strOff := len;
392+ putBytes(strs, strsLen);
393+ shstrOff := len;
394+ putBytes(ADR(ShNames[0]), LEN(ShNames));
395+ if stripped or (Link.placesChunk < 0) then
396+ for c := 0 to 2 do dbgOff[c] := len; dbgSize[c] := 0; end;
397+ else
398+ putDebug(dbgOff, dbgSize);
399+ end;
400+
401+ padTo((len + 7) div 8 * 8);
402+ shOff := len;
403+ patch(40, shOff, 8);
404+ (* types: 1 PROGBITS, 2 SYMTAB, 3 STRTAB, 6 DYNAMIC, 8 NOBITS, 11 DYNSYM;
405+ flags: 2 ALLOC, 3 WRITE+ALLOC, 6 ALLOC+EXECINSTR. A symbol table's
406+ link is its string table's index: 5 .strtab, 8 .dynstr. The order
407+ here is the index the code above relies on. *)
408+ shdr("", 0, 0, 0, 0, 0, 0, 0, 0, 0);
409+ shdr(".text", 1, 6, Link.Base + Link.textOff, Link.textOff, Link.textSize, 0, 0, 16, 0);
410+ shdr(".rodata", 1, 2, Link.roAdr, Link.roOff, Link.roSize, 0, 0, 16, 0);
411+ shdr(".bss", 8, 3, Link.bssAdr + dynSize, Link.roOff + Link.roSize, Link.bssSize - dynSize, 0, 0, 16, 0);
412+ shdr(".symtab", 2, 0, 0, symOff, nsyms * 24, 5, nsyms, 8, 24);
413+ shdr(".strtab", 3, 0, 0, strOff, strsLen, 0, 0, 1, 0);
414+ shdr(".shstrtab", 3, 0, 0, shstrOff, LEN(ShNames), 0, 0, 1, 0);
415+ if dyn then (* the loader's tables, for readelf and objdump *)
416+ shdr(".dynamic", 6, 3, Link.bssAdr, Link.bssOff, dynSize, 8, 0, 8, 16);
417+ shdr(".dynstr", 3, 2, Link.extraAdr + strAt, Link.extraAdr + strAt - Link.roAdr + Link.roOff, strLen, 0, 0, 1, 0);
418+ shdr(".dynsym", 11, 2, Link.extraAdr + symAt, Link.extraAdr + symAt - Link.roAdr + Link.roOff, nsym * 24, 8, 1, 8, 24);
419+ end;
420+ shdr(".debug_line", 1, 0, 0, dbgOff[0], dbgSize[0], 0, 0, 1, 0);
421+ shdr(".debug_info", 1, 0, 0, dbgOff[1], dbgSize[1], 0, 0, 1, 0);
422+ shdr(".debug_abbrev", 1, 0, 0, dbgOff[2], dbgSize[2], 0, 0, 1, 0);
423+
424+ if not Files.write(path, buf[0..len]) or (Sys.chmod(path, 1EDH) < 0) then
425+ Diag.fatal(Diag.say("can't write {}", [Fmt.str(path)]));
426+ end;
427+end;
428+
429+begin
430+ mainPath := "";
431+end Elf.

src/Gen.raz added +2350 -0

@@ -0,0 +1,2350 @@
1+(* Gen: the code generator, for x86-64.
2+
3+ Item and Parse drive a stack machine: they push constants, addresses
4+ and the values of variables, operate on the values on top, store
5+ them and jump on them. Every value has a kind: a word, which is an
6+ integer as big as an address, a pointer, a BOOL, a set or a narrower
7+ integer; a long, a 64-bit integer on a machine whose word is smaller
8+ (never here); an F32; an F64. This unit makes the machine's code for
9+ those calls, and nothing above it knows the machine: a port is a new
10+ Gen, with an encoder of its own.
11+
12+ The stack is kept in registers, as in Wirth's compilers (Niklaus
13+ Wirth's Pascal and Oberon compilers): the value at depth d, depth 0
14+ being the bottom, is in r8 to r11, register d mod 4, or in xmm8 to
15+ xmm11 if it is a real. A value that needs a register a lower one
16+ holds spills that one: stores it in a frame slot, to free the
17+ register. A constant, or an address in the frame or of a chunk, is
18+ only noted until something needs it in a register, so that it can be
19+ an instruction's operand.
20+
21+ A slice is two words, a pointer and then a length.
22+
23+ Calls use the System V convention, which x86-64 Linux has for C:
24+ arguments in rdi, rsi, rdx, rcx, r8, r9 and xmm0 to xmm7, the rest on
25+ the machine's stack; rbx, rbp and r12 to r15 are callee-saved, which
26+ is to say a called procedure gives them back as it found them. The
27+ arguments are computed left to right onto the stack of values, and
28+ moved into their registers just before the call: a call in a later
29+ argument spills the earlier ones, as any call spills the values under
30+ it, so that it can't disturb them. A slice goes as its two words, as
31+ System V passes a 16-byte struct of two integers; a record, array or
32+ variant passed by value goes as the address of a copy the caller
33+ makes. A slice, or two results that are single values, come back in
34+ rax and rdx (inTwoRegs); any other record, or several results, comes
35+ back in memory the caller provides, through a hidden pointer
36+ (behindPointer), where C would send a small struct back in registers.
37+
38+ A procedure's frame holds its parameters, its variables, and the
39+ temporaries of the statement running. The variables are zeroed on
40+ entry.
41+
42+ Depends on: Scan and Diag for errors, Sym for types, Chunk for code
43+ and data, X64 for instructions.
44+ Leaves out: what the program means, its types and their checks; that
45+ is Item.
46+
47+ The seed's `Mark` in the middle of a push or a check can't give an
48+ error back, so it is shown and the call goes on without doing what
49+ it could not (see newEntry and check): the compile ends with the
50+ message, and the parser's recovery makes the stack right again with
51+ resetStack. endProc returns its error, for the parser to pass up.
52+
53+ What the parser sets, `inPlace`, has a setter, as the exported
54+ variables can't be set from outside. The seed's types lose their T
55+ (`TAdr` is `Adr`), and its `Call` record, which the procedure `call`
56+ takes, is `CallInfo`. *)
57+module Gen;
58+import Fmt, Diag, Scan, Sym, Chunk, X := X64;
59+
60+const
61+ NoLabel* = -1;
62+ WordSize* = 8; (* the size of an address, and of INT *)
63+ (* What the machine catches by itself, which the code needn't test for
64+ (report section 10): on x86-64 Linux, a division by zero, a stack
65+ overflow (at the guard page under the stack), a call to nil, and
66+ a load or store within NilPage bytes of address 0, which is never
67+ mapped. *)
68+ NilPage* = 4096;
69+
70+ RAX = X.RAX; RCX = X.RCX; RDX = X.RDX; RSP = X.RSP; RBP = X.RBP;
71+ RSI = X.RSI; RDI = X.RDI; R8 = X.R8; R9 = X.R9; R10 = X.R10; R11 = X.R11;
72+
73+type
74+ Kind* = (kWord, kLong, kF32, kF64);
75+
76+ (* Where a variable is: its address is relative to the frame, to a
77+ chunk, to an address on the stack, or to one held in a frame slot *)
78+ Base* = (bFrame, bGlobal, bStack, bSlot, bReg);
79+ Adr* = record
80+ base*: Base;
81+ chunk*: INT; (* bGlobal: the chunk; bSlot: the frame slot; bReg: the register *)
82+ off*: I64; (* added to the address; for bReg, which word, 0 or 8 *)
83+ hi*: INT; (* bReg, a slice: the register of its length, the
84+ second word; chunk is that of its pointer *)
85+ end;
86+
87+ (* The code made so far, to go back to for a second try at a body *)
88+ CodeMark* = record pc*, fixups*, lines*, said*, fails*: INT; end;
89+
90+ (* For entryPoint: the address of chunk, put in the variable whose
91+ chunk is into before the program starts *)
92+ Link* = record chunk*, into*: INT; end;
93+
94+ CallInfo* = record
95+ sig*: ^Sym.Type;
96+ param*: ^Sym.Obj; (* the parameter the next argument is for *)
97+ obj*: ^Sym.Obj; (* the procedure called, if it has a name *)
98+ n*: INT; (* the arguments *)
99+ isF*: [64]BOOL; (* ... goes in an xmm register *)
100+ pair*: [64]BOOL; (* ... is a slice's first word, the next its second *)
101+ target*: I64; (* the frame slot of a procedure value, if chunk < 0 *)
102+ chunk*: INT; (* else the procedure's chunk *)
103+ ext*: BOOL; (* C's: called through the chunk holding its address *)
104+ ret*: I64; (* set by call: the temporary a slice or a record result is in *)
105+ end;
106+
107+const
108+ (* the registers a procedure keeps its busiest variables in: System V's
109+ callee-saved ones, so they live through calls (a register variable);
110+ a procedure saves those it uses, and Rt finds them there for the
111+ trap report *)
112+ VarRegs*: [5]INT = [X.RBX, X.R12, X.R13, X.R14, X.R15];
113+ (* the registers the trap report can show a variable in: VarRegs, then
114+ rdi and rsi, where a procedure that calls nothing keeps the
115+ parameters that arrive in them (keptIn) *)
116+ ShownRegs*: [7]INT = [X.RBX, X.R12, X.R13, X.R14, X.R15, X.RDI, X.RSI];
117+ (* the registers a procedure keeps its busiest reals in, xmm12 to
118+ xmm15, numbered from XmmVar up so that they aren't taken for r12 to
119+ r15 (regAt). Each has a slot too, written as it is, where the trap
120+ report finds it, and from which it is loaded again after a call, as
121+ System V has no callee-saved xmm register (xHome). *)
122+ XmmVar* = 16;
123+ XVarRegs*: [4]INT = [XmmVar + 12, XmmVar + 13, XmmVar + 14, XmmVar + 15];
124+ (* a procedure's registers of variables, as bits: bit i is VarRegs[i],
125+ bit XBit + i XVarRegs[i] *)
126+ XBit* = 5;
127+
128+var
129+ rtFail*, argcChunk*, argvChunk*: INT;
130+ (* the stubs that check's code calls, one for each kind of failure,
131+ made by entryPoint for those used *)
132+ failStubs: [6]INT;
133+ lost*: BOOL; (* a parameter kept where it arrived was wanted
134+ for other work: the procedure is compiled again,
135+ the parameter in memory *)
136+ inPlace: INT; (* the register of a variable that the statement
137+ being compiled assigns, x := x + e, where the
138+ value can be worked out in the variable's own
139+ register, from its first push on (lInto) *)
140+ depth*: INT; (* the values on the stack *)
141+ pushed*: INT; (* quadwords pushed on the machine's stack *)
142+ codeChunk*: INT; (* the procedure or body being compiled, or -1 *)
143+
144+type
145+ (* where a value on the stack is *)
146+ Loc = (lConst, (* not loaded: val is the value *)
147+ lHeld, (* not loaded: in register val, a register
148+ variable's own (see VarRegs), read in place, which
149+ nothing in an expression can change *)
150+ lAdr, (* not loaded: the address of chunk, or of the frame
151+ if chunk is -1, plus val *)
152+ lIdx, (* not loaded: the address m, an element of an array
153+ or of a slice in registers: the array's or the
154+ pointer's register, or rbp, as the base, and the
155+ index in a register variable's or the value's
156+ own register (indexSlice, indexArray) *)
157+ lMem, (* not loaded: the value of size bytes at m, in the
158+ frame, a chunk, or at an address lAdr or lIdx
159+ noted, read where it is used (pushVar) *)
160+ lInto, (* in register val, a register variable's own, which
161+ is what the value goes to (inPlace): so it is
162+ changed in place *)
163+ lReg, (* in its register *)
164+ lFrame); (* spilled: in the frame slot val *)
165+
166+ Entry = record
167+ loc: Loc;
168+ val: I64; (* lConst: the value; lHeld: the register; lAdr: the
169+ offset; lFrame: the frame slot *)
170+ chunk: INT; (* lAdr: the chunk, or -1 for the frame *)
171+ m: X.Mem; (* lIdx, lMem *)
172+ size: INT; (* lMem *)
173+ signed: BOOL; (* lMem *)
174+ k: Kind;
175+ off: I64; (* lHeld, lReg: a word, its register plus off, the
176+ constant of x + 1 not yet added (op), so that an
177+ operand that uses it can take it as its
178+ displacement: [r13 + r9 * 8 - 8] *)
179+ end;
180+
181+ (* a check of the procedure, whose failure endFails makes *)
182+ Fail = record
183+ L, what, ra, name, at: INT;
184+ m: X.Mem;
185+ n: I64;
186+ end;
187+
188+const
189+ StubNames: [6][]U8 = ["check0", "check1", "check2", "check3", "check4", "check5"];
190+ (* the registers of the stack: the value at depth d is in Regs[d mod
191+ NumRegs]. rax, rdx and rcx, which division and shifts need, and rsi
192+ and rdi, which copying needs, aren't among them. *)
193+ NumRegs = 4;
194+ Regs: [NumRegs]INT = [R8, R9, R10, R11];
195+ XRegs: [NumRegs]INT = [8, 9, 10, 11]; (* xmm8 to xmm11 *)
196+ IntRegs: [6]INT = [RDI, RSI, RDX, RCX, R8, R9];
197+
198+var
199+ stack: [256]Entry;
200+ owner: [NumRegs]INT; (* the value in each register, or -1 *)
201+ frameTop, frameMax, permTop: I64;
202+ frameFix: INT; (* where the frame size is patched in *)
203+ paramTop: I64; (* the parameters' slots end here *)
204+ zeroTop: I64; (* the locals the prologue zeroes end here *)
205+ retSlot: I64; (* holds the hidden result pointer *)
206+ resType: ^Sym.Type; (* the procedure's result, or nil *)
207+ exitL: INT;
208+ (* parameters arriving in registers: where each is stored on entry *)
209+ inReg: [14]INT;
210+ inSlot: [14]I64;
211+ inSize: [14]INT;
212+ inObj: [14]^Sym.Obj;
213+ numIn: INT;
214+ procParams: ^Sym.Obj; (* the parameters, for enterBody *)
215+ regMask: INT; (* the registers of variables, as bits (XBit) *)
216+ kept: INT; (* bit r: register r holds a parameter, as it arrived *)
217+ saveAt: I64; (* where they are saved, a quadword each *)
218+ homes: [4]I64; (* the slots of the variables in XVarRegs *)
219+ frameAt: [3]I64; (* frameTop, frameMax, permTop after the declarations *)
220+ fails: [4096]Fail;
221+ numFails: INT;
222+
223+proc setInPlace*(r: INT);
224+begin
225+ inPlace := r;
226+end;
227+
228+proc kindOf*(t: ^Sym.Type): Kind;
229+begin
230+ if t^.form = Sym.fReal then
231+ if t^.size = 4 then return kF32; end;
232+ return kF64;
233+ end;
234+ if t^.size > WordSize then return kLong; end;
235+ return kWord;
236+end;
237+
238+(* The stack, as in Wirth's compilers: the value at depth d is held in
239+ register d mod NumRegs. A value, when a higher one wants its register,
240+ and every value in a register when a call would clobber them, is
241+ spilled to a frame slot, and loaded again where it is used. A constant
242+ is only noted.
243+
244+ drop emits no code, and a dropped value's register still holds it
245+ until the next push claims it: place (for bStack), operands,
246+ indexSlice and jumpCmp read a register after dropping its value.
247+
248+ Registers outside the stack, free within one operation: rax, rcx and
249+ rdx for arithmetic; rsi and rdi for copying; and, where the stack holds
250+ nothing in them, r10 for the prologue's zeroing loop and r11 for a call
251+ through a procedure value; xmm0 and xmm1 for reals.
252+
253+ A real, an F32 or an F64, is held in xmm8 to xmm11 (XRegs), where the
254+ machine computes with reals, the value at depth d in XRegs[d mod
255+ NumRegs]: so each depth has two registers, and holds its value in the
256+ one of its kind, which owner doesn't tell apart. The xmm registers
257+ from xmm8 up carry no arguments, so that call can move a real into
258+ xmm0 to xmm7 without overwriting another still to go. *)
259+
260+proc fits32(v: I64): BOOL;
261+begin
262+ return (v >= -2147483648) and (v <= 2147483647);
263+end;
264+
265+(* The register of kind k for the value at depth i *)
266+proc regIn(k: Kind; i: INT): INT;
267+begin
268+ if k in {kF32, kF64} then return XRegs[i mod NumRegs]; end;
269+ return Regs[i mod NumRegs];
270+end;
271+
272+proc regOf(i: INT): INT;
273+begin
274+ return regIn(stack[i].k, i);
275+end;
276+
277+proc isReal(i: INT): BOOL;
278+begin
279+ return stack[i].k in {kF32, kF64};
280+end;
281+
282+(* A real constant, its bits v, as an operand: 8 bytes in read-only
283+ data, as the machine has no instruction that holds one *)
284+proc realConst(v: I64): X.Mem;
285+var c: INT;
286+begin
287+ c := Chunk.newChunk(Chunk.secRodata, -1, -1);
288+ Chunk.setData(c, ^U8(ADR(v)), 8, 8);
289+ return X.memRip(c, 0);
290+end;
291+
292+(* The real i into xmm register x, from wherever it is, as valueTo does
293+ for an integer register *)
294+proc xValueTo(i, x: INT);
295+begin
296+ match stack[i].loc of
297+ | lConst: X.movsXM(x, realConst(stack[i].val), stack[i].k = kF32);
298+ | lMem: X.movsXM(x, stack[i].m, stack[i].size = 4);
299+ | lHeld: if INT(stack[i].val) # x then X.movX(x, INT(stack[i].val)); end;
300+ | lInto: if INT(stack[i].val) # x then X.movX(x, INT(stack[i].val)); end;
301+ | lReg: if regOf(i) # x then X.movX(x, regOf(i)); end;
302+ | else: X.movsXM(x, X.mem(RBP, stack[i].val), false); (* spilled, as 8 bytes *)
303+ end;
304+end;
305+
306+proc loaded(i: INT): INT; forward;
307+proc allocTemp*(size, align: I64): I64; forward;
308+
309+(* The value i, in a register, goes to a frame slot; one noted that
310+ holds its register, as an index, is worked out in it first *)
311+proc spill(i: INT);
312+var s: I64;
313+begin
314+ if (stack[i].loc # lReg) or (stack[i].off # 0) then _ := loaded(i); end;
315+ s := allocTemp(8, 8);
316+ if isReal(i) then X.movsMX(X.mem(RBP, s), regOf(i), false);
317+ else X.store(X.mem(RBP, s), regOf(i), 8); end;
318+ stack[i].loc := lFrame;
319+ stack[i].val := s;
320+ owner[i mod NumRegs] := -1;
321+end;
322+
323+(* Each value below depth d read from memory now, as what comes next
324+ may change it *)
325+proc readMems(d: INT);
326+var i: INT;
327+begin
328+ for i := 0 to d - 1 do
329+ if stack[i].loc = lMem then _ := loaded(i); end;
330+ end;
331+end;
332+
333+(* Every value below depth d in a register, spilled; one noted in memory
334+ is read first, as a call may change it *)
335+proc spillBelow(d: INT);
336+var r: INT;
337+begin
338+ readMems(d);
339+ for r := 0 to NumRegs - 1 do
340+ if (owner[r] >= 0) and (owner[r] < d) then spill(owner[r]); end;
341+ end;
342+end;
343+
344+(* The register of kind k of value i, for it to hold: a lower value at
345+ its depth's registers is spilled. *)
346+proc claim(i: INT; k: Kind): INT;
347+var r: INT;
348+begin
349+ r := i mod NumRegs;
350+ if (owner[r] >= 0) and (owner[r] # i) then spill(owner[r]); end;
351+ owner[r] := i;
352+ return regIn(k, i);
353+end;
354+
355+(* The memory at the noted address i, plus off *)
356+proc adrMem(i: INT; off: I64): X.Mem;
357+begin
358+ if stack[i].chunk < 0 then return X.mem(RBP, stack[i].val + off); end;
359+ return X.memRip(stack[i].chunk, INT(stack[i].val + off));
360+end;
361+
362+(* The value i, in its register *)
363+proc loaded(i: INT): INT;
364+var r: INT;
365+begin
366+ if stack[i].loc = lInto then return INT(stack[i].val); end;
367+ if (stack[i].loc # lReg) and isReal(i) then
368+ xValueTo(i, claim(i, stack[i].k));
369+ stack[i].loc := lReg;
370+ elsif stack[i].loc # lReg then
371+ r := claim(i, kWord);
372+ match stack[i].loc of
373+ | lConst: X.movRI(r, stack[i].val);
374+ | lHeld: X.movRR(r, INT(stack[i].val));
375+ | lAdr: X.lea(r, adrMem(i, 0));
376+ | lIdx: X.lea(r, stack[i].m);
377+ | lMem: X.load(r, stack[i].m, stack[i].size, stack[i].signed);
378+ | else: X.load(r, X.mem(RBP, stack[i].val), 8, false);
379+ end;
380+ stack[i].loc := lReg;
381+ end;
382+ if stack[i].off # 0 then
383+ X.lea(regOf(i), X.mem(regOf(i), stack[i].off));
384+ stack[i].off := 0;
385+ end;
386+ return regOf(i);
387+end;
388+
389+(* The register value i is in, only to be read: a variable's own, or
390+ its register *)
391+proc peek(i: INT): INT;
392+begin
393+ if (stack[i].loc = lHeld) and (stack[i].off = 0) then return INT(stack[i].val); end;
394+ return loaded(i);
395+end;
396+
397+(* The offset of value i, taken from it, for the caller to add or to
398+ make a displacement of *)
399+proc takeOff(i: INT): I64;
400+var o: I64;
401+begin
402+ o := stack[i].off;
403+ stack[i].off := 0;
404+ return o;
405+end;
406+
407+(* The word on top, in a register, has o added: noted, if o can be a
408+ displacement, else added now *)
409+proc putOff(o: I64);
410+begin
411+ if fits32(stack[depth - 1].off + o) then
412+ stack[depth - 1].off := stack[depth - 1].off + o;
413+ else
414+ X.movRI(RCX, o);
415+ X.alu(X.aluAdd, loaded(depth - 1), RCX);
416+ end;
417+end;
418+
419+proc top: INT;
420+begin
421+ if depth = 0 then Diag.fatal("internal error: the stack is empty"); end;
422+ return loaded(depth - 1);
423+end;
424+
425+(* A value on the stack's top. At the stack's last place it is shown as
426+ an error and nothing is pushed: see the head of this unit. *)
427+proc newEntry(k: Kind; loc: Loc; v: I64);
428+begin
429+ if depth > LEN(stack) - 1 then
430+ _ := Scan.mark("the expression is too deep");
431+ return;
432+ end;
433+ stack[depth].k := k;
434+ stack[depth].loc := loc;
435+ stack[depth].val := v;
436+ stack[depth].chunk := -1;
437+ stack[depth].off := 0;
438+ INC(depth);
439+end;
440+
441+(* An address, lIdx, or a value at it, lMem, noted as the operand m. Its
442+ index may be in the register of the value just dropped, at this
443+ depth: it is the new value's own, then. *)
444+proc newMem(loc: Loc; m: X.Mem; k: Kind; size: INT; signed: BOOL);
445+begin
446+ newEntry(k, loc, 0);
447+ stack[depth - 1].m := m;
448+ stack[depth - 1].size := size;
449+ stack[depth - 1].signed := signed;
450+ if m.index = Regs[(depth - 1) mod NumRegs] then owner[(depth - 1) mod NumRegs] := depth - 1; end;
451+end;
452+
453+(* The register a new value on top is to be computed in *)
454+proc target: INT;
455+begin
456+ return claim(depth, kWord);
457+end;
458+
459+(* The xmm register a new real on top is to be computed in *)
460+proc xTarget: INT;
461+begin
462+ return claim(depth, kF64);
463+end;
464+
465+(* The value just computed in target goes on top *)
466+proc computed(k: Kind);
467+begin
468+ newEntry(k, lReg, 0);
469+end;
470+
471+proc drop*;
472+begin
473+ DEC(depth);
474+ if owner[depth mod NumRegs] = depth then owner[depth mod NumRegs] := -1; end;
475+end;
476+
477+(* rsi and rdi are about to be used for other work, as in copying: a
478+ parameter kept in either must go to memory (lost). *)
479+proc clobberArgs;
480+begin
481+ if kept # 0 then lost := true; end;
482+end;
483+
484+(* The value i into register r, from wherever it is: a constant or an
485+ address is made there, a variable's register or the value's own
486+ register copied, a spilled value loaded. Unlike loaded, it leaves the
487+ value where it was, so r is its only new copy. *)
488+proc valueTo(i, r: INT);
489+begin
490+ if isReal(i) and (stack[i].loc in {lHeld, lInto}) then
491+ X.movqRX(r, INT(stack[i].val));
492+ else
493+ match stack[i].loc of
494+ | lConst: X.movRI(r, stack[i].val);
495+ | lHeld: X.movRR(r, INT(stack[i].val));
496+ | lInto: X.movRR(r, INT(stack[i].val));
497+ | lAdr: X.lea(r, adrMem(i, 0));
498+ | lIdx: X.lea(r, stack[i].m);
499+ | lMem: X.load(r, stack[i].m, stack[i].size, stack[i].signed);
500+ | lReg:
501+ if isReal(i) then X.movqRX(r, regOf(i));
502+ elsif regOf(i) # r then X.movRR(r, regOf(i)); end;
503+ | else: X.load(r, X.mem(RBP, stack[i].val), 8, false);
504+ end;
505+ end;
506+ if stack[i].off # 0 then X.lea(r, X.mem(r, stack[i].off)); end;
507+end;
508+
509+(* The value on top, popped into register r *)
510+proc popTo(r: INT);
511+begin
512+ valueTo(depth - 1, r);
513+ drop();
514+end;
515+
516+(* Whether the value on top is a constant, and if so, which *)
517+proc topConst: (BOOL, I64);
518+begin
519+ return stack[depth - 1].loc = lConst, stack[depth - 1].val;
520+end;
521+
522+proc resetStack*(d, p: INT);
523+var r: INT;
524+begin
525+ depth := d;
526+ pushed := p;
527+ for r := 0 to NumRegs - 1 do owner[r] := -1; end;
528+end;
529+
530+proc pushConst*(k: Kind; v: I64);
531+begin
532+ newEntry(k, lConst, v);
533+end;
534+
535+(* The register of the word at a, a variable in registers: the variable's
536+ own, or for a slice its pointer's (off 0) or its length's (off 8) *)
537+proc regAt(a: Adr): INT;
538+var r: INT;
539+begin
540+ if a.off = 0 then r := a.chunk; else r := a.hi; end;
541+ if r >= XmmVar then r := r - XmmVar; end; (* an xmm register, XVarRegs *)
542+ return r;
543+end;
544+
545+(* The memory a names. An address on the stack is popped, and is in its
546+ register still; one in a slot is loaded into r. *)
547+proc place(a: Adr; r: INT): X.Mem;
548+var m: X.Mem; ra: INT; o: I64;
549+begin
550+ if a.base = bReg then Diag.fatal("internal error: a register has no address"); end;
551+ match a.base of
552+ | bFrame: return X.mem(RBP, a.off);
553+ | bGlobal: return X.memRip(a.chunk, INT(a.off));
554+ | bStack:
555+ if stack[depth - 1].loc = lAdr then
556+ m := adrMem(depth - 1, a.off);
557+ drop();
558+ return m;
559+ elsif stack[depth - 1].loc = lIdx then
560+ m := stack[depth - 1].m;
561+ m.disp := m.disp + INT(a.off);
562+ drop();
563+ return m;
564+ end;
565+ (* an offset noted on the address is the operand's, as
566+ p^.f + 8: [r8 + 8] *)
567+ if fits32(a.off + stack[depth - 1].off) then o := takeOff(depth - 1); else o := 0; end;
568+ ra := peek(depth - 1);
569+ drop();
570+ return X.mem(ra, a.off + o);
571+ | else: (* bSlot: the address is in the frame slot a.chunk *)
572+ X.load(r, X.mem(RBP, a.chunk), 8, false);
573+ return X.mem(r, a.off);
574+ end;
575+end;
576+
577+(* The address a names, on top of the stack *)
578+proc pushAdr*(a: Adr);
579+var m: X.Mem; r: INT;
580+begin
581+ if (a.base = bStack) and (a.off = 0) then return; end; (* it is on top already *)
582+ if a.base in {bFrame, bGlobal} then
583+ newEntry(kWord, lAdr, a.off);
584+ if a.base = bGlobal then stack[depth - 1].chunk := a.chunk; end;
585+ return;
586+ end;
587+ (* The order matters. With the address on the stack, place pops it and
588+ must come first, so that target may reuse its register; otherwise
589+ target comes first, since place may need r to load a slot's pointer. *)
590+ if a.base = bStack then
591+ m := place(a, -1); r := target();
592+ else
593+ r := target(); m := place(a, r);
594+ end;
595+ X.lea(r, m);
596+ computed(kWord);
597+end;
598+
599+proc pushVar*(a: Adr; size: INT; signed: BOOL; k: Kind);
600+var m: X.Mem; r: INT;
601+begin
602+ r := inPlace;
603+ inPlace := -1;
604+ if r >= XmmVar then r := r - XmmVar; end;
605+ if (a.base = bReg) and (regAt(a) = r) then
606+ newEntry(k, lInto, r);
607+ return;
608+ end;
609+ if a.base = bReg then
610+ newEntry(k, lHeld, regAt(a));
611+ return;
612+ end;
613+ (* a variable in the frame or a chunk, or at an address only noted, is
614+ 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
616+ m := place(a, -1);
617+ newMem(lMem, m, k, size, signed);
618+ return;
619+ end;
620+ (* in the order pushAdr explains *)
621+ if a.base = bStack then
622+ m := place(a, -1); r := target();
623+ else
624+ r := target(); m := place(a, r);
625+ end;
626+ if k in {kF32, kF64} then X.movsXM(xTarget(), m, size = 4);
627+ else X.load(r, m, size, signed); end;
628+ computed(k);
629+end;
630+
631+proc pushProc*(c: INT; ext: BOOL);
632+var r: INT;
633+begin
634+ r := target();
635+ if ext then X.load(r, X.memRip(c, 0), 8, false);
636+ else X.lea(r, X.memRip(c, 0)); end;
637+ computed(kWord);
638+end;
639+
640+(* The slot of the variable in xmm register x *)
641+proc homeOf(x: INT): X.Mem;
642+begin
643+ return X.mem(RBP, homes[x + XmmVar - XVarRegs[0]]);
644+end;
645+
646+(* Pops a value into the variable at a; an address on the stack is under
647+ the value. *)
648+proc popVar*(a: Adr; size: INT);
649+var r: INT; v: I64; c, fl: BOOL;
650+begin
651+ if (a.base = bReg) and isReal(depth - 1) then
652+ xValueTo(depth - 1, regAt(a));
653+ drop();
654+ X.movsMX(homeOf(regAt(a)), regAt(a), false); (* written through, as xHome says *)
655+ return;
656+ end;
657+ if a.base = bReg then
658+ c, v := topConst();
659+ if c then X.movRI(regAt(a), v);
660+ elsif peek(depth - 1) # regAt(a) then X.movRR(regAt(a), peek(depth - 1)); end; (* else it is there, lInto *)
661+ drop();
662+ return;
663+ end;
664+ c, v := topConst();
665+ if c and fits32(v) then
666+ drop();
667+ X.storeI(place(a, RCX), INT(v), size);
668+ return;
669+ end;
670+ if c then r := RAX; X.movRI(RAX, v);
671+ else r := peek(depth - 1); end;
672+ fl := (stack[depth - 1].loc # lConst) and isReal(depth - 1);
673+ drop();
674+ if fl then X.movsMX(place(a, RCX), r, size = 4);
675+ else X.store(place(a, RCX), r, size); end;
676+end;
677+
678+(* Register src to dst, an xmm register's if fl *)
679+proc movReg(fl: BOOL; dst, src: INT);
680+begin
681+ if fl then X.movX(dst, src); else X.movRR(dst, src); end;
682+end;
683+
684+(* The two values on top, of one kind, change places. *)
685+proc swap*;
686+var e: Entry; x, y, t: INT; rx, ry, fl: BOOL;
687+begin
688+ x := depth - 2; y := depth - 1;
689+ (* a value noted at an address that uses its register is worked out,
690+ so that its register moves with it *)
691+ if stack[x].loc in {lIdx, lMem} then _ := loaded(x); end;
692+ if stack[y].loc in {lIdx, lMem} then _ := loaded(y); end;
693+ rx := stack[x].loc = lReg;
694+ ry := stack[y].loc = lReg;
695+ fl := isReal(y);
696+ if fl then t := 0; else t := RAX; end; (* xmm0, or rax *)
697+ if rx and ry then
698+ movReg(fl, t, regOf(x));
699+ movReg(fl, regOf(x), regOf(y));
700+ movReg(fl, regOf(y), t);
701+ elsif rx then
702+ owner[x mod NumRegs] := -1;
703+ movReg(fl, claim(y, stack[y].k), regOf(x));
704+ elsif ry then
705+ owner[y mod NumRegs] := -1;
706+ movReg(fl, claim(x, stack[x].k), regOf(y));
707+ end;
708+ e := stack[x]; stack[x] := stack[y]; stack[y] := e;
709+end;
710+
711+(* Copying *)
712+
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. *)
717+proc copyBytes(size: I64);
718+var o, n: I64;
719+begin
720+ if size > 64 then
721+ X.movRI(RCX, size);
722+ X.repMovsb();
723+ return;
724+ end;
725+ o := 0;
726+ while o < size do
727+ n := 8;
728+ while n > size - o do n := n div 2; end;
729+ X.load(RCX, X.mem(RSI, o), INT(n), false);
730+ X.store(X.mem(RDI, o), RCX, INT(n));
731+ INC(o, n);
732+ end;
733+end;
734+
735+(* Pops a source's address, and a destination's under it, and copies
736+ size bytes to off bytes past the destination. *)
737+proc copyBlock*(size, off: I64);
738+begin
739+ clobberArgs();
740+ popTo(RSI);
741+ popTo(RDI);
742+ if off # 0 then X.lea(RDI, X.mem(RDI, off)); end;
743+ copyBytes(size);
744+end;
745+
746+(* Pops a source's address, and copies size bytes to a: for a slice in
747+ registers, its two words into them. *)
748+proc copyTo*(a: Adr; size: I64);
749+begin
750+ clobberArgs();
751+ popTo(RSI);
752+ if a.base = bReg then
753+ X.load(a.chunk, X.mem(RSI, 0), 8, false);
754+ X.load(a.hi, X.mem(RSI, 8), 8, false);
755+ return;
756+ end;
757+ X.lea(RDI, place(a, RDI));
758+ copyBytes(size);
759+end;
760+
761+proc zeroVar*(a: Adr; size: I64);
762+begin
763+ clobberArgs();
764+ X.lea(RDI, place(a, RDI));
765+ X.movRI(RCX, size);
766+ X.movRI(RAX, 0);
767+ X.repStosb();
768+end;
769+
770+(* Operations *)
771+
772+(* n if v is 2^n, which is 0 for 1; -1 if v isn't a power of two *)
773+proc exactLog2(v: I64): INT;
774+var n: INT;
775+begin
776+ n := 0;
777+ while (v > 1) and ((v & 1) = 0) do v := v shr 1; INC(n); end;
778+ if v # 1 then n := -1; end;
779+ return n;
780+end;
781+
782+(* r times v, a size: by a shift where v is a power of two, as it
783+ mostly is, since a shift takes one cycle and imul three *)
784+proc mulI(r: INT; v: I64);
785+begin
786+ if exactLog2(v) > 0 then X.shiftI(X.shShl, r, exactLog2(v));
787+ elsif v # 1 then X.imulI(r, INT(v)); end;
788+end;
789+
790+(* r compared with v, through rdx if v needs more than 32 bits; with
791+ zero by test, which sets the flags as cmp would and is shorter *)
792+proc cmpI(r: INT; v: I64);
793+begin
794+ if v = 0 then X.testRR(r, r);
795+ elsif fits32(v) then X.aluI(X.aluCmp, r, INT(v));
796+ else X.movRI(RDX, v); X.alu(X.aluCmp, r, RDX); end;
797+end;
798+
799+(* r div or mod 2^k, 1 <= k <= 62, with shifts: div truncates towards
800+ zero, so a negative dividend first gets 2^k - 1 added (the bias). *)
801+proc divPow2(sy: Scan.Sym; r, k: INT; unsign: BOOL);
802+begin
803+ (* unsigned: div shifts right; mod keeps the low k bits, by shifting
804+ them up to the top and back down *)
805+ if unsign then
806+ if sy = Scan.sDiv then X.shiftI(X.shShr, r, k);
807+ else X.shiftI(X.shShl, r, 64 - k); X.shiftI(X.shShr, r, 64 - k); end;
808+ return;
809+ end;
810+ (* signed: sar 63 makes the sign into all ones or all zeros, and shr
811+ 64 - k keeps k of them, the bias 2^k - 1 or 0; with it added, sar k
812+ rounds towards zero. The remainder is r less the quotient times 2^k. *)
813+ X.movRR(RCX, r);
814+ X.shiftI(X.shSar, RCX, 63);
815+ X.shiftI(X.shShr, RCX, 64 - k);
816+ X.alu(X.aluAdd, RCX, r);
817+ X.shiftI(X.shSar, RCX, k);
818+ if sy = Scan.sDiv then X.movRR(r, RCX);
819+ else X.shiftI(X.shShl, RCX, k); X.alu(X.aluSub, r, RCX); end;
820+end;
821+
822+(* Before rax div y, of a signed type of bits < 64: its smallest value
823+ divided by -1 overflows it, which must stop the program as it does for
824+ an I64 (report section 6.1). idiv on the 64-bit values wouldn't fault,
825+ so then rax is made the smallest I64, and it does. *)
826+proc divTrap(bits, y: INT);
827+var L: INT;
828+begin
829+ L := NoLabel;
830+ cmpI(y, -1);
831+ X.jcc(X.ccNE, L);
832+ cmpI(RAX, I64(-1) shl (bits - 1));
833+ X.jcc(X.ccNE, L);
834+ X.shiftI(X.shShl, RAX, 64 - bits);
835+ X.fixLink(L);
836+end;
837+
838+(* Whether the value on top is a word in memory that can be the right
839+ operand of an instruction as it is: add r, [m] *)
840+proc topInMem: BOOL;
841+begin
842+ return (stack[depth - 1].loc = lMem) and (stack[depth - 1].size = 8);
843+end;
844+
845+(* The right operand of the two values on top, popped, in register y:
846+ its own, or rcx for a constant; the left one stays, in its register,
847+ which is returned with y. *)
848+proc operands: (INT, INT);
849+var v: I64; c: BOOL; y: INT;
850+begin
851+ c, v := topConst();
852+ if c then X.movRI(RCX, v); y := RCX; else y := peek(depth - 1); end;
853+ drop();
854+ return top(), y;
855+end;
856+
857+(* The two reals on top, the left op the right, worked out in the left's
858+ xmm register. The right is taken from memory where it is, as a
859+ constant, a variable or a spilled value is: mulsd xmm8, [rbp - 16]. *)
860+proc realOp(sy: Scan.Sym; k: Kind);
861+var f: BOOL; c, x, y: INT; m: X.Mem;
862+begin
863+ f := k = kF32;
864+ match sy of
865+ | sPlus: c := 58H; (* addsd, or addss for an F32 *)
866+ | sMinus: c := 5CH; (* subsd, subss *)
867+ | sTimes: c := 59H; (* mulsd, mulss *)
868+ | else: c := 5EH; (* divsd, divss *)
869+ end;
870+ if stack[depth - 1].loc in {lConst, lMem, lFrame} then
871+ match stack[depth - 1].loc of
872+ | lConst: m := realConst(stack[depth - 1].val);
873+ | lMem: m := stack[depth - 1].m;
874+ | else: m := X.mem(RBP, stack[depth - 1].val);
875+ end;
876+ drop();
877+ X.sseM(c, top(), m, f);
878+ else
879+ y := peek(depth - 1);
880+ drop();
881+ x := top();
882+ X.sse(c, x, y, f);
883+ end;
884+end;
885+
886+(* The group 1 operation of +, -, &, | and xor *)
887+proc aluOf(sy: Scan.Sym): INT;
888+begin
889+ match sy of
890+ | sPlus: return X.aluAdd;
891+ | sMinus: return X.aluSub;
892+ | sAmp: return X.aluAnd;
893+ | sBar: return X.aluOr;
894+ | else: return X.aluXor;
895+ end;
896+end;
897+
898+const
899+ (* the condition codes of the comparisons, from sEql: = # < <= > >= *)
900+ CcSigned: [6]INT = [X.ccE, X.ccNE, X.ccL, X.ccLE, X.ccG, X.ccGE];
901+ CcUnsigned: [6]INT = [X.ccE, X.ccNE, X.ccB, X.ccBE, X.ccA, X.ccAE];
902+
903+(* The two values on top, the left op the right, an integer of size
904+ bytes, signed or not, brought back to its width. *)
905+proc op*(sy: Scan.Sym; k: Kind; size: INT; signed: BOOL);
906+var v, o: I64; r, y, sh, bits: INT; c: BOOL; m: X.Mem;
907+begin
908+ if k in {kF32, kF64} then realOp(sy, k); return; end;
909+ bits := size * 8;
910+ (* a constant on the left of an operation whose order doesn't matter
911+ goes right, where it can be an immediate or a shift *)
912+ if (((sy = Scan.sPlus) or (sy = Scan.sTimes) or (sy = Scan.sAmp) or (sy = Scan.sBar) or (sy = Scan.sXor))) and (stack[depth - 2].loc = lConst)
913+ and (stack[depth - 1].loc # lConst) then swap(); end;
914+ c, v := topConst();
915+ (* A word's offset (see Entry) is carried through + and -, and
916+ through * by a constant, as (x + a) * k is x * k + a * k: the
917+ operation is done on the registers, the offsets worked out here,
918+ and put on the result. x + 1 is only noted. A value changed in
919+ place, lInto, has no offset. *)
920+ o := 0;
921+ if (bits = 64) and (stack[depth - 2].loc # lInto)
922+ and ((((sy = Scan.sPlus) or (sy = Scan.sMinus))) or ((sy = Scan.sTimes) and c and fits32(v))) then
923+ o := takeOff(depth - 2);
924+ if sy = Scan.sTimes then o := o * v;
925+ elsif c and fits32(v) then
926+ if sy = Scan.sPlus then o := o + v; else o := o - v; end;
927+ drop();
928+ if not (stack[depth - 1].loc in {lReg, lHeld}) then _ := top(); end;
929+ putOff(o);
930+ return;
931+ elsif sy = Scan.sPlus then o := o + takeOff(depth - 1);
932+ else o := o - takeOff(depth - 1); end;
933+ end;
934+ sh := -1;
935+ if c and (((sy = Scan.sTimes) or (sy = Scan.sDiv) or (sy = Scan.sMod))) then sh := exactLog2(v); end;
936+ if c and (sh >= 1) then
937+ drop();
938+ r := top();
939+ if sy = Scan.sTimes then X.shiftI(X.shShl, r, sh); else divPow2(sy, r, sh, not signed); end;
940+ elsif c and fits32(v) and (((sy = Scan.sPlus) or (sy = Scan.sMinus) or (sy = Scan.sBar) or (sy = Scan.sXor) or (sy = Scan.sAmp) or (sy = Scan.sTimes) or (sy = Scan.sShl) or (sy = Scan.sShr))) then
941+ drop();
942+ r := top();
943+ match sy of
944+ | sTimes: X.imulI(r, INT(v));
945+ | sShl: X.shiftI(X.shShl, r, INT(v & I64(bits - 1)));
946+ | sShr:
947+ if signed then X.shiftI(X.shSar, r, INT(v & I64(bits - 1)));
948+ else X.shiftI(X.shShr, r, INT(v & I64(bits - 1))); end;
949+ | else: X.aluI(aluOf(sy), r, INT(v));
950+ end;
951+ elsif topInMem() and (((sy = Scan.sPlus) or (sy = Scan.sMinus) or (sy = Scan.sAmp) or (sy = Scan.sBar) or (sy = Scan.sXor))) then
952+ m := stack[depth - 1].m;
953+ drop();
954+ r := top();
955+ X.aluM(aluOf(sy), r, m);
956+ else
957+ r, y := operands();
958+ if ((sy = Scan.sPlus) or (sy = Scan.sMinus) or (sy = Scan.sAmp) or (sy = Scan.sBar) or (sy = Scan.sXor)) then
959+ X.alu(aluOf(sy), r, y);
960+ elsif sy = Scan.sTimes then
961+ X.imul(r, y);
962+ elsif ((sy = Scan.sDiv) or (sy = Scan.sMod)) then
963+ X.movRR(RAX, r);
964+ if not signed then
965+ X.movRI(RDX, 0); X.unary(6, y); (* div *)
966+ else
967+ (* only -1 can make the division overflow, so a constant
968+ divisor other than -1 needs no check *)
969+ if (bits < 64) and (not c or (v = -1)) then divTrap(bits, y); end;
970+ X.cqo(); X.unary(7, y); (* idiv, of rdx:rax, which cqo made from rax *)
971+ end;
972+ if sy = Scan.sDiv then X.movRR(r, RAX); else X.movRR(r, RDX); end;
973+ else (* sShl, sShr *)
974+ (* the count modulo the width: the machine takes it modulo 64 *)
975+ if y # RCX then X.movRR(RCX, y); end;
976+ if bits < 64 then X.aluI(X.aluAnd, RCX, bits - 1); end;
977+ if sy = Scan.sShl then X.shift(X.shShl, r);
978+ elsif signed then X.shift(X.shSar, r);
979+ else X.shift(X.shShr, r); end;
980+ end;
981+ end;
982+ if bits < 64 then X.extend(r, size, signed); end;
983+ stack[depth - 1].k := k;
984+ if o # 0 then putOff(o); end;
985+end;
986+
987+(* The left op the right of the two values on top, as a BOOL *)
988+proc compare*(sy: Scan.Sym; k: Kind; signed: BOOL);
989+var f: BOOL; r, x, y, i: INT; v: I64; c: BOOL; m: X.Mem;
990+begin
991+ i := INT(sy) - INT(Scan.sEql);
992+ if k in {kF32, kF64} then
993+ f := k = kF32;
994+ y := peek(depth - 1);
995+ drop();
996+ x := peek(depth - 1);
997+ drop();
998+ r := target(); (* the BOOL, in the left's integer register *)
999+ (* ucomis sets the flags as an unsigned comparison would, but for an
1000+ unordered pair (a NaN) it sets zero, parity and carry all. So only
1001+ "above" can be tested straight: it is false for NaN, as every
1002+ comparison but # must be. a < b is made b > a. = also asks for
1003+ no parity, as NaN = NaN sets the zero flag, and # asks for
1004+ parity as well. *)
1005+ match sy of
1006+ | sEql: X.ucomis(x, y, f); X.setCC(X.ccE, r); X.setCC(X.ccNP, RCX); X.alu(X.aluAnd, r, RCX);
1007+ | sNeq: X.ucomis(x, y, f); X.setCC(X.ccNE, r); X.setCC(X.ccP, RCX); X.alu(X.aluOr, r, RCX);
1008+ | sLss: X.ucomis(y, x, f); X.setCC(X.ccA, r);
1009+ | sLeq: X.ucomis(y, x, f); X.setCC(X.ccAE, r);
1010+ | sGtr: X.ucomis(x, y, f); X.setCC(X.ccA, r);
1011+ | else: X.ucomis(x, y, f); X.setCC(X.ccAE, r);
1012+ end;
1013+ computed(kWord);
1014+ else
1015+ c, v := topConst();
1016+ if c then
1017+ drop(); r := top(); cmpI(r, v);
1018+ elsif topInMem() then
1019+ m := stack[depth - 1].m; drop(); r := top(); X.aluM(X.aluCmp, r, m);
1020+ else
1021+ r, y := operands(); X.alu(X.aluCmp, r, y);
1022+ end;
1023+ if signed then X.setCC(CcSigned[i], r); else X.setCC(CcUnsigned[i], r); end;
1024+ end;
1025+ stack[depth - 1].k := kWord;
1026+end;
1027+
1028+(* A real is negated by flipping its sign bit, in rax *)
1029+proc neg*(k: Kind; size: INT; signed: BOOL);
1030+var r: INT;
1031+begin
1032+ r := top();
1033+ if k in {kF32, kF64} then
1034+ X.movqRX(RAX, r);
1035+ if k = kF32 then X.btc(RAX, 31); else X.btc(RAX, 63); end;
1036+ X.movqXR(r, RAX);
1037+ else
1038+ X.unary(3, r); (* neg *)
1039+ if size < 8 then X.extend(r, size, signed); end;
1040+ end;
1041+end;
1042+
1043+proc complement*(size: INT; signed: BOOL);
1044+var r: INT;
1045+begin
1046+ r := top();
1047+ X.unary(2, r); (* not *)
1048+ if size < 8 then X.extend(r, size, signed); end;
1049+end;
1050+
1051+proc notBool*;
1052+begin
1053+ X.aluI(X.aluXor, top(), 1);
1054+end;
1055+
1056+(* The integer on top, brought to size bytes *)
1057+proc narrow*(size: INT; signed: BOOL);
1058+var r: INT;
1059+begin
1060+ r := top();
1061+ if size < 8 then X.extend(r, size, signed); end;
1062+ stack[depth - 1].k := kWord;
1063+end;
1064+
1065+(* The integer on top, as a real of kind k; big if it may be a U64 above
1066+ high(I64), which the machine would take as negative *)
1067+proc intToReal*(k: Kind; big: BOOL);
1068+var L1, L2, r, x: INT; f: BOOL;
1069+begin
1070+ f := k = kF32;
1071+ r := top();
1072+ x := regIn(k, depth - 1); (* its xmm register *)
1073+ if big then
1074+ (* above high(I64): halve, keeping the low bit, and double *)
1075+ L1 := NoLabel; L2 := NoLabel;
1076+ X.testRR(r, r);
1077+ X.jcc(X.ccS, L1);
1078+ X.cvtsi2s(x, r, f);
1079+ X.jmp(L2);
1080+ X.fixLink(L1);
1081+ X.movRR(RCX, r);
1082+ X.shiftI(X.shShr, RCX, 1);
1083+ X.aluI(X.aluAnd, r, 1);
1084+ X.alu(X.aluOr, RCX, r);
1085+ X.cvtsi2s(x, RCX, f);
1086+ X.sse(58H, x, x, f); (* adds it to itself: doubles *)
1087+ X.fixLink(L2);
1088+ else
1089+ X.cvtsi2s(x, r, f);
1090+ end;
1091+ stack[depth - 1].k := k;
1092+end;
1093+
1094+(* The real of kind k on top, truncated to an integer *)
1095+proc realToInt*(k: Kind);
1096+var x: INT;
1097+begin
1098+ x := top();
1099+ X.cvtts2si(regIn(kWord, depth - 1), x, k = kF32);
1100+ stack[depth - 1].k := kWord;
1101+end;
1102+
1103+(* The real of kind k on top, as the other kind *)
1104+proc realToReal*(k: Kind);
1105+var x: INT;
1106+begin
1107+ x := top();
1108+ X.sse(5AH, x, x, k = kF32); (* cvtss2sd, or cvtsd2ss *)
1109+ if k = kF32 then stack[depth - 1].k := kF64; else stack[depth - 1].k := kF32; end;
1110+end;
1111+
1112+(* Whether the slices in the frame at a and b (the offsets of their
1113+ pointers, the lengths 8 bytes on) are equal (or not, if not eq): the
1114+ lengths, then the bytes, len shl shift of them, compared where the
1115+ comparison stands. *)
1116+proc compareSeq*(a, b: I64; shift: INT; eq: BOOL);
1117+var differ, r: INT;
1118+begin
1119+ clobberArgs();
1120+ r := target();
1121+ X.load(RCX, X.mem(RBP, b + 8), 8, false);
1122+ X.aluM(X.aluCmp, RCX, X.mem(RBP, a + 8));
1123+ differ := NoLabel;
1124+ X.jcc(X.ccNE, differ);
1125+ X.load(RSI, X.mem(RBP, b), 8, false);
1126+ X.load(RDI, X.mem(RBP, a), 8, false);
1127+ if shift > 0 then X.shiftI(X.shShl, RCX, shift); end;
1128+ (* repe cmpsb with rcx = 0 leaves the flags alone, so make them say
1129+ equal first, which is right if there are no bytes *)
1130+ X.alu(X.aluCmp, RCX, RCX);
1131+ X.repeCmpsb();
1132+ X.fixLink(differ);
1133+ if eq then X.setCC(X.ccE, r); else X.setCC(X.ccNE, r); end;
1134+ computed(kWord);
1135+end;
1136+
1137+(* An error points at its message's length, an 8-byte word, with the
1138+ text after it; nil is no error. Pops one, and makes the slice of its
1139+ message at tmp, empty for nil. *)
1140+proc errorText*(tmp: I64);
1141+var L: INT;
1142+begin
1143+ popTo(RAX);
1144+ X.movRI(RCX, 0);
1145+ L := NoLabel;
1146+ X.testRR(RAX, RAX);
1147+ X.jcc(X.ccE, L);
1148+ X.load(RCX, X.mem(RAX, 0), 8, false);
1149+ X.lea(RAX, X.mem(RAX, 8));
1150+ X.fixLink(L);
1151+ X.store(X.mem(RBP, tmp), RAX, 8);
1152+ X.store(X.mem(RBP, tmp + 8), RCX, 8);
1153+end;
1154+
1155+(* Pops a step and an integer variable's address, and adds the step to
1156+ it, or takes it away. *)
1157+proc incDec*(size: INT; signed, dec: BOOL);
1158+var r, y, o: INT; v: I64; a: Adr; c: BOOL;
1159+begin
1160+ c, v := topConst();
1161+ if dec then o := X.aluSub; else o := X.aluAdd; end;
1162+ if c and fits32(v) then
1163+ drop();
1164+ a.base := bStack; a.off := 0;
1165+ X.aluMI(o, place(a, RCX), INT(v), size);
1166+ return;
1167+ end;
1168+ r, y := operands();
1169+ drop();
1170+ X.load(RAX, X.mem(r, 0), size, signed);
1171+ X.alu(o, RAX, y);
1172+ X.store(X.mem(r, 0), RAX, size);
1173+end;
1174+
1175+(* INC or DEC of the variable in register r, by the value on top; a
1176+ narrow one wraps at its width *)
1177+proc incDecReg*(r, size: INT; signed, dec: BOOL);
1178+var y, o: INT; v: I64; c: BOOL;
1179+begin
1180+ if dec then o := X.aluSub; else o := X.aluAdd; end;
1181+ c, v := topConst();
1182+ if c and fits32(v) then X.aluI(o, r, INT(v));
1183+ else y := top(); X.alu(o, r, y); end;
1184+ drop();
1185+ if size < 8 then X.extend(r, size, signed); end;
1186+end;
1187+
1188+(* The pointer on top, which NEW got, to size zero bytes unless nil *)
1189+proc zeroNew*(size: I64);
1190+var L, r: INT;
1191+begin
1192+ clobberArgs();
1193+ r := top();
1194+ L := NoLabel;
1195+ X.testRR(r, r);
1196+ X.jcc(X.ccE, L);
1197+ X.movRR(RDI, r);
1198+ X.movRI(RCX, size);
1199+ X.movRI(RAX, 0);
1200+ X.repStosb();
1201+ X.fixLink(L);
1202+end;
1203+
1204+(* CAS(p, old, new), XCHG(p, v) or XADD(p, v), from the stack: the
1205+ result where p was *)
1206+proc atomic*(which: INT);
1207+var r, n: INT;
1208+begin
1209+ if which = Sym.bCas then readMems(depth - 3); else readMems(depth - 2); end; (* what it writes may be one *)
1210+ if which = Sym.bCas then n := top(); drop(); end;
1211+ popTo(RAX); (* cmpxchg compares with rax, so CAS's old value goes there *)
1212+ r := top();
1213+ match which of
1214+ | Sym.bCas: X.lockCmpxchg(X.mem(r, 0), n); X.setCC(X.ccE, r);
1215+ | Sym.bXchg: X.xchg(X.mem(r, 0), RAX); X.movRR(r, RAX);
1216+ | else: X.lockXadd(X.mem(r, 0), RAX); X.movRR(r, RAX);
1217+ end;
1218+ stack[depth - 1].k := kWord;
1219+end;
1220+
1221+(* The system call and its arguments, n values on the stack. Linux takes
1222+ the number in rax and the arguments in rdi, rsi, rdx, r10, r8 and r9,
1223+ and the syscall instruction clobbers rcx and r11. Every value in a
1224+ register is spilled first, as r8 to r11 are the stack's registers,
1225+ and the arguments are loaded from their slots. *)
1226+proc sysCall*(n: INT);
1227+const SysRegs: [7]INT = [RAX, RDI, RSI, RDX, R10, R8, R9];
1228+var i: INT;
1229+begin
1230+ clobberArgs();
1231+ spillBelow(depth);
1232+ for i := 0 to n - 1 do valueTo(depth - n + i, SysRegs[i]); end;
1233+ for i := 1 to n do drop(); end;
1234+ X.syscall();
1235+ X.movRR(target(), RAX);
1236+ computed(kWord);
1237+end;
1238+
1239+proc fence*;
1240+begin
1241+ X.mfence();
1242+end;
1243+
1244+(* Jumps. A label is the chain of the jumps to it, until it is placed. *)
1245+
1246+proc jump*(var L: INT);
1247+begin
1248+ X.jmp(L);
1249+end;
1250+
1251+(* Pops a BOOL, and jumps if it is when *)
1252+proc jumpIf*(var L: INT; when: BOOL);
1253+var r: INT;
1254+begin
1255+ r := peek(depth - 1);
1256+ drop();
1257+ X.testRR(r, r);
1258+ if when then X.jcc(X.ccNE, L); else X.jcc(X.ccE, L); end;
1259+end;
1260+
1261+(* Pops two integers, and jumps if the left op the right *)
1262+proc jumpCmp*(sy: Scan.Sym; signed: BOOL; var L: INT);
1263+var r, y, i: INT; v: I64; c: BOOL; m: X.Mem;
1264+begin
1265+ i := INT(sy) - INT(Scan.sEql);
1266+ (* a comparison changes neither: a variable's register will do *)
1267+ c, v := topConst();
1268+ if c then
1269+ drop(); r := peek(depth - 1); cmpI(r, v);
1270+ elsif topInMem() then
1271+ m := stack[depth - 1].m; drop(); r := peek(depth - 1); X.aluM(X.aluCmp, r, m);
1272+ else
1273+ y := peek(depth - 1); drop(); r := peek(depth - 1); X.alu(X.aluCmp, r, y);
1274+ end;
1275+ drop();
1276+ if signed then X.jcc(CcSigned[i], L); else X.jcc(CcUnsigned[i], L); end;
1277+end;
1278+
1279+(* jumpCmp out of an expression, past code that may spill: the values
1280+ under the two compared are spilled first, so that they are where the
1281+ code after the landing place expects them, whichever way it came. In
1282+ v + (a < b and f(x) = 0), a call to f spills v on the way through, so
1283+ v must be in its slot too where a < b jumps past the call. *)
1284+proc jumpOut*(sy: Scan.Sym; signed: BOOL; var L: INT);
1285+begin
1286+ spillBelow(depth - 2);
1287+ jumpCmp(sy, signed, L);
1288+end;
1289+
1290+(* The two values on top, compared, as a BOOL: true unless notOp, the
1291+ opposite comparison, holds. fj and tj are the chains of jumps, made
1292+ earlier by and, or and not, that are taken when the whole condition is
1293+ false and when it is true; they land here, on the 0 and the 1. *)
1294+proc condValue*(notOp: Scan.Sym; signed: BOOL; fj, tj: INT);
1295+var r, e: INT;
1296+begin
1297+ jumpOut(notOp, signed, fj);
1298+ X.fixLink(tj);
1299+ r := target();
1300+ X.movRI(r, 1);
1301+ e := NoLabel;
1302+ X.jmp(e);
1303+ X.fixLink(fj);
1304+ X.movRI(r, 0);
1305+ X.fixLink(e);
1306+ computed(kWord);
1307+end;
1308+
1309+(* jumpBack, fix, fixTo and joinJumps are Gen's names for the encoder's,
1310+ so that a port can place jumps its own way. fix(L) places label L here;
1311+ fixTo(L, top) makes every jump on chain L go to the earlier place top;
1312+ joinJumps makes one chain of two. *)
1313+proc jumpBack*(top: INT);
1314+begin
1315+ X.jmpBack(top);
1316+end;
1317+
1318+proc fix*(L: INT);
1319+begin
1320+ X.fixLink(L);
1321+end;
1322+
1323+(* A jump table, for a match on the integer in frame slot slot, whose
1324+ labels run from lo up for n values. The selector less lo, compared
1325+ unsigned (so below lo is above n too), is out of the table if it
1326+ isn't below n, and goes to the else arm at elseAt, or, if there is
1327+ none, to endL, the end of the match. Else it indexes a table of
1328+ 4-byte offsets, each from the start of the lea, that follows the
1329+ jump, and the code jumps to its start plus the entry:
1330+
1331+ mov rax, [slot]
1332+ sub rax, lo
1333+ cmp rax, n - 1
1334+ ja else
1335+ lea rcx, [rip + start] start: this very lea
1336+ movsxd rax, [rcx + rax*4 + 17]
1337+ add rax, rcx
1338+ jmp rax
1339+ table: .long arm0 - start, arm1 - start, ...
1340+
1341+ The four instructions after the compare are 7, 5, 3 and 2 bytes, so
1342+ the table is 17 bytes on, which jumpTable checks. It returns start;
1343+ the caller then makes the n entries with tableEntry. *)
1344+proc jumpTable*(slot, lo: I64; n, elseAt: INT; var endL: INT): INT;
1345+const TableAt = 17;
1346+var start: INT;
1347+begin
1348+ X.load(RAX, X.mem(RBP, slot), 8, false);
1349+ if lo # 0 then X.aluI(X.aluSub, RAX, INT(lo)); end;
1350+ X.aluI(X.aluCmp, RAX, n - 1);
1351+ if elseAt # NoLabel then X.jccBack(X.ccA, elseAt); else X.jcc(X.ccA, endL); end;
1352+ start := Chunk.pc;
1353+ X.lea(RCX, X.here());
1354+ X.load(RAX, X.memIdx(RCX, RAX, 4, TableAt), 4, true);
1355+ X.alu(X.aluAdd, RAX, RCX);
1356+ X.jmpR(RAX);
1357+ if Chunk.pc # start + TableAt then Diag.fatal("internal error: the jump table is not where it was said"); end;
1358+ return start;
1359+end;
1360+
1361+(* The next entry of the table that jumpTable started at table: the
1362+ code at target *)
1363+proc tableEntry*(table, target: INT);
1364+begin
1365+ Chunk.put4(target - table);
1366+end;
1367+
1368+proc alignLoop*;
1369+begin
1370+ X.align(32);
1371+end;
1372+
1373+proc joinJumps*(L1, L2: INT): INT;
1374+begin
1375+ return X.joinLinks(L1, L2);
1376+end;
1377+
1378+proc fixTo*(L, top: INT);
1379+begin
1380+ X.fixLinkTo(L, top);
1381+end;
1382+
1383+(* Checks *)
1384+
1385+const
1386+ NoBase = -2; (* a Mem that is no memory *)
1387+ ARegister = -3; (* a Mem that is no memory but a register, its index *)
1388+
1389+(* The name s, interned *)
1390+proc internStr(s: []U8): INT;
1391+begin
1392+ return Scan.intern(ADR(s[0]), LEN(s));
1393+end;
1394+
1395+(* The program goes on if the condition cc holds, and otherwise stops
1396+ in Rt.fail(what, a, b, len, at, name), which says what failed at p,
1397+ found by at, which a stub works out from where it was called; what is
1398+ an index a (0), a slice a..b (1), each for a length len, a position a
1399+ of the enumeration called name (2), a slice of a pointer a..b that
1400+ runs backwards (3), or a nil pointer (4). Rt.fail knows 5 and 6, a
1401+ division fault and a stack overflow, which this machine catches
1402+ itself, so no check here has them. The arguments go in rdi, rsi, rdx,
1403+ rcx, r8 and r9: a is in register ra, b in RDX; len is in memory at m,
1404+ or n if m.base is NoBase, or in register m.index if it is ARegister.
1405+ rdi and rsi are passed on as they were, since a parameter may be kept
1406+ in them, for the trap report to show: so a goes to the stub in rax.
1407+ The failing code is out of the way, at the
1408+ procedure's end (endFails), so that a check that holds costs a jump
1409+ not taken; it has p for its place (at is p's offset in the source),
1410+ never returns, and may use any register once it has read what it
1411+ needs. *)
1412+proc check(cc, what: INT; p: Diag.Pos; ra: INT; m: X.Mem; n: I64; name: INT);
1413+begin
1414+ if numFails > LEN(fails) - 1 then
1415+ _ := Scan.mark(Diag.say("more than {} checks in one procedure", [Fmt.int(LEN(fails))]));
1416+ return;
1417+ end;
1418+ fails[numFails].L := NoLabel;
1419+ X.jcc(cc xor 1, fails[numFails].L); (* x86's conditions come in pairs, the other one its last bit flipped *)
1420+ fails[numFails].what := what;
1421+ fails[numFails].ra := ra;
1422+ fails[numFails].m := m;
1423+ fails[numFails].n := n;
1424+ fails[numFails].name := name;
1425+ fails[numFails].at := p.a;
1426+ INC(numFails);
1427+end;
1428+
1429+(* The failures of the procedure's checks: each gives Rt.fail its values
1430+ and the place of the offending expression, through a stub for its
1431+ kind, which takes the place from where it was called *)
1432+proc endFails;
1433+var i, line, col: INT; f: Fail;
1434+begin
1435+ for i := 0 to numFails - 1 do
1436+ f := fails[i];
1437+ X.fixLink(f.L);
1438+ line, col := Scan.lineCol(f.at);
1439+ Chunk.noteLine(line, col);
1440+ if f.ra # RAX then X.movRR(RAX, f.ra); end;
1441+ if f.m.base = NoBase then X.movRI(RCX, f.n);
1442+ elsif f.m.base = ARegister then X.movRR(RCX, f.m.index);
1443+ else X.load(RCX, f.m, 8, false); end;
1444+ if f.name >= 0 then X.lea(R9, X.memRip(f.name, 0)); end;
1445+ if failStubs[f.what] < 0 then
1446+ failStubs[f.what] := Chunk.newChunk(Chunk.secText, internStr("Rt"), internStr(StubNames[f.what]));
1447+ end;
1448+ X.callChunk(failStubs[f.what]);
1449+ end;
1450+ numFails := 0;
1451+end;
1452+
1453+(* For check: a length known here, not in memory *)
1454+proc noMem: X.Mem;
1455+begin
1456+ return X.mem(NoBase, 0);
1457+end;
1458+
1459+(* For check: a length in register r, a slice's in registers *)
1460+proc inRegister(r: INT): X.Mem;
1461+var m: X.Mem;
1462+begin
1463+ m := X.mem(ARegister, 0);
1464+ m.index := r;
1465+ return m;
1466+end;
1467+
1468+(* The index on top is below n, unsigned *)
1469+proc checkIndex*(n: I64; p: Diag.Pos);
1470+var r: INT;
1471+begin
1472+ r := peek(depth - 1);
1473+ cmpI(r, n);
1474+ check(X.ccB, 0, p, r, noMem(), n, -1);
1475+end;
1476+
1477+(* The integer on top is a position of an enumeration of n names *)
1478+proc checkEnum*(n: I64; name: INT; p: Diag.Pos);
1479+var r: INT;
1480+begin
1481+ r := top();
1482+ cmpI(r, n);
1483+ check(X.ccB, 2, p, r, noMem(), n, name);
1484+end;
1485+
1486+(* The address on top, from a pointer, which is to be used reach bytes
1487+ past: the program stops if it is nil, unless the machine would stop
1488+ it, as for a reach within NilPage. *)
1489+proc checkNil*(reach: I64; p: Diag.Pos);
1490+var r: INT;
1491+begin
1492+ if reach <= NilPage then return; end;
1493+ r := top();
1494+ X.testRR(r, r);
1495+ check(X.ccNE, 4, p, r, noMem(), 0, -1);
1496+end;
1497+
1498+(* The displacement disp of an element of size bytes, with the offset of
1499+ the index on top taken into it if it fits: s[k - 1] is [r13 + r9 * 8
1500+ - 8] *)
1501+proc indexOff(size, disp: I64): I64;
1502+begin
1503+ if fits32(disp + stack[depth - 1].off * size) then return disp + takeOff(depth - 1) * size; end;
1504+ return disp;
1505+end;
1506+
1507+(* Pops an index, and the address of the slice at a if it is on the
1508+ stack, and pushes the address of its element of size bytes: the
1509+ index, checked against the length, times size, plus the pointer.
1510+ It is worked out in the index's own register, which then holds the
1511+ address; but if the slice's address is on the stack, under the
1512+ index, the element's register is the one that holds that, still
1513+ needed, so the work is done in rax. A slice in registers is
1514+ compared with and added to them; for an element of 1, 2, 4 or 8
1515+ bytes, its address is only noted, as the operand [pointer + index *
1516+ size], to be read or written where it is used (lIdx). *)
1517+proc indexSlice*(a: Adr; size: I64; checked: BOOL; p: Diag.Pos);
1518+var m, ml: X.Mem; r: INT; inRax: BOOL; o: I64;
1519+begin
1520+ if (a.base = bReg) and (((size = 1) or (size = 2) or (size = 4) or (size = 8))) then
1521+ o := 0;
1522+ if not checked then o := indexOff(size, 0); end;
1523+ r := peek(depth - 1);
1524+ if checked then
1525+ X.alu(X.aluCmp, r, a.hi);
1526+ check(X.ccB, 0, p, r, inRegister(a.hi), 0, -1);
1527+ end;
1528+ drop();
1529+ newMem(lIdx, X.memIdx(a.chunk, r, INT(size), o), kWord, 8, false);
1530+ return;
1531+ end;
1532+ inRax := a.base = bStack;
1533+ if inRax then r := RAX; popTo(RAX);
1534+ else r := top(); drop(); end;
1535+ if a.base = bReg then
1536+ if checked then
1537+ X.alu(X.aluCmp, r, a.hi);
1538+ check(X.ccB, 0, p, r, inRegister(a.hi), 0, -1);
1539+ end;
1540+ mulI(r, size);
1541+ X.alu(X.aluAdd, r, a.chunk);
1542+ else
1543+ m := place(a, RCX);
1544+ ml := m; ml.disp := ml.disp + 8;
1545+ if checked then
1546+ X.aluM(X.aluCmp, r, ml);
1547+ check(X.ccB, 0, p, r, ml, 0, -1);
1548+ end;
1549+ mulI(r, size);
1550+ X.aluM(X.aluAdd, r, m);
1551+ end;
1552+ if inRax then X.movRR(target(), RAX);
1553+ else _ := claim(depth, kWord); end; (* the index's register again, now for the address *)
1554+ computed(kWord);
1555+end;
1556+
1557+(* Pops an index, checked, and makes the address of the element it
1558+ picks of the array at a. An element of 1, 2,
1559+ 4 or 8 bytes is only noted, as the operand [base + index * size]
1560+ (lIdx): an array in the frame has rbp as its base, and one in a
1561+ chunk, if the index is a variable's register, its address made in
1562+ the value's own register. Any other is added up. *)
1563+proc indexArray*(a: Adr; size: I64);
1564+var r, b: INT; o: I64;
1565+begin
1566+ if (((size = 1) or (size = 2) or (size = 4) or (size = 8))) and (a.base = bFrame) then
1567+ o := indexOff(size, a.off);
1568+ r := peek(depth - 1);
1569+ drop();
1570+ newMem(lIdx, X.memIdx(RBP, r, INT(size), o), kWord, 8, false);
1571+ elsif (((size = 1) or (size = 2) or (size = 4) or (size = 8))) and (a.base = bGlobal) and (stack[depth - 1].loc = lHeld) then
1572+ o := indexOff(size, 0);
1573+ r := peek(depth - 1);
1574+ drop();
1575+ b := target();
1576+ X.lea(b, X.memRip(a.chunk, INT(a.off)));
1577+ newMem(lIdx, X.memIdx(b, r, INT(size), o), kWord, 8, false);
1578+ else
1579+ mulI(top(), size);
1580+ pushAdr(a);
1581+ op(Scan.sPlus, kWord, 8, false);
1582+ end;
1583+end;
1584+
1585+(* Pops lo and hi, and the address of the array or slice at a if it is
1586+ on the stack, and makes the slice lo..hi of it, with elements of size
1587+ bytes, in the frame at tmp; the array has n elements. *)
1588+proc slice*(a: Adr; isArray: BOOL; n, size, tmp: I64; checked: BOOL; p: Diag.Pos);
1589+var m, ml: X.Mem;
1590+begin
1591+ popTo(RDX);
1592+ popTo(RCX);
1593+ if a.base = bSlot then clobberArgs(); end; (* place loads its slot into rdi *)
1594+ if a.base = bReg then
1595+ ml := inRegister(a.hi); (* a slice in registers *)
1596+ else
1597+ m := place(a, RDI);
1598+ ml := m; ml.disp := ml.disp + 8;
1599+ end;
1600+ if checked then
1601+ (* two checks, both unsigned, so that a negative bound fails too:
1602+ hi against the length, then lo against hi *)
1603+ if isArray then cmpI(RDX, n); ml := noMem();
1604+ elsif a.base = bReg then X.alu(X.aluCmp, RDX, a.hi);
1605+ else X.aluM(X.aluCmp, RDX, ml); end;
1606+ check(X.ccBE, 1, p, RCX, ml, n, -1);
1607+ X.alu(X.aluCmp, RCX, RDX);
1608+ check(X.ccBE, 1, p, RCX, ml, n, -1);
1609+ end;
1610+ X.movRR(RAX, RDX);
1611+ X.alu(X.aluSub, RAX, RCX);
1612+ X.store(X.mem(RBP, tmp + 8), RAX, 8);
1613+ mulI(RCX, size);
1614+ if isArray then X.lea(RAX, m);
1615+ elsif a.base = bReg then X.movRR(RAX, a.chunk);
1616+ else X.load(RAX, m, 8, false); end;
1617+ X.alu(X.aluAdd, RAX, RCX);
1618+ X.store(X.mem(RBP, tmp), RAX, 8);
1619+end;
1620+
1621+(* COPY: the elements of the slice in the frame at sOff, of size bytes
1622+ each, to the start of the one at dOff, which must be at least as long
1623+ (the source may be shorter), as one block; backwards when the
1624+ destination is above the source, so that an overlap comes out right. *)
1625+proc copySlice*(dOff, sOff, size: I64; checked: BOOL; p: Diag.Pos);
1626+var ml: X.Mem; L, E: INT;
1627+begin
1628+ clobberArgs();
1629+ X.load(RDX, X.mem(RBP, sOff + 8), 8, false);
1630+ if checked then
1631+ ml := X.mem(RBP, dOff + 8);
1632+ X.movRI(RAX, 0);
1633+ X.aluM(X.aluCmp, RDX, ml);
1634+ check(X.ccBE, 1, p, RAX, ml, 0, -1);
1635+ end;
1636+ X.movRR(RCX, RDX);
1637+ mulI(RCX, size);
1638+ X.load(RSI, X.mem(RBP, sOff), 8, false);
1639+ X.load(RDI, X.mem(RBP, dOff), 8, false);
1640+ X.alu(X.aluCmp, RDI, RSI);
1641+ L := NoLabel;
1642+ X.jcc(X.ccBE, L); (* the destination is not above: forwards, at L *)
1643+ (* backwards: std makes rep movsb run downward, so it starts at the
1644+ last byte of each *)
1645+ X.lea(RSI, X.memIdx(RSI, RCX, 1, -1));
1646+ X.lea(RDI, X.memIdx(RDI, RCX, 1, -1));
1647+ X.std();
1648+ X.repMovsb();
1649+ X.cld();
1650+ E := NoLabel;
1651+ X.jmp(E);
1652+ X.fixLink(L);
1653+ X.repMovsb();
1654+ X.fixLink(E);
1655+end;
1656+
1657+(* Pops a pointer, lo and hi, and makes the slice p[lo..hi] at tmp. Its
1658+ bounds can't be known, but it can't run backwards. *)
1659+proc slicePtr*(size, tmp: I64; checked: BOOL; p: Diag.Pos);
1660+begin
1661+ clobberArgs();
1662+ popTo(RDX);
1663+ popTo(RCX);
1664+ popTo(RDI);
1665+ if checked then
1666+ X.alu(X.aluCmp, RCX, RDX);
1667+ check(X.ccLE, 3, p, RCX, noMem(), 0, -1);
1668+ end;
1669+ X.movRR(RAX, RDX);
1670+ X.alu(X.aluSub, RAX, RCX);
1671+ X.store(X.mem(RBP, tmp + 8), RAX, 8);
1672+ mulI(RCX, size);
1673+ X.alu(X.aluAdd, RCX, RDI);
1674+ X.store(X.mem(RBP, tmp), RCX, 8);
1675+end;
1676+
1677+(* Calls *)
1678+
1679+(* The call c, its c.n arguments the values on top of the stack, in
1680+ registers, noted as constants or spilled. They go to registers or the
1681+ machine's stack, the procedure is called, and its result, if any,
1682+ comes back: one value is pushed, two results are pushed as two values,
1683+ a slice or a record is stored in the temporary c.ret.
1684+
1685+ ni and nf count the integer and the real registers used so far, k the
1686+ arguments on the machine's stack, and pad is 1 when a padding quadword
1687+ is needed. *)
1688+
1689+proc call*(var c: CallInfo);
1690+var
1691+ res: ^Sym.Type; i, ni, nf, k, pad, r, first: INT;
1692+ onStack: [64]BOOL; late: [2]INT; (* late: the values for r8 and r9 *)
1693+begin
1694+ (* the arguments are the c.n values on top, where computing them left
1695+ them; the registers in use under them are saved around the call *)
1696+ clobberArgs();
1697+ first := depth - c.n;
1698+ spillBelow(first);
1699+ res := c.sig^.base;
1700+ c.ret := 0;
1701+ ni := 0; nf := 0;
1702+ if (res # nil) and (Sym.behindPointer(res) or (res^.form = Sym.fSlice)) then
1703+ c.ret := allocTemp(res^.size, res^.align);
1704+ if Sym.behindPointer(res) then ni := 1; end;
1705+ end;
1706+ (* the System V classes: each argument in the next free register of
1707+ its kind, or else on the stack *)
1708+ k := 0;
1709+ for i := 0 to c.n - 1 do
1710+ if c.isF[i] then
1711+ onStack[i] := nf >= 8;
1712+ if nf < 8 then INC(nf); end;
1713+ else
1714+ (* a slice's words both go in registers, or both on the stack *)
1715+ if (i > 0) and c.pair[i - 1] then onStack[i] := onStack[i - 1];
1716+ elsif c.pair[i] then onStack[i] := ni > 4;
1717+ else onStack[i] := ni >= 6; end;
1718+ if not onStack[i] then INC(ni); end;
1719+ end;
1720+ if onStack[i] then INC(k); end;
1721+ end;
1722+ (* System V wants rsp a multiple of 16 at the call. A procedure's body
1723+ has it so (push rbp, and a frame size that is a multiple of 16), so
1724+ a quadword of padding makes the count pushed since even. The stack
1725+ arguments go right to left, so that the first is at the lowest
1726+ address. *)
1727+ pad := 0;
1728+ if ((pushed + k) & 1) # 0 then pad := 1; end;
1729+ if pad # 0 then X.aluI(X.aluSub, RSP, 8); end;
1730+ for i := c.n - 1 to 0 by -1 do
1731+ if onStack[i] then
1732+ valueTo(first + i, RAX);
1733+ X.push(RAX);
1734+ end;
1735+ end;
1736+ ni := 0; nf := 0;
1737+ late[0] := -1; late[1] := -1;
1738+ if (c.ret # 0) and Sym.behindPointer(res) then X.lea(RDI, X.mem(RBP, c.ret)); ni := 1; end;
1739+ (* rdi, rsi, rdx, rcx and the xmm registers first; r8 and r9 last, as
1740+ they are stack registers and may hold arguments not yet moved: late
1741+ is the value for each. The fifth goes through rax, so that writing r8
1742+ doesn't destroy a value still wanted for r9. *)
1743+ for i := 0 to c.n - 1 do
1744+ if not onStack[i] then
1745+ if c.isF[i] then
1746+ xValueTo(first + i, nf);
1747+ INC(nf);
1748+ else
1749+ if ni < 4 then valueTo(first + i, IntRegs[ni]); else late[ni - 4] := first + i; end;
1750+ INC(ni);
1751+ end;
1752+ end;
1753+ end;
1754+ if late[0] >= 0 then valueTo(late[0], RAX); end;
1755+ if late[1] >= 0 then valueTo(late[1], R9); end;
1756+ if late[0] >= 0 then X.movRR(R8, RAX); end;
1757+ for i := 1 to c.n do drop(); end;
1758+ (* a procedure taking ... is told in al how many xmm registers it got *)
1759+ if c.sig^.variadic then X.movRI(RAX, nf); end;
1760+ if c.ext then X.callM(X.memRip(c.chunk, 0));
1761+ elsif c.chunk >= 0 then X.callChunk(c.chunk);
1762+ else
1763+ (* r11 is scratch: caller-saved, carrying no argument, and free,
1764+ as the value stack was spilled above *)
1765+ X.load(R11, X.mem(RBP, c.target), 8, false);
1766+ X.callR(R11);
1767+ end;
1768+ if k + pad > 0 then X.aluI(X.aluAdd, RSP, 8 * (k + pad)); end;
1769+ (* the variables in xmm registers, which the call may have changed,
1770+ from their slots *)
1771+ for i := 0 to 3 do
1772+ if (regMask & (1 shl (XBit + i))) # 0 then
1773+ X.movsXM(XVarRegs[i] - XmmVar, X.mem(RBP, homes[i]), false);
1774+ end;
1775+ end;
1776+ (* the result: a slice in rax and rdx goes to the caller's temporary,
1777+ two results on the stack, the first under the second, and a single
1778+ value on top *)
1779+ if res # nil then
1780+ if res^.form = Sym.fSlice then
1781+ X.store(X.mem(RBP, c.ret), RAX, 8);
1782+ X.store(X.mem(RBP, c.ret + 8), RDX, 8);
1783+ elsif Sym.inTwoRegs(res) then
1784+ X.movRR(target(), RAX); computed(kWord);
1785+ X.movRR(target(), RDX); computed(kWord);
1786+ elsif (c.ret = 0) and (res^.form = Sym.fReal) then
1787+ X.movX(xTarget(), 0);
1788+ computed(kindOf(res));
1789+ elsif c.ret = 0 then
1790+ r := target();
1791+ X.movRR(r, RAX);
1792+ if res^.form = Sym.fBool then X.extend(r, 1, false);
1793+ elsif (res^.form = Sym.fInt) and (res^.size < 8) then X.extend(r, INT(res^.size), res^.signed); end;
1794+ computed(kindOf(res));
1795+ end;
1796+ end;
1797+end;
1798+
1799+(* Frames *)
1800+
1801+(* A slot of size bytes in the frame: its offset from rbp, negative, as
1802+ the frame grows down. A temporary is released at the end of its
1803+ statement (tempMark, releaseTemps); allocPerm's lasts the procedure. *)
1804+proc allocTemp*(size, align: I64): I64;
1805+begin
1806+ if align < 1 then align := 1; end;
1807+ frameTop := Sym.alignUp(frameTop + size, align);
1808+ if frameTop > frameMax then frameMax := frameTop; end;
1809+ return -frameTop;
1810+end;
1811+
1812+proc allocPerm*(size, align: I64): I64;
1813+var s: I64;
1814+begin
1815+ s := allocTemp(size, align);
1816+ permTop := frameTop;
1817+ return s;
1818+end;
1819+
1820+proc tempMark*: I64;
1821+begin
1822+ return frameTop;
1823+end;
1824+
1825+(* The slots allocated since the mark m are free again, but those
1826+ allocPerm made stay *)
1827+proc releaseTemps*(m: I64);
1828+begin
1829+ if m < permTop then m := permTop; end;
1830+ frameTop := m;
1831+end;
1832+
1833+(* Every slot used so far stays reserved for the rest of the procedure:
1834+ a deferred statement's temporaries live until it runs. *)
1835+proc keepTemps*;
1836+begin
1837+ frameTop := frameMax;
1838+ permTop := frameMax;
1839+end;
1840+
1841+(* The parameters' places: each in a frame slot of its own, stored there
1842+ from its register on entry, or above the frame where the caller
1843+ pushed it. A var parameter, and a record or array passed by value,
1844+ holds an address (ind). *)
1845+proc beginProc*(sig: ^Sym.Type; params: ^Sym.Obj);
1846+var p: ^Sym.Obj; ni, nf, k: INT; stackOff: I64; f: BOOL;
1847+begin
1848+ frameTop := 0; frameMax := 0; permTop := 0;
1849+ resetStack(0, 0);
1850+ exitL := NoLabel;
1851+ numIn := 0;
1852+ lost := false;
1853+ kept := 0;
1854+ resType := sig^.base;
1855+ procParams := params;
1856+ regMask := 0;
1857+ ni := 0; nf := 0; stackOff := 16; (* stackOff: above the saved rbp and the return address *)
1858+ if (resType # nil) and Sym.behindPointer(resType) then
1859+ retSlot := allocPerm(8, 8);
1860+ inReg[0] := RDI; inSlot[0] := retSlot; inSize[0] := 8; inObj[0] := nil;
1861+ numIn := 1; ni := 1;
1862+ end;
1863+ p := params;
1864+ while p # nil do
1865+ p^.ind := p^.isVar or (Sym.isAggregate(p^.typ) and (p^.typ^.form # Sym.fSlice));
1866+ f := (p^.typ^.form = Sym.fReal) and not p^.isVar;
1867+ if (p^.typ^.form = Sym.fSlice) and not p^.isVar then
1868+ (* its two words, in two registers or both on the stack *)
1869+ if ni <= 4 then
1870+ p^.val := allocPerm(16, 8);
1871+ for k := 0 to 1 do
1872+ inReg[numIn] := IntRegs[ni]; inSlot[numIn] := p^.val + I64(8 * k);
1873+ inSize[numIn] := 8; inObj[numIn] := p;
1874+ INC(numIn); INC(ni);
1875+ end;
1876+ else
1877+ p^.val := stackOff;
1878+ INC(stackOff, 16);
1879+ end;
1880+ elsif (f and (nf < 8)) or (not f and (ni < 6)) then
1881+ p^.val := allocPerm(8, 8);
1882+ (* a real's register, xmm nf, is told from an integer register by
1883+ a negative number (enterBody decodes it) *)
1884+ if f then
1885+ inReg[numIn] := -1 - nf; INC(nf);
1886+ else
1887+ inReg[numIn] := IntRegs[ni]; INC(ni);
1888+ end;
1889+ inSlot[numIn] := p^.val;
1890+ inObj[numIn] := p;
1891+ if p^.ind then inSize[numIn] := 8;
1892+ elsif p^.typ^.form in {Sym.fInt, Sym.fBool, Sym.fEnum, Sym.fSet, Sym.fReal} then inSize[numIn] := INT(p^.typ^.size);
1893+ else inSize[numIn] := 8; end;
1894+ INC(numIn);
1895+ else
1896+ p^.val := stackOff;
1897+ INC(stackOff, 8);
1898+ end;
1899+ p := p^.next;
1900+ end;
1901+ paramTop := frameTop;
1902+end;
1903+
1904+(* The frame as beginProc left it, with the parameters' slots only: the
1905+ locals are given theirs again once their registers are chosen. *)
1906+proc resetLocals*;
1907+begin
1908+ frameTop := paramTop; frameMax := paramTop; permTop := paramTop;
1909+end;
1910+
1911+(* The register the word (0, or 1 for a slice's second) of parameter o
1912+ arrives in, or -1 if it comes on the stack or in an xmm register *)
1913+proc arrivesIn(o: ^Sym.Obj; word: INT): INT;
1914+var i, r: INT;
1915+begin
1916+ r := -1;
1917+ for i := 0 to numIn - 1 do
1918+ if (inObj[i] = o) and (inSlot[i] = o^.val + I64(8 * word)) and (inReg[i] >= 0) then r := inReg[i]; end;
1919+ end;
1920+ return r;
1921+end;
1922+
1923+(* Parameter o, of a procedure that calls nothing, stays in the register
1924+ it arrives in if that is rdi or rsi, which only a call or a copy needs:
1925+ no register is saved for it, and nothing is moved. A slice stays only
1926+ if it has both. If the procedure turns out to copy after all, lost is
1927+ set, and it is compiled again with o in memory. *)
1928+proc keepArrived*(o: ^Sym.Obj);
1929+var r: INT;
1930+begin
1931+ r := arrivesIn(o, 0);
1932+ if o^.typ^.form = Sym.fSlice then
1933+ if (r = RDI) and (arrivesIn(o, 1) = RSI) then o^.reg := RDI; o^.reg2 := RSI; end;
1934+ elsif (r = RDI) or (r = RSI) then o^.reg := r; end;
1935+end;
1936+
1937+(* Whether parameter o is kept where it arrived *)
1938+proc keptIn*(o: ^Sym.Obj): BOOL;
1939+begin
1940+ return (o^.reg = RDI) or (o^.reg = RSI);
1941+end;
1942+
1943+(* The locals in memory have their slots: the prologue zeroes those and
1944+ nothing below. The procedure keeps variables in the registers of
1945+ mask, which are saved next, a quadword each, in slots that need no
1946+ zeroing; the frame as it then stands is where a second try at the
1947+ body starts. *)
1948+proc useRegs*(mask: INT);
1949+var i, k: INT; p: ^Sym.Obj;
1950+begin
1951+ zeroTop := permTop;
1952+ regMask := mask;
1953+ (* the parameters left in rdi and rsi, as they arrived *)
1954+ kept := 0;
1955+ p := procParams;
1956+ while p # nil do
1957+ if ((p^.reg = RDI) or (p^.reg = RSI)) then kept := kept | (1 shl p^.reg); end;
1958+ if ((p^.reg2 = RDI) or (p^.reg2 = RSI)) then kept := kept | (1 shl p^.reg2); end;
1959+ p := p^.next;
1960+ end;
1961+ k := 0;
1962+ for i := 0 to 4 do
1963+ if (mask & (1 shl i)) # 0 then INC(k); end;
1964+ end;
1965+ if k > 0 then saveAt := allocPerm(8 * k, 8); end;
1966+ frameAt[0] := frameTop; frameAt[1] := frameMax; frameAt[2] := permTop;
1967+end;
1968+
1969+(* The variable in xmm register r of XVarRegs has a slot of 8 bytes at
1970+ slot, kept as it changes *)
1971+proc xHome*(r: INT; slot: I64);
1972+begin
1973+ homes[r - XVarRegs[0]] := slot;
1974+end;
1975+
1976+proc markCode*(var m: CodeMark);
1977+begin
1978+ m.pc := Chunk.pc; m.fixups := Chunk.numFixups; m.lines := Chunk.numLines; m.said := X.saidCount();
1979+ m.fails := numFails;
1980+end;
1981+
1982+(* The code made since m taken back, as if it had never been made; the
1983+ frame is left as it is *)
1984+proc rewind*(m: CodeMark);
1985+begin
1986+ Chunk.rewindTo(m.pc, m.fixups, m.lines);
1987+ X.unsay(m.said);
1988+ numFails := m.fails;
1989+end;
1990+
1991+(* For a second try at the body: the code as it was at m, and the frame
1992+ as useRegs found it *)
1993+proc redo*(m: CodeMark);
1994+begin
1995+ Chunk.rewindTo(m.pc, m.fixups, m.lines);
1996+ X.unsay(m.said);
1997+ numFails := 0;
1998+ lost := false;
1999+ frameTop := frameAt[0]; frameMax := frameAt[1]; permTop := frameAt[2];
2000+ exitL := NoLabel;
2001+end;
2002+
2003+(* The prologue, which is for the procedure's first line. Only the
2004+ locals in memory are zeroed, from the parameters' slots down to
2005+ zeroTop: the parameters are stored over their slots next, the
2006+ registers of variables are zeroed in place, their save slots are
2007+ written before they are read, and so is every temporary. *)
2008+proc enterBody*(c, line: INT);
2009+var i, loop, r: INT; n: I64; p: ^Sym.Obj;
2010+begin
2011+ Chunk.beginChunk(c);
2012+ codeChunk := c;
2013+ Chunk.noteLine(line, 1); (* a declaration starts a line *)
2014+ X.push(RBP);
2015+ X.movRR(RBP, RSP);
2016+ X.say("sub rsp, frame");
2017+ (* sub rsp, imm32: always the form with a 32-bit field, so that endProc
2018+ can patch the frame's size in *)
2019+ Chunk.put1(48H); Chunk.put1(81H); Chunk.put1(0ECH);
2020+ frameFix := Chunk.pc; Chunk.put4(0);
2021+ 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);
2033+ end;
2034+ (* each register that holds a variable is saved, for the caller, and
2035+ zeroed, as a variable starts at zero *)
2036+ Chunk.setSaves(c, regMask & ((1 shl XBit) - 1), INT(saveAt));
2037+ n := 0;
2038+ for i := 0 to 4 do
2039+ if (regMask & (1 shl i)) # 0 then
2040+ X.store(X.mem(RBP, saveAt + 8 * n), VarRegs[i], 8);
2041+ X.movRI(VarRegs[i], 0);
2042+ INC(n);
2043+ end;
2044+ end;
2045+ (* and each xmm register that holds a variable, zeroed, as its slot
2046+ is: the caller keeps its own *)
2047+ for i := 0 to 3 do
2048+ if (regMask & (1 shl (XBit + i))) # 0 then
2049+ X.movRI(RAX, 0);
2050+ X.movqXR(XVarRegs[i] - XmmVar, RAX);
2051+ end;
2052+ end;
2053+ (* the parameters that came in registers, to their slots or, for a
2054+ register variable, to its register: a slice's second word, the one
2055+ for the slot 8 bytes into its own, to its length's *)
2056+ for i := 0 to numIn - 1 do
2057+ if inReg[i] < 0 then
2058+ X.movsMX(X.mem(RBP, inSlot[i]), -1 - inReg[i], false);
2059+ if inObj[i]^.reg # 0 then X.movX(inObj[i]^.reg - XmmVar, -1 - inReg[i]); end;
2060+ elsif (inObj[i] # nil) and (inObj[i]^.reg # 0) then
2061+ r := inObj[i]^.reg;
2062+ if inSlot[i] # inObj[i]^.val then r := inObj[i]^.reg2; end;
2063+ if r # inReg[i] then X.movRR(r, inReg[i]); end; (* else it is kept where it is *)
2064+ if inSize[i] < 8 then X.extend(r, inSize[i], inObj[i]^.typ^.signed); end;
2065+ else
2066+ X.store(X.mem(RBP, inSlot[i]), inReg[i], inSize[i]);
2067+ end;
2068+ end;
2069+ (* a register variable's parameter that came on the stack, above the
2070+ frame (val > 0), is loaded from there *)
2071+ p := procParams;
2072+ while p # nil do
2073+ if (p^.reg # 0) and (p^.val > 0) then
2074+ if p^.typ^.form = Sym.fReal then
2075+ X.movsXM(p^.reg - XmmVar, X.mem(RBP, p^.val), p^.typ^.size = 4);
2076+ elsif p^.typ^.form in {Sym.fInt, Sym.fBool, Sym.fEnum, Sym.fSet} then
2077+ X.load(p^.reg, X.mem(RBP, p^.val), INT(p^.typ^.size), p^.typ^.signed);
2078+ else
2079+ X.load(p^.reg, X.mem(RBP, p^.val), 8, false);
2080+ if p^.typ^.form = Sym.fSlice then X.load(p^.reg2, X.mem(RBP, p^.val + 8), 8, false); end;
2081+ end;
2082+ end;
2083+ p := p^.next;
2084+ end;
2085+end;
2086+
2087+(* Pops one of several results, a value of size bytes, into its place
2088+ off bytes into the caller's, behind the hidden pointer. *)
2089+proc resultTo*(off: I64; size: INT);
2090+var r: INT; fl: BOOL;
2091+begin
2092+ r := top();
2093+ fl := isReal(depth - 1);
2094+ drop();
2095+ X.load(RCX, X.mem(RBP, retSlot), 8, false);
2096+ if fl then X.movsMX(X.mem(RCX, off), r, size = 4);
2097+ else X.store(X.mem(RCX, off), r, size); end;
2098+end;
2099+
2100+(* Pops an address, and copies size bytes from it to the result, off
2101+ bytes into it. *)
2102+proc copyResult*(off, size: I64);
2103+begin
2104+ clobberArgs();
2105+ popTo(RSI);
2106+ X.load(RDI, X.mem(RBP, retSlot), 8, false);
2107+ if off # 0 then X.lea(RDI, X.mem(RDI, off)); end;
2108+ copyBytes(size);
2109+end;
2110+
2111+(* return: the result, a value on top, goes in rax or xmm0; two words,
2112+ the two values on top, in rax and rdx; one behind the hidden pointer
2113+ goes back with that pointer in rax. *)
2114+proc returnJump*;
2115+begin
2116+ if resType # nil then
2117+ if Sym.behindPointer(resType) then
2118+ X.load(RAX, X.mem(RBP, retSlot), 8, false);
2119+ elsif Sym.inTwoRegs(resType) then
2120+ popTo(RDX);
2121+ popTo(RAX);
2122+ elsif resType^.form = Sym.fReal then
2123+ xValueTo(depth - 1, 0);
2124+ drop();
2125+ else
2126+ popTo(RAX);
2127+ end;
2128+ end;
2129+ X.jmp(exitL);
2130+end;
2131+
2132+(* The first of what try does where the error isn't nil (the report, 7.8):
2133+ the machine's stack made even, as the deferred statements about to be
2134+ run expect to find it. try can stand among the arguments of another
2135+ call, where quadwords have been pushed. Nothing is lost: the frame is
2136+ above rsp, and the code returns through the frame pointer. *)
2137+proc tryAlign*;
2138+begin
2139+ X.aluI(X.aluAnd, RSP, -16);
2140+end;
2141+
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);
2147+var f: ^Sym.Obj;
2148+begin
2149+ if Sym.behindPointer(resType) then
2150+ X.load(RDI, X.mem(RBP, retSlot), 8, false);
2151+ X.movRI(RCX, resType^.size);
2152+ X.movRI(RAX, 0);
2153+ X.repStosb();
2154+ f := resType^.fields;
2155+ while f^.next # nil do f := f^.next; end;
2156+ X.load(RCX, X.mem(RBP, slot), 8, false);
2157+ X.load(RDX, X.mem(RBP, retSlot), 8, false);
2158+ X.store(X.mem(RDX, f^.val), RCX, 8);
2159+ X.load(RAX, X.mem(RBP, retSlot), 8, false);
2160+ elsif Sym.inTwoRegs(resType) then
2161+ X.load(RDX, X.mem(RBP, slot), 8, false);
2162+ X.movRI(RAX, 0);
2163+ else
2164+ X.load(RAX, X.mem(RBP, slot), 8, false);
2165+ end;
2166+ X.jmp(exitL);
2167+end;
2168+
2169+(* The end of the procedure in chunk c: the code that returns, and the
2170+ frame's size, known only now, patched into its prologue. If it is
2171+ open, running off its end, it returns zeros. *)
2172+proc endProc*(c: INT; open: BOOL): ERROR;
2173+var n: I64; i: INT;
2174+begin
2175+ codeChunk := -1;
2176+ if (depth # 0) or (pushed # 0) then Diag.fatal("internal error: stack depth"); end;
2177+ if open then
2178+ if Sym.behindPointer(resType) then
2179+ X.load(RDI, X.mem(RBP, retSlot), 8, false);
2180+ X.movRI(RCX, resType^.size);
2181+ X.movRI(RAX, 0);
2182+ X.repStosb();
2183+ X.load(RAX, X.mem(RBP, retSlot), 8, false);
2184+ else
2185+ X.movRI(RAX, 0);
2186+ if Sym.inTwoRegs(resType) then X.movRI(RDX, 0); end;
2187+ X.movqXR(0, RAX);
2188+ end;
2189+ else
2190+ X.dropJumpTo(exitL);
2191+ end;
2192+ X.fixLink(exitL);
2193+ n := 0;
2194+ for i := 0 to 4 do
2195+ if (regMask & (1 shl i)) # 0 then
2196+ X.load(VarRegs[i], X.mem(RBP, saveAt + 8 * n), 8, false);
2197+ INC(n);
2198+ end;
2199+ end;
2200+ X.leave();
2201+ X.ret();
2202+ endFails();
2203+ n := Sym.alignUp(frameMax, 16);
2204+ if n < 16 then n := 16; end;
2205+ if n > 2147483647 then return Scan.mark("frame too big"); end;
2206+ Chunk.put4At(frameFix, INT(n));
2207+ (* the listing's text for the sub, which starts 3 bytes (REX.W, opcode,
2208+ ModRM) before its immediate *)
2209+ if X.listing then X.restate(frameFix - 3, Diag.say("sub rsp, {}", [Fmt.int(INT(n))])); end;
2210+ Chunk.endChunk(c);
2211+ return nil;
2212+end;
2213+
2214+(* A deferred statement is compiled where it stands, as a subroutine of
2215+ its procedure that the code jumps over, in the procedure's own frame
2216+ (the same rbp), so that it sees all its variables; deferBegin gives its
2217+ address and what pushed was, and starts it, with the return address
2218+ pushed. The stack is empty where it is called, and where it begins. *)
2219+proc deferBegin*(var L: INT): (INT, INT);
2220+var saved: INT;
2221+begin
2222+ X.jmp(L);
2223+ saved := pushed;
2224+ pushed := 1;
2225+ return Chunk.pc, saved;
2226+end;
2227+
2228+proc deferEnd*(L, saved: INT);
2229+begin
2230+ keepTemps();
2231+ X.ret();
2232+ X.fixLink(L);
2233+ pushed := saved;
2234+end;
2235+
2236+proc runDefer*(at: INT);
2237+begin
2238+ X.callBack(at);
2239+end;
2240+
2241+(* The entry point, _start, and its chunk: it saves argc and argv, and
2242+ the address of the places for Rt; runs every used module's body, then
2243+ main; and ends with Rt.exit, its status main's or 0. A dynamic program
2244+ starts as C's crt1 does, through __libc_start_main(main, argc, argv,
2245+ nil, nil, rtld_fini, stack_end), with rsp aligned; its main first
2246+ gives Rt C's exit, in cExit.
2247+
2248+ dynamic: the program uses C. first: the first module, whose chain
2249+ gives the order of the bodies. mainObj: the program's main procedure, or
2250+ nil. cExit and exitProc: the chunks of Rt's cExit and exit. The
2251+ first numLinks of links: the addresses Rt is given, of what the program
2252+ has: the places, and the profiler and calls; what it isn't given,
2253+ nothing reaches, and the linker leaves out. *)
2254+proc entryPoint*(dynamic: BOOL; first: ^Sym.Module; mainObj: ^Sym.Obj; cExit, exitProc: INT; links: []Link; numLinks: INT): INT;
2255+var entry, start, i: INT; m: ^Sym.Module;
2256+begin
2257+ entry := Chunk.newChunk(Chunk.secText, -1, internStr("_start"));
2258+ if dynamic then
2259+ start := Chunk.newChunk(Chunk.secText, -1, internStr("main"));
2260+ Chunk.beginChunk(entry);
2261+ (* at the start rdx holds rtld_fini, from the dynamic loader, and the
2262+ stack argc, then argv *)
2263+ X.movRI(X.RBP, 0); (* no frame above, where a trace stops *)
2264+ X.movRR(R9, RDX); (* rtld_fini, the sixth argument *)
2265+ X.pop(RSI); (* argc, the second *)
2266+ X.movRR(RDX, RSP); (* argv, the third *)
2267+ X.aluI(X.aluAnd, RSP, -16);
2268+ X.push(RAX); (* padding, so that the next push, the seventh *)
2269+ X.push(RSP); (* argument, stack_end, leaves rsp aligned *)
2270+ X.movRI(R8, 0); (* fini and init: none *)
2271+ X.movRI(RCX, 0);
2272+ X.lea(RDI, X.memRip(start, 0)); (* main, the first argument *)
2273+ X.callM(X.memRip(Chunk.externChunk(internStr("__libc_start_main")), 0));
2274+ X.ud2(); (* it never returns *)
2275+ Chunk.endChunk(entry);
2276+ Chunk.beginChunk(start);
2277+ X.push(RBP); (* aligns the stack again *)
2278+ X.store(X.memRip(argcChunk, 0), RDI, 8);
2279+ X.store(X.memRip(argvChunk, 0), RSI, 8);
2280+ X.load(RAX, X.memRip(Chunk.externChunk(internStr("exit")), 0), 8, false);
2281+ X.store(X.memRip(cExit, 0), RAX, 8);
2282+ else
2283+ start := entry;
2284+ Chunk.beginChunk(entry);
2285+ X.load(RAX, X.mem(RSP, 0), 8, false);
2286+ X.store(X.memRip(argcChunk, 0), RAX, 8);
2287+ X.lea(RAX, X.mem(RSP, 8));
2288+ X.store(X.memRip(argvChunk, 0), RAX, 8);
2289+ end;
2290+ for i := 0 to numLinks - 1 do
2291+ X.lea(RAX, X.memRip(links[i].chunk, 0));
2292+ X.store(X.memRip(links[i].into, 0), RAX, 8);
2293+ end;
2294+ m := first;
2295+ while m # nil do
2296+ if m^.used and (m^.body >= 0) then X.callChunk(m^.body); end;
2297+ m := m^.next;
2298+ end;
2299+ if mainObj # nil then X.callChunk(mainObj^.chunk); end;
2300+ if (mainObj # nil) and (mainObj^.typ^.base # nil) then X.movRR(RDI, RAX); else X.movRI(RDI, 0); end;
2301+ X.callChunk(exitProc);
2302+ X.ud2(); (* exit never returns: trap if it does *)
2303+ Chunk.endChunk(start);
2304+ (* Rt.fail, for the failures of each kind: the place is where the
2305+ check's call is. The return address is the next instruction's, which
2306+ may belong to another line; one byte back is inside the call, so the
2307+ lookup finds the call's line. rsp is aligned for the call, as the
2308+ check's code may have pushed an odd number of quadwords. rdi and rsi
2309+ as the failing code had them go on the stack, as Rt.fail's last two
2310+ arguments, and a comes in rax (endFails). *)
2311+ for i := 0 to LEN(failStubs) - 1 do
2312+ if failStubs[i] >= 0 then
2313+ Chunk.beginChunk(failStubs[i]);
2314+ X.load(R8, X.mem(RSP, 0), 8, false);
2315+ X.aluI(X.aluSub, R8, 1);
2316+ X.aluI(X.aluAnd, RSP, -16);
2317+ X.push(RSI);
2318+ X.push(RDI);
2319+ X.movRR(RSI, RAX);
2320+ X.movRI(RDI, i);
2321+ X.callChunk(rtFail);
2322+ X.ud2();
2323+ Chunk.endChunk(failStubs[i]);
2324+ end;
2325+ end;
2326+ return entry;
2327+end;
2328+
2329+(* A code procedure: its instructions, read by the assembler (X64),
2330+ are the whole of chunk c *)
2331+proc codeProc*(c: INT; constExpr: X.ConstFn): ERROR;
2332+begin
2333+ Chunk.beginChunk(c);
2334+ try X.assemble(constExpr);
2335+ Chunk.endChunk(c);
2336+ return nil;
2337+end;
2338+
2339+var i: INT;
2340+begin
2341+ for i := 0 to LEN(failStubs) - 1 do failStubs[i] := -1; end;
2342+ inPlace := -1;
2343+ codeChunk := -1;
2344+ resetStack(0, 0);
2345+ rtFail := Chunk.newChunk(Chunk.secText, internStr("Rt"), internStr("fail"));
2346+ argcChunk := Chunk.newChunk(Chunk.secBss, -1, internStr("argc"));
2347+ Chunk.setBss(argcChunk, 8, 8);
2348+ argvChunk := Chunk.newChunk(Chunk.secBss, -1, internStr("argv"));
2349+ Chunk.setBss(argvChunk, 8, 8);
2350+end Gen.

src/Item.raz (history) added +1729 -0

@@ -0,0 +1,1729 @@
1+(* Item: operands, their types, and what they mean.
2+
3+ The parser describes each operand as an item, as in Wirth's
4+ compilers: a constant, a variable at an address it can name, a value
5+ on Gen's stack, a procedure, a string. The routines here check the
6+ items' types, fold constants, and have Gen make the code, as calls of
7+ its stack machine; nothing here knows the machine.
8+
9+ Depends on: Scan for errors, Sym for types, Chunk for data, Gen for
10+ code.
11+ Leaves out: the language's syntax, which is Parse; the machine, which
12+ is Gen.
13+
14+ An error the seed's `Mark` ended in a jump back to the parser's
15+ recovery point. Here the routine that finds it shows it and returns
16+ `Scan.Failed`, and every routine that calls one passes it up with
17+ `try`, to where the parser reads on: what has been made by then is
18+ what the seed had made when it jumped. So most routines here return an
19+ ERROR, as the last of their results.
20+
21+ The seed's `Mismatch` of two operands is `mismatchOps` (raz has no
22+ overloading), and what the parser sets, `demoted` and `checks`, has a
23+ setter each, as an exported variable is read-only outside its module.
24+ The seed's `TItem` is `Item` and `TMode` is `Mode`; its procedures begin
25+ in lower case. *)
26+module Item;
27+import Fmt, Diag, Scan, Sym, Chunk, Gen;
28+
29+type
30+ Mode* = (mConst, mVar, mStack, mProc, mType, mStr, mBuiltin, mCase, mNone, mCond,
31+ mWords); (* two results of a call, on the stack, the first under the second *)
32+
33+ Item* = record
34+ mode*: Mode;
35+ typ*: ^Sym.Type;
36+ rel*: Scan.Sym; (* mCond: the comparison of the two integers on
37+ the stack, not yet made, as Wirth's compilers
38+ keep a condition *)
39+ relSigned*: BOOL;
40+ fj*, tj*: INT; (* mCond: the chains of jumps already made that are
41+ taken when the whole condition is false, and when
42+ it is true, not yet given a place (and, or and
43+ not make them); see Gen's jumpOut *)
44+ val*: I64; (* mConst: the value, an F64's bits; mStr: its length *)
45+ base*: Gen.Base; (* mVar: what the address is relative to *)
46+ chunk*: INT; (* mVar with bGlobal, mStr: the chunk; bSlot: the slot *)
47+ off*: I64; (* mVar: added to the base *)
48+ vol*: BOOL; (* mVar: reached through ^VOLATILE *)
49+ isVar*: BOOL; (* mVar: a variable of the program, not a temporary *)
50+ odd*: BOOL; (* mVar: in a packed record, so maybe misaligned *)
51+ ro*: BOOL; (* mVar: another module's exported variable, or part
52+ of one, which only that module changes *)
53+ deref*: BOOL; (* mVar: at an address from a pointer, which may be
54+ nil and isn't tested yet (nilTest) *)
55+ obj*: ^Sym.Obj; (* mProc, mBuiltin, mCase; mVar: the variable named *)
56+ pos*: Diag.Pos; (* where it is in the source, for messages *)
57+ end;
58+
59+const
60+ (* the comparison that holds when the one at the same place doesn't, for integers *)
61+ NegatedOps: [6]Scan.Sym = [Scan.sNeq, Scan.sEql, Scan.sGeq, Scan.sGtr, Scan.sLeq, Scan.sLss];
62+
63+const
64+ MaxI64 = 9223372036854775807;
65+ MinI64 = -9223372036854775807 - 1;
66+
67+var
68+ demoted*: BOOL; (* address wanted a register variable's address: its
69+ procedure is compiled again, the variable in memory *)
70+ checks*: BOOL; (* the module's index and slice checks are made: it
71+ doesn't say check off *)
72+ result: ^Sym.Type; (* the result of the procedure being compiled, or nil *)
73+ passing: ^Sym.Obj; (* the parameter the argument at passingAt goes to *)
74+ passingAt: Diag.Pos;
75+
76+proc setDemoted*(yes: BOOL);
77+begin
78+ demoted := yes;
79+end;
80+
81+proc setChecks*(yes: BOOL);
82+begin
83+ checks := yes;
84+end;
85+
86+(* The comparison that holds when op doesn't *)
87+proc negated(op: Scan.Sym): Scan.Sym;
88+begin
89+ return NegatedOps[INT(op) - INT(Scan.sEql)];
90+end;
91+
92+proc isRel(op: Scan.Sym): BOOL;
93+begin
94+ return (op >= Scan.sEql) and (op <= Scan.sGeq);
95+end;
96+
97+(* Whether op is one of the list: Scan.Sym has too many names for a set *)
98+proc oneOf(op: Scan.Sym; list: []Scan.Sym): BOOL;
99+var i: INT;
100+begin
101+ for i := 0 to LEN(list) - 1 do
102+ if list[i] = op then return true; end;
103+ end;
104+ return false;
105+end;
106+
107+proc bit(f: BOOL): I64;
108+begin
109+ if f then return 1; end;
110+ return 0;
111+end;
112+
113+(* A message, from a format and the strings that fill it *)
114+proc say1(f, a: []U8): []U8;
115+begin
116+ return Diag.say(f, [Fmt.str(a)]);
117+end;
118+
119+proc say2(f, a, b: []U8): []U8;
120+begin
121+ return Diag.say(f, [Fmt.str(a), Fmt.str(b)]);
122+end;
123+
124+(* Items *)
125+
126+proc makeConst*(var x: Item; t: ^Sym.Type; v: I64);
127+var p: Diag.Pos;
128+begin
129+ p := x.pos;
130+ x := {};
131+ x.pos := p;
132+ x.mode := mConst;
133+ x.typ := t;
134+ x.val := v;
135+end;
136+
137+(* A real constant: untyped, unless typed later. Its value is an F64,
138+ which for an F32 is one an F32 can hold. *)
139+proc makeReal*(var x: Item; r: F64);
140+var p: ^F64;
141+begin
142+ makeConst(x, Sym.tRConst, 0);
143+ p := ^F64(ADR(x.val));
144+ p^ := r;
145+end;
146+
147+proc isF32(t: ^Sym.Type): BOOL;
148+begin
149+ return (t^.form = Sym.fReal) and (t^.size = 4);
150+end;
151+
152+proc realOf*(x: Item): F64;
153+var v: I64; p: ^F64;
154+begin
155+ v := x.val;
156+ p := ^F64(ADR(v));
157+ return p^;
158+end;
159+
160+(* Gives a real constant the real type t, rounded to it. *)
161+proc realTo(var x: Item; t: ^Sym.Type);
162+var r: F64;
163+begin
164+ r := realOf(x);
165+ if isF32(t) then makeReal(x, F64(F32(r))); else makeReal(x, r); end;
166+ x.typ := t;
167+end;
168+
169+(* The current string literal, as an item of its own chunk. *)
170+proc makeStr*(var x: Item);
171+begin
172+ x := {};
173+ x.mode := mStr;
174+ x.typ := Sym.tStr;
175+ x.val := Scan.slen;
176+ x.chunk := Chunk.newChunk(Chunk.secRodata, -1, -1);
177+ Chunk.setData(x.chunk, Scan.strWithZero(), Scan.slen + 1, 1);
178+end;
179+
180+proc frameAdr*(off: I64): Gen.Adr;
181+var a: Gen.Adr;
182+begin
183+ a.base := Gen.bFrame;
184+ a.chunk := -1;
185+ a.off := off;
186+ a.hi := 0;
187+ return a;
188+end;
189+
190+proc globalAdr*(c: INT): Gen.Adr;
191+var a: Gen.Adr;
192+begin
193+ a.base := Gen.bGlobal;
194+ a.chunk := c;
195+ a.off := 0;
196+ a.hi := 0;
197+ return a;
198+end;
199+
200+(* Where the variable x is, for Gen; a slice in registers has two *)
201+proc adrOf*(x: Item): Gen.Adr;
202+var a: Gen.Adr;
203+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;
210+end;
211+
212+(* An item for "found ...": a constant without a type of its own as it
213+ is written, so that "found 1.5" says what is wrong; else its type. *)
214+proc what*(x: Item): []U8;
215+begin
216+ if (x.mode = mConst) and ((x.typ = Sym.tConst) or (x.typ = Sym.tRConst)) then
217+ return Diag.source(x.pos);
218+ end;
219+ return Sym.typeName(x.typ);
220+end;
221+
222+(* Two operands of different types. Numbers convert, so say how. *)
223+proc mismatchOps(x, y: Item; xt, yt: ^Sym.Type): ERROR;
224+var text: []U8;
225+begin
226+ text := say2("{} and {} are different types", Sym.typeName(xt), Sym.typeName(yt));
227+ if (Sym.isInt(xt) or (xt^.form = Sym.fReal)) and (Sym.isInt(yt) or (yt^.form = Sym.fReal))
228+ and (xt # Sym.tConst) and (xt # Sym.tRConst) then
229+ return Scan.markHelp(Diag.join(x.pos, y.pos), text,
230+ say2("convert one to the other's type, as in {}({})", Sym.typeName(xt), Diag.source(y.pos)));
231+ end;
232+ return Scan.markAt(Diag.join(x.pos, y.pos), text);
233+end;
234+
235+(* An item that is not a value, by what it is. *)
236+proc notValue(x: Item): ERROR;
237+begin
238+ match x.mode of
239+ | mType: return Scan.markAt(x.pos, say1("{} is a type, not a value", Sym.typeName(x.typ)));
240+ | mBuiltin: return Scan.markAt(x.pos, say1("{} is a built-in procedure, not a value", Scan.nameOf(x.obj^.name)));
241+ | mCase: return Scan.markAt(x.pos, say1("{} is a case, not a value", Scan.nameOf(x.obj^.name)));
242+ | mNone:
243+ if x.obj # nil then return Scan.markAt(x.pos, say1("{} returns nothing", Scan.nameOf(x.obj^.name))); end;
244+ return Scan.markAt(x.pos, "the procedure returns nothing");
245+ | else: return Scan.markAt(x.pos, "a string can't be an operand");
246+ end;
247+end;
248+
249+proc makeItem*(var x: Item; o: ^Sym.Obj): ERROR;
250+begin
251+ x := {};
252+ x.typ := o^.typ;
253+ x.obj := o;
254+ match o^.cls of
255+ | oConst:
256+ if o^.typ = Sym.tStr then
257+ x.mode := mStr; x.val := o^.val; x.chunk := o^.chunk;
258+ elsif o^.typ^.form in {Sym.fArray, Sym.fRecord} then
259+ (* an array or record constant: a variable in read-only data, not one of
260+ the program's, so nothing can change it *)
261+ x.mode := mVar; x.base := Gen.bGlobal; x.chunk := o^.chunk;
262+ else
263+ x.mode := mConst; x.val := o^.val;
264+ end;
265+ | oVar:
266+ x.mode := mVar;
267+ x.ro := (o^.lev = 0) and (o^.home # Sym.curModule);
268+ x.isVar := not x.ro;
269+ if o^.ext then
270+ Gen.pushVar(globalAdr(o^.chunk), 8, false, Gen.kWord);
271+ x.base := Gen.bStack;
272+ elsif o^.lev = 0 then
273+ x.base := Gen.bGlobal; x.chunk := o^.chunk;
274+ elsif o^.ind then
275+ x.base := Gen.bSlot; x.chunk := INT(o^.val); x.off := o^.off;
276+ elsif o^.reg # 0 then
277+ x.base := Gen.bReg; x.chunk := o^.reg;
278+ else
279+ x.base := Gen.bFrame; x.off := o^.val;
280+ end;
281+ | oProc: x.mode := mProc;
282+ | oType: x.mode := mType;
283+ | oBuiltin: x.mode := mBuiltin;
284+ | oCase: x.mode := mCase;
285+ | else: return Scan.mark(say1("{} is not a value", Scan.nameOf(o^.name)));
286+ end;
287+ return nil;
288+end;
289+
290+proc scalarSize*(t: ^Sym.Type): INT;
291+begin
292+ if t^.form in {Sym.fInt, Sym.fBool, Sym.fEnum, Sym.fSet, Sym.fReal} then return INT(t^.size); end;
293+ return 8;
294+end;
295+
296+(* The width an operation on t is brought back to, and whether signed *)
297+proc intSize(t: ^Sym.Type): INT;
298+begin
299+ if t^.form = Sym.fInt then return INT(t^.size); end;
300+ return 8;
301+end;
302+
303+proc signed(t: ^Sym.Type): BOOL;
304+begin
305+ return ((t^.form = Sym.fInt) and t^.signed) or (t^.form = Sym.fConst);
306+end;
307+
308+proc cut(v: I64; t: ^Sym.Type): I64;
309+begin
310+ if t^.form # Sym.fInt then return v; end;
311+ match t^.size of
312+ | 1: if t^.signed then return I64(I8(v)); end; return I64(U8(v));
313+ | 2: if t^.signed then return I64(I16(v)); end; return I64(U16(v));
314+ | 4: if t^.signed then return I64(I32(v)); end; return I64(U32(v));
315+ | else: return v;
316+ end;
317+end;
318+
319+(* Code computing with a real is noted on its chunk, at the first place,
320+ for a target without reals (report 5.1) to refuse if the chunk turns
321+ out to be used. A real moved whole, as a record's bytes are copied,
322+ needs nothing the target lacks, and isn't noted. *)
323+proc usesReals*(p: Diag.Pos);
324+begin
325+ if (Gen.codeChunk >= 0) and not Chunk.chunks[Gen.codeChunk].reals then
326+ Chunk.setReals(Gen.codeChunk, p);
327+ end;
328+end;
329+
330+(* x, at an address from a pointer, is about to be used: Gen tests the
331+ address for nil where the machine wouldn't stop at it (report section
332+ 10), from its offset to its end. *)
333+proc nilTest*(var x: Item);
334+begin
335+ if (x.mode = mVar) and x.deref then Gen.checkNil(x.off + x.typ^.size, x.pos); end;
336+ x.deref := false;
337+end;
338+
339+(* x's value, on top of the stack *)
340+proc value*(var x: Item): ERROR;
341+var f: F32; p: ^U32;
342+begin
343+ if x.mode = mCond then
344+ if (x.fj = Gen.NoLabel) and (x.tj = Gen.NoLabel) then Gen.compare(x.rel, Gen.kWord, x.relSigned);
345+ else Gen.condValue(negated(x.rel), x.relSigned, x.fj, x.tj); end;
346+ x.mode := mStack;
347+ return nil;
348+ end;
349+ if x.typ^.form = Sym.fReal then usesReals(x.pos); end;
350+ nilTest(x);
351+ match x.mode of
352+ | mConst:
353+ if (x.typ^.form = Sym.fError) and (x.val > 0) then Gen.pushAdr(globalAdr(INT(x.val) - 1));
354+ elsif isF32(x.typ) then
355+ f := F32(realOf(x));
356+ p := ^U32(ADR(f));
357+ Gen.pushConst(Gen.kF32, I64(p^));
358+ else Gen.pushConst(Gen.kindOf(x.typ), x.val); end;
359+ | mVar:
360+ if not Sym.isScalar(x.typ) then
361+ return Scan.markAt(x.pos, say1("expected a single value, found {}", what(x)));
362+ end;
363+ Gen.pushVar(adrOf(x), scalarSize(x.typ), (x.typ^.form = Sym.fInt) and x.typ^.signed, Gen.kindOf(x.typ));
364+ | mStack: x.mode := mStack;
365+ | mProc:
366+ if x.obj^.isCode and (x.obj^.typ^.base # nil) and x.obj^.typ^.base^.tuple then
367+ return Scan.markAt(x.pos, "a code procedure with two results can only be called");
368+ end;
369+ Gen.pushProc(x.obj^.chunk, x.obj^.ext);
370+ | else: return notValue(x);
371+ end;
372+ x.mode := mStack;
373+ return nil;
374+end;
375+
376+(* The address of the variable or string x, on top of the stack *)
377+proc address*(var x: Item): ERROR;
378+begin
379+ nilTest(x);
380+ if (x.mode = mVar) and (x.base = Gen.bReg) then
381+ (* its address is wanted after all: the procedure is compiled again
382+ with the variable in memory; till then, this code is thrown away *)
383+ x.obj^.reg := 0;
384+ x.obj^.reg2 := 0;
385+ demoted := true;
386+ x.base := Gen.bFrame;
387+ x.off := x.obj^.val;
388+ end;
389+ if x.mode = mStr then Gen.pushAdr(globalAdr(x.chunk));
390+ elsif x.mode = mVar then
391+ Gen.pushAdr(adrOf(x));
392+ x.base := Gen.bStack; x.off := 0;
393+ else return Scan.markAt(x.pos, "expected a variable"); end;
394+ return nil;
395+end;
396+
397+(* x isn't wanted: what it has on the stack is dropped *)
398+proc discard*(x: Item): ERROR;
399+var y: Item;
400+begin
401+ if x.mode = mCond then
402+ y := x;
403+ try value(y);
404+ Gen.drop();
405+ return nil;
406+ end;
407+ if (x.mode = mStack) or ((x.mode = mVar) and (x.base = Gen.bStack)) then Gen.drop(); end;
408+ if x.mode = mWords then Gen.drop(); Gen.drop(); end;
409+ return nil;
410+end;
411+
412+(* Frames *)
413+
414+proc tempItem*(var x: Item; t: ^Sym.Type; off: I64);
415+var p: Diag.Pos;
416+begin
417+ p := x.pos;
418+ x := {};
419+ x.pos := p;
420+ x.mode := mVar; x.typ := t; x.base := Gen.bFrame; x.off := off;
421+end;
422+
423+proc toSlot*(var x: Item): (I64, ERROR);
424+var s: I64;
425+begin
426+ try value(x);
427+ s := Gen.allocTemp(8, 8);
428+ Gen.popVar(frameAdr(s), 8);
429+ return s, nil;
430+end;
431+
432+(* Copying *)
433+
434+(* x, copied to a temporary *)
435+proc copyToTemp*(var x: Item): ERROR;
436+var t: I64; f, g: ^Sym.Obj; a: Gen.Adr;
437+begin
438+ if x.vol then return Scan.markAt(x.pos, "can't copy through a volatile pointer"); end;
439+ t := Gen.allocTemp(x.typ^.size, x.typ^.align);
440+ if (x.mode = mVar) and (x.base = Gen.bReg) then
441+ (* a slice in registers, which has no address: its words stored *)
442+ a := adrOf(x);
443+ Gen.pushVar(a, 8, false, Gen.kWord);
444+ Gen.popVar(frameAdr(t), 8);
445+ a.off := 8;
446+ Gen.pushVar(a, 8, false, Gen.kWord);
447+ Gen.popVar(frameAdr(t + 8), 8);
448+ tempItem(x, x.typ, t);
449+ return nil;
450+ end;
451+ if x.mode = mWords then
452+ (* the second result is on top, so it is popped first *)
453+ f := x.typ^.fields; g := f^.next;
454+ Gen.popVar(frameAdr(t + g^.val), scalarSize(g^.typ));
455+ Gen.popVar(frameAdr(t + f^.val), scalarSize(f^.typ));
456+ tempItem(x, x.typ, t);
457+ return nil;
458+ end;
459+ try address(x);
460+ Gen.copyTo(frameAdr(t), x.typ^.size);
461+ tempItem(x, x.typ, t);
462+ return nil;
463+end;
464+
465+(* A slice made from an address on the stack and a length. *)
466+proc sliceOf*(var x: Item; t: ^Sym.Type; len: I64);
467+var s: I64;
468+begin
469+ s := Gen.allocTemp(16, 8);
470+ Gen.popVar(frameAdr(s), 8);
471+ Gen.pushConst(Gen.kWord, len);
472+ Gen.popVar(frameAdr(s + 8), 8);
473+ tempItem(x, t, s);
474+end;
475+
476+(* An INT goes silently into an I64, and a UINT into a U64, losing
477+ nothing on any target (report section 5.10). *)
478+proc widens(s, t: ^Sym.Type): BOOL;
479+begin
480+ return ((s = Sym.tInt) and Sym.same(t, Sym.tI64)) or ((s = Sym.tUInt) and Sym.same(t, Sym.tU64));
481+end;
482+
483+(* Another module's exported variable can be read, not changed, nor
484+ handed to anything that could change it (report section 3). *)
485+proc notReadOnly*(x: Item): ERROR;
486+begin
487+ if x.ro then
488+ return Scan.markAt(x.pos, Diag.say("{} is {}'s, and can't be changed outside it",
489+ [Fmt.str(Diag.source(x.pos)), Fmt.str(Scan.nameOf(x.obj^.home^.name))]));
490+ end;
491+ return nil;
492+end;
493+
494+(* An error in x's type; if x is an argument, a note at the parameter
495+ it goes to. *)
496+proc mismatch(x: Item; text: []U8): ERROR;
497+begin
498+ Diag.error(x.pos, text);
499+ if (passing # nil) and (x.pos.f = passingAt.f) and (x.pos.a = passingAt.a) and (x.pos.b = passingAt.b) then
500+ Diag.note(passing^.pos, say1("it goes to {}, declared here", Scan.nameOf(passing^.name)));
501+ end;
502+ return Scan.Failed;
503+end;
504+
505+proc coerce*(var x: Item; t: ^Sym.Type): ERROR;
506+var s: ^Sym.Type; tmp: I64;
507+begin
508+ if x.mode = mCond then try value(x); end;
509+ s := x.typ;
510+ if x.mode = mStr then
511+ if (t^.form = Sym.fSlice) and (t^.base = Sym.tU8) then
512+ try address(x); sliceOf(x, t, x.val);
513+ elsif (t^.form = Sym.fPtr) and (t^.base = Sym.tU8) then
514+ try address(x); x.mode := mStack; x.typ := t;
515+ elsif (t^.form = Sym.fArray) and (t^.base = Sym.tU8) and (t^.len >= x.val) then
516+ tmp := Gen.allocTemp(t^.size, 1);
517+ try address(x);
518+ Gen.copyTo(frameAdr(tmp), x.val);
519+ if t^.len > x.val then Gen.zeroVar(frameAdr(tmp + x.val), t^.len - x.val); end;
520+ tempItem(x, t, tmp);
521+ else return mismatch(x, say1("can't use a string as {}", Sym.typeName(t))); end;
522+ return nil;
523+ end;
524+ if x.mode in {mType, mBuiltin, mNone, mCase} then return notValue(x); end;
525+ if Sym.same(s, t) then return nil; end;
526+ if widens(s, t) then x.typ := t; (* the same bits, on a 64-bit target *)
527+ elsif (s = Sym.tRConst) and (t^.form = Sym.fReal) then realTo(x, t);
528+ elsif (s^.form = Sym.fConst) and (t^.form = Sym.fInt) then
529+ if (x.mode = mConst) and not Sym.fits(x.val, t) then
530+ return Scan.markAt(x.pos, Diag.say("{} doesn't fit {}", [Fmt.int(x.val), Fmt.str(Sym.typeName(t))]));
531+ end;
532+ x.typ := t;
533+ elsif (s^.form = Sym.fNil) and (t^.form in {Sym.fPtr, Sym.fProc, Sym.fError}) then
534+ x.typ := t;
535+ elsif (s^.form = Sym.fPtr) and (t^.form = Sym.fPtr) and t^.vol and not s^.vol
536+ and Sym.same(s^.base, t^.base) then
537+ x.typ := t;
538+ elsif (s^.form = Sym.fArray) and (t^.form = Sym.fSlice) and Sym.same(s^.base, t^.base) then
539+ try notReadOnly(x);
540+ if x.vol then return Scan.markAt(x.pos, "can't make a slice through a volatile pointer"); end;
541+ if x.odd then return Scan.markAt(x.pos, "can't make a slice of a field of a packed record"); end;
542+ try address(x);
543+ sliceOf(x, t, s^.len);
544+ elsif (x.mode = mProc) and (t^.form # Sym.fProc) and (s^.base = nil) then
545+ return Scan.markAt(x.pos, say1("{} is a procedure, and returns nothing", Diag.source(x.pos)));
546+ elsif (x.mode = mProc) and (t^.form # Sym.fProc) then
547+ return Scan.markHelp(x.pos,
548+ say2("can't use {} as {}", Sym.typeName(s), Sym.typeName(t)),
549+ say1("to call it, write {}()", Diag.source(x.pos)));
550+ else
551+ return mismatch(x, say2("can't use {} as {}", Sym.typeName(s), Sym.typeName(t)));
552+ end;
553+ return nil;
554+end;
555+
556+(* coerce where the types must be the same, as in a for loop, INC and
557+ several results, which don't widen an INT to an I64 (report sections
558+ 5.10, 6.1 and 7.2); help, if not empty, says why. *)
559+proc coerceExact*(var x: Item; t: ^Sym.Type; help: []U8): ERROR;
560+var h: []U8;
561+begin
562+ if widens(x.typ, t) then
563+ h := help;
564+ if LEN(h) = 0 then
565+ h := say2("they don't mix here: write {}({})", Sym.typeName(t), Diag.source(x.pos));
566+ end;
567+ return Scan.markHelp(x.pos, say2("expected {}, found {}", Sym.typeName(t), what(x)), h);
568+ end;
569+ return coerce(x, t);
570+end;
571+
572+(* dst := src. The address of dst, if it has to be computed, is on the
573+ stack already, under src's. *)
574+proc assign*(var dst, src: Item): ERROR;
575+begin
576+ try coerce(src, dst.typ);
577+ if Sym.isScalar(dst.typ) then
578+ try value(src);
579+ Gen.popVar(adrOf(dst), scalarSize(dst.typ));
580+ else
581+ if dst.vol or src.vol then return Scan.markAt(src.pos, "can't copy through a volatile pointer"); end;
582+ if (src.mode = mVar) and (src.base = Gen.bReg) then try copyToTemp(src); end; (* a slice in registers *)
583+ try address(src);
584+ if dst.base = Gen.bStack then Gen.copyBlock(dst.typ^.size, dst.off);
585+ else Gen.copyTo(adrOf(dst), dst.typ^.size); end;
586+ end;
587+ return nil;
588+end;
589+
590+(* t's name, ending in a zero byte, for Rt.fail *)
591+proc nameChunk(t: ^Sym.Type): INT;
592+var s: []U8; p: ^U8; n, c: INT;
593+begin
594+ s := Sym.typeName(t);
595+ n := LEN(s);
596+ p := Scan.grab(n + 1);
597+ COPY(p[0..n], s);
598+ p[n] := 0;
599+ c := Chunk.newChunk(Chunk.secRodata, -1, -1);
600+ Chunk.setData(c, p, n + 1, 1);
601+ return c;
602+end;
603+
604+(* Selectors *)
605+
606+proc deref*(var x: Item): ERROR;
607+var t: ^Sym.Type;
608+begin
609+ t := x.typ;
610+ if t^.form # Sym.fPtr then
611+ return Scan.markAt(x.pos, say1("expected a pointer, found {}", Sym.typeName(t)));
612+ end;
613+ if t^.base = nil then
614+ return Scan.markAt(x.pos, say1("{} points to a type never declared", Sym.typeName(t)));
615+ end;
616+ try value(x);
617+ x.mode := mVar; x.base := Gen.bStack; x.off := 0; x.deref := true;
618+ x.typ := t^.base; x.vol := t^.vol; x.isVar := true; x.odd := false; x.ro := false;
619+ return nil;
620+end;
621+
622+(* A field of a packed record, of more than one byte's alignment, may
623+ sit anywhere; it is read and written, but has no address and no
624+ volatile access, which a machine that can't reach a misaligned word
625+ couldn't make one access (report section 5.5). *)
626+proc field*(var x: Item; f: ^Sym.Obj): ERROR;
627+begin
628+ if x.typ^.packd and (f^.typ^.align > 1) then
629+ if x.vol then return Scan.markAt(x.pos, "a field of a packed record can't be volatile"); end;
630+ x.odd := true;
631+ end;
632+ x.off := x.off + f^.val;
633+ x.typ := f^.typ;
634+ return nil;
635+end;
636+
637+proc indexPrep*(var x: Item): ERROR;
638+begin
639+ nilTest(x);
640+ if x.mode = mStr then try coerce(x, Sym.tBytes); end;
641+ if (x.typ^.form = Sym.fPtr) and (x.typ^.base^.form = Sym.fArray) then
642+ return Scan.markAt(x.pos, "a pointer to an array is indexed as p^[i]");
643+ end;
644+ if x.typ^.form = Sym.fPtr then try value(x);
645+ elsif not ((x.mode = mVar) and (x.typ^.form in {Sym.fArray, Sym.fSlice})) then
646+ return Scan.markAt(x.pos, say1("expected an array, a slice or a pointer, found {}", what(x)));
647+ end;
648+ return nil;
649+end;
650+
651+(* The index on top, times the size of an element *)
652+proc scaleBy(s: I64);
653+begin
654+ if s # 1 then
655+ Gen.pushConst(Gen.kWord, s);
656+ Gen.op(Scan.sTimes, Gen.kWord, 8, true);
657+ end;
658+end;
659+
660+proc index*(var x, y: Item): ERROR;
661+var t: ^Sym.Type; s: I64;
662+begin
663+ t := x.typ;
664+ s := t^.base^.size;
665+ if not Sym.isInt(y.typ) then
666+ return Scan.markAt(y.pos, say1("an index is an integer, found {}", what(y)));
667+ end;
668+ if t^.form = Sym.fPtr then
669+ try value(y);
670+ scaleBy(s);
671+ Gen.op(Scan.sPlus, Gen.kWord, 8, false);
672+ x.mode := mVar; x.base := Gen.bStack; x.off := 0;
673+ x.vol := t^.vol; x.isVar := true; x.odd := false; x.ro := false;
674+ elsif (t^.form = Sym.fArray) and (y.mode = mConst) then
675+ if (y.val < 0) or (y.val >= t^.len) then
676+ return Scan.markAt(y.pos, Diag.say("index {} is out of range for a length of {}", [Fmt.int(y.val), Fmt.int(t^.len)]));
677+ end;
678+ x.off := x.off + y.val * s;
679+ elsif t^.form = Sym.fArray then
680+ try value(y);
681+ if checks then Gen.checkIndex(t^.len, y.pos); end;
682+ if x.base = Gen.bStack then scaleBy(s); Gen.op(Scan.sPlus, Gen.kWord, 8, false);
683+ else Gen.indexArray(adrOf(x), s); x.off := 0; end;
684+ x.base := Gen.bStack;
685+ else
686+ try value(y);
687+ Gen.indexSlice(adrOf(x), s, checks, y.pos);
688+ x.base := Gen.bStack; x.off := 0; x.isVar := true; x.vol := false; x.ro := false;
689+ end;
690+ x.typ := t^.base;
691+ return nil;
692+end;
693+
694+proc sliceLo*(var lo: Item): ERROR;
695+begin
696+ if not Sym.isInt(lo.typ) then
697+ return Scan.markAt(lo.pos, say1("an index is an integer, found {}", what(lo)));
698+ end;
699+ return value(lo);
700+end;
701+
702+proc slice*(var x, lo, hi: Item): ERROR;
703+var t, st: ^Sym.Type; tmp: I64;
704+begin
705+ t := x.typ;
706+ if not Sym.isInt(hi.typ) then
707+ return Scan.markAt(hi.pos, say1("an index is an integer, found {}", what(hi)));
708+ end;
709+ if x.vol then return Scan.markAt(x.pos, "can't make a slice through a volatile pointer"); end;
710+ if x.odd then return Scan.markAt(x.pos, "can't make a slice of a field of a packed record"); end;
711+ if t^.form = Sym.fArray then try notReadOnly(x); end;
712+ try value(hi);
713+ tmp := Gen.allocTemp(16, 8);
714+ if t^.form = Sym.fPtr then Gen.slicePtr(t^.base^.size, tmp, checks, lo.pos);
715+ else Gen.slice(adrOf(x), t^.form = Sym.fArray, t^.len, t^.base^.size, tmp, checks, lo.pos); end;
716+ st := Sym.newType(Sym.fSlice, 16, 8);
717+ st^.base := t^.base;
718+ tempItem(x, st, tmp);
719+ return nil;
720+end;
721+
722+(* Operators *)
723+
724+proc neg*(var x: Item): ERROR;
725+begin
726+ if x.typ^.form = Sym.fReal then
727+ if x.mode = mConst then x.val := x.val xor MinI64;
728+ else try value(x); Gen.neg(Gen.kindOf(x.typ), 8, false); end;
729+ elsif Sym.isInt(x.typ) then
730+ if (x.mode = mConst) and (x.typ^.form = Sym.fConst) and (x.val = MinI64) then
731+ return Scan.markAt(x.pos, "the constant is too big for I64");
732+ elsif x.mode = mConst then x.val := cut(-x.val, x.typ);
733+ else try value(x); Gen.neg(Gen.kWord, intSize(x.typ), signed(x.typ)); end;
734+ else return Scan.markAt(x.pos, say1("can't negate {}", Sym.typeName(x.typ))); end;
735+ return nil;
736+end;
737+
738+proc notOp*(var x: Item): ERROR;
739+var L: INT;
740+begin
741+ if Sym.isInt(x.typ) then
742+ return Scan.markHelp(x.pos, say1("\"not\" needs a BOOL, found {}", what(x)), "the bits of an integer flip with ~");
743+ end;
744+ if x.typ^.form # Sym.fBool then
745+ return Scan.markAt(x.pos, say1("\"not\" needs a BOOL, found {}", what(x)));
746+ end;
747+ if x.mode = mConst then x.val := 1 - x.val;
748+ elsif x.mode = mCond then
749+ x.rel := negated(x.rel);
750+ L := x.fj; x.fj := x.tj; x.tj := L;
751+ else try value(x); Gen.notBool(); end;
752+ return nil;
753+end;
754+
755+proc complement*(var x: Item): ERROR;
756+begin
757+ if x.typ^.form = Sym.fBool then
758+ return Scan.markHelp(x.pos, say1("\"~\" needs an integer, found {}", what(x)), "a BOOL is negated with not");
759+ end;
760+ if not Sym.isInt(x.typ) then
761+ return Scan.markAt(x.pos, say1("\"~\" needs an integer, found {}", what(x)));
762+ end;
763+ if x.mode = mConst then x.val := cut(~x.val, x.typ);
764+ else try value(x); Gen.complement(intSize(x.typ), signed(x.typ)); end;
765+ return nil;
766+end;
767+
768+(* Arrays, slices and strings, which = and # compare element by element *)
769+proc isSeq(t: ^Sym.Type): BOOL;
770+begin
771+ return t^.form in {Sym.fStr, Sym.fArray, Sym.fSlice};
772+end;
773+
774+proc elemOf(t: ^Sym.Type): ^Sym.Type;
775+begin
776+ if t^.form = Sym.fStr then return Sym.tU8; end;
777+ return t^.base;
778+end;
779+
780+(* An array, slice or string as a slice in a temporary, for comparing. *)
781+proc seqSlice(var x: Item): ERROR;
782+var t: ^Sym.Type;
783+begin
784+ t := Sym.newType(Sym.fSlice, 16, 8);
785+ t^.base := elemOf(x.typ);
786+ if x.typ^.form = Sym.fSlice then
787+ x.typ := t; try copyToTemp(x);
788+ elsif x.mode = mStr then
789+ try address(x); sliceOf(x, t, x.val);
790+ else
791+ if x.vol then return Scan.markAt(x.pos, "can't compare through a volatile pointer"); end;
792+ try address(x); sliceOf(x, t, x.typ^.len);
793+ end;
794+ return nil;
795+end;
796+
797+(* x, a BOOL, as a condition: a value compared with 0 if it isn't one *)
798+proc makeCond(var x: Item): ERROR;
799+begin
800+ if x.mode = mCond then return nil; end;
801+ try value(x);
802+ Gen.pushConst(Gen.kWord, 0);
803+ x.mode := mCond;
804+ x.rel := Scan.sNeq;
805+ x.relSigned := false;
806+ x.fj := Gen.NoLabel;
807+ x.tj := Gen.NoLabel;
808+ return nil;
809+end;
810+
811+proc op1*(op: Scan.Sym; var x: Item; var L: INT): ERROR;
812+begin
813+ L := Gen.NoLabel;
814+ if ((op = Scan.sAnd) or (op = Scan.sOr)) and (x.typ^.form = Sym.fBool) then
815+ if x.mode = mConst then return nil; end; (* folded by op2 *)
816+ try makeCond(x);
817+ if op = Scan.sAnd then
818+ Gen.jumpOut(negated(x.rel), x.relSigned, x.fj);
819+ Gen.fix(x.tj);
820+ x.tj := Gen.NoLabel;
821+ else
822+ Gen.jumpOut(x.rel, x.relSigned, x.tj);
823+ Gen.fix(x.fj);
824+ x.fj := Gen.NoLabel;
825+ end;
826+ elsif ((op = Scan.sEql) or (op = Scan.sNeq)) and isSeq(x.typ) then
827+ try seqSlice(x);
828+ elsif (op = Scan.sPlus) and (x.mode = mStr) then
829+ (* two string constants to be joined: nothing to compute *)
830+ elsif (op = Scan.sPlus) and isSeq(x.typ) then
831+ return Scan.markHelp(x.pos, say1("+ doesn't join {}", what(x)), "strings are joined in a Buf: Buf.str(b, s)");
832+ elsif x.mode in {mType, mBuiltin, mNone, mCase, mStr} then
833+ return notValue(x);
834+ elsif x.mode # mConst then
835+ try value(x);
836+ end;
837+ return nil;
838+end;
839+
840+proc log2(v: I64): INT;
841+var n: INT;
842+begin
843+ n := 0;
844+ while (v > 1) and ((v & 1) = 0) do v := v shr 1; INC(n); end;
845+ if v # 1 then n := -1; end;
846+ return n;
847+end;
848+
849+(* Whether a op b, for + - *, overflows an I64: an untyped constant
850+ doesn't wrap, it is an error (report section 4). *)
851+proc overflows(op: Scan.Sym; a, b: I64): BOOL;
852+begin
853+ match op of
854+ | sPlus: return ((b > 0) and (a > MaxI64 - b)) or ((b < 0) and (a < MinI64 - b));
855+ | sMinus: return ((b < 0) and (a > MaxI64 + b)) or ((b > 0) and (a < MinI64 + b));
856+ | sTimes:
857+ if (a = 0) or (b = 0) then return false; end;
858+ if a = -1 then return b = MinI64; end;
859+ if b = -1 then return a = MinI64; end;
860+ return (a * b) div b # a;
861+ | else: return false;
862+ end;
863+end;
864+
865+(* A type's width in bits; an untyped constant's is an I64's *)
866+proc bits(t: ^Sym.Type): I64;
867+begin
868+ return t^.size * 8;
869+end;
870+
871+proc foldInt(op: Scan.Sym; a, b: I64; t: ^Sym.Type; p: Diag.Pos): (I64, ERROR);
872+var u: BOOL;
873+begin
874+ u := (t^.form = Sym.fInt) and not t^.signed;
875+ if (t^.form = Sym.fConst) and overflows(op, a, b) then
876+ return 0, Scan.markAt(p, "the constant is too big for I64");
877+ end;
878+ match op of
879+ | sPlus: return a + b, nil;
880+ | sMinus: return a - b, nil;
881+ | sTimes: return a * b, nil;
882+ | sDiv, sMod:
883+ if b = 0 then return 0, Scan.markAt(p, "division by zero"); end;
884+ if u then
885+ if op = Scan.sDiv then return I64(U64(a) div U64(b)), nil; end;
886+ return I64(U64(a) mod U64(b)), nil;
887+ end;
888+ if (b = -1) and (a = I64(-1) shl (bits(t) - 1)) then return 0, Scan.markAt(p, "division overflows"); end;
889+ if op = Scan.sDiv then return a div b, nil; end;
890+ return a mod b, nil;
891+ | sAmp: return a & b, nil;
892+ | sBar: return a | b, nil;
893+ | sXor: return a xor b, nil;
894+ | sShl: return a shl (b & (bits(t) - 1)), nil;
895+ | sShr:
896+ if u then return I64(U64(a) shr (b & (bits(t) - 1))), nil; end;
897+ return a shr (b & (bits(t) - 1)), nil;
898+ | sEql: return bit(a = b), nil;
899+ | sNeq: return bit(a # b), nil;
900+ | sLss:
901+ if u then return bit(U64(a) < U64(b)), nil; end;
902+ return bit(a < b), nil;
903+ | sLeq:
904+ if u then return bit(U64(a) <= U64(b)), nil; end;
905+ return bit(a <= b), nil;
906+ | sGtr:
907+ if u then return bit(U64(a) > U64(b)), nil; end;
908+ return bit(a > b), nil;
909+ | sGeq:
910+ if u then return bit(U64(a) >= U64(b)), nil; end;
911+ return bit(a >= b), nil;
912+ | else: return 0, Scan.markAt(p, "bad operator");
913+ end;
914+end;
915+
916+(* Folds x op y, of the real type t: an F32 rounded at each step, as
917+ the machine would. *)
918+proc foldReal(op: Scan.Sym; x, y: Item; t: ^Sym.Type; var r: Item): BOOL;
919+var a, b: F64; ok: BOOL;
920+begin
921+ a := realOf(x); b := realOf(y);
922+ ok := true;
923+ match op of
924+ | sPlus: makeReal(r, a + b);
925+ | sMinus: makeReal(r, a - b);
926+ | sTimes: makeReal(r, a * b);
927+ | sSlash: makeReal(r, a / b);
928+ | sEql: makeConst(r, Sym.tBool, bit(a = b));
929+ | sNeq: makeConst(r, Sym.tBool, bit(a # b));
930+ | sLss: makeConst(r, Sym.tBool, bit(a < b));
931+ | sLeq: makeConst(r, Sym.tBool, bit(a <= b));
932+ | sGtr: makeConst(r, Sym.tBool, bit(a > b));
933+ | sGeq: makeConst(r, Sym.tBool, bit(a >= b));
934+ | else: ok := false;
935+ end;
936+ if r.typ^.form = Sym.fReal then realTo(r, t); end;
937+ return ok;
938+end;
939+
940+(* and, or and not are for BOOLs; &, |, xor and ~ for the bits of
941+ integers: x is the wrong kind for op, and the message names the
942+ operator it may have meant *)
943+proc wrongLogic(op: Scan.Sym; var x: Item): ERROR;
944+var bitsOf: []U8;
945+begin
946+ bitsOf := "the bits of integers take ";
947+ if (op = Scan.sAnd) and Sym.isInt(x.typ) then
948+ return Scan.markHelp(x.pos, say1("\"and\" needs BOOLs, found {}", what(x)), say1("{}&", bitsOf));
949+ elsif (op = Scan.sOr) and Sym.isInt(x.typ) then
950+ return Scan.markHelp(x.pos, say1("\"or\" needs BOOLs, found {}", what(x)), say1("{}|", bitsOf));
951+ elsif op = Scan.sAmp then
952+ return Scan.markHelp(x.pos, say1("\"&\" needs integers, found {}", what(x)), "BOOLs take and");
953+ elsif op = Scan.sBar then
954+ return Scan.markHelp(x.pos, say1("\"|\" needs integers, found {}", what(x)), "BOOLs take or");
955+ elsif op = Scan.sXor then
956+ return Scan.markHelp(x.pos, say1("\"xor\" needs integers, found {}", what(x)), "BOOLs that differ are #");
957+ end;
958+ return Scan.markAt(x.pos, say2("{} needs BOOLs, found {}", Scan.symText(op), what(x)));
959+end;
960+
961+(* x + y, of two string constants: one string, in a chunk of its own
962+ (report section 4) *)
963+proc joinStr(var x, y: Item): ERROR;
964+var p: ^U8; c, xs, ys, xl, yl: INT;
965+begin
966+ if y.mode # mStr then
967+ return Scan.markAt(y.pos, say1("\"+\" joins two strings, found {}", what(y)));
968+ end;
969+ xs := Chunk.chunks[x.chunk].start;
970+ ys := Chunk.chunks[y.chunk].start;
971+ xl := INT(x.val);
972+ yl := INT(y.val);
973+ p := Scan.grab(xl + yl + 1);
974+ COPY(p[0..xl], Chunk.rodata[xs..xs + xl]);
975+ COPY(p[xl..xl + yl + 1], Chunk.rodata[ys..ys + yl + 1]);
976+ c := Chunk.newChunk(Chunk.secRodata, -1, -1);
977+ Chunk.setData(c, p, xl + yl + 1, 1);
978+ x.chunk := c;
979+ x.val := x.val + y.val;
980+ return nil;
981+end;
982+
983+(* A set's operations, as operations on its bits: the two values on top *)
984+proc setOp(op: Scan.Sym);
985+begin
986+ match op of
987+ | sPlus: Gen.op(Scan.sBar, Gen.kWord, 8, false);
988+ | sTimes: Gen.op(Scan.sAmp, Gen.kWord, 8, false);
989+ | sMinus: Gen.complement(8, false); Gen.op(Scan.sAmp, Gen.kWord, 8, false);
990+ | sLeq, sGeq:
991+ (* x <= y has no bit of x outside y *)
992+ if op = Scan.sGeq then Gen.swap(); end;
993+ Gen.complement(8, false);
994+ Gen.op(Scan.sAmp, Gen.kWord, 8, false);
995+ Gen.pushConst(Gen.kWord, 0);
996+ Gen.compare(Scan.sEql, Gen.kWord, false);
997+ | sIn:
998+ Gen.swap();
999+ Gen.op(Scan.sShr, Gen.kWord, 8, false);
1000+ Gen.pushConst(Gen.kWord, 1);
1001+ Gen.op(Scan.sAmp, Gen.kWord, 8, false);
1002+ | else: Gen.compare(op, Gen.kWord, false);
1003+ end;
1004+end;
1005+
1006+(* The operators the arithmetic of integers, of reals and of sets
1007+ stand for, and the comparisons *)
1008+proc intOp(op: Scan.Sym): BOOL;
1009+begin
1010+ return isRel(op) or oneOf(op, [Scan.sPlus, Scan.sMinus, Scan.sTimes, Scan.sDiv, Scan.sMod,
1011+ Scan.sAmp, Scan.sBar, Scan.sXor, Scan.sShl, Scan.sShr]);
1012+end;
1013+
1014+proc doesntApply(op: Scan.Sym; x, y: Item; t: ^Sym.Type): ERROR;
1015+begin
1016+ return Scan.markAt(Diag.join(x.pos, y.pos), say2("{} doesn't apply to {}", Scan.symText(op), Sym.typeName(t)));
1017+end;
1018+
1019+proc op2*(op: Scan.Sym; var x, y: Item; _L: INT): ERROR;
1020+var xt, yt, t, e: ^Sym.Type; r: Item; scale: INT; isPtr: BOOL; a, b, v: I64;
1021+begin
1022+ xt := x.typ; yt := y.typ;
1023+ if y.mode in {mType, mBuiltin, mNone, mCase} then return notValue(y); end;
1024+ if (op = Scan.sPlus) and (x.mode = mStr) then return joinStr(x, y); end;
1025+
1026+ if (op = Scan.sAnd) or (op = Scan.sOr) then
1027+ if xt^.form # Sym.fBool then return wrongLogic(op, x); end;
1028+ if yt^.form # Sym.fBool then return wrongLogic(op, y); end;
1029+ if (x.mode = mConst) and (y.mode = mConst) then
1030+ if op = Scan.sAnd then x.val := x.val & y.val; else x.val := x.val | y.val; end;
1031+ elsif x.mode = mConst then
1032+ (* true and y, false or y: y; else x, y computed and dropped *)
1033+ if (x.val = 1) = (op = Scan.sAnd) then x := y;
1034+ else try discard(y); end;
1035+ else
1036+ try makeCond(y);
1037+ if op = Scan.sAnd then x.fj := Gen.joinJumps(x.fj, y.fj); x.tj := y.tj;
1038+ else x.tj := Gen.joinJumps(x.tj, y.tj); x.fj := y.fj; end;
1039+ x.rel := y.rel;
1040+ x.relSigned := y.relSigned;
1041+ end;
1042+ return nil;
1043+ end;
1044+
1045+ if oneOf(op, [Scan.sAmp, Scan.sBar, Scan.sXor]) and (xt^.form = Sym.fBool) then return wrongLogic(op, x); end;
1046+ if oneOf(op, [Scan.sAmp, Scan.sBar, Scan.sXor]) and (yt^.form = Sym.fBool) then return wrongLogic(op, y); end;
1047+
1048+ (* the lengths, then the bytes, LEN * SIZE(T) of them: the elements
1049+ are of types whose bytes say all there is to their values *)
1050+ if ((op = Scan.sEql) or (op = Scan.sNeq)) and isSeq(xt) then
1051+ e := elemOf(xt);
1052+ if not isSeq(yt) then
1053+ return Scan.markAt(Diag.join(x.pos, y.pos), say1("can't compare an array with {}", Sym.typeName(yt)));
1054+ elsif not Sym.same(e, elemOf(yt)) then
1055+ return Scan.markAt(Diag.join(x.pos, y.pos),
1056+ say2("can't compare an array of {} with one of {}", Sym.typeName(e), Sym.typeName(elemOf(yt))));
1057+ end;
1058+ if e^.form = Sym.fReal then
1059+ return Scan.markHelp(Diag.join(x.pos, y.pos),
1060+ say1("can't compare arrays of reals with {}", Scan.symText(op)),
1061+ "-0.0 = 0.0 and a NaN equals nothing, though their bytes say otherwise: write a loop");
1062+ elsif not (e^.form in {Sym.fInt, Sym.fBool, Sym.fEnum, Sym.fSet, Sym.fPtr}) then
1063+ return Scan.markHelp(Diag.join(x.pos, y.pos),
1064+ say2("can't compare arrays of {} with {}", Sym.typeName(e), Scan.symText(op)), "write a loop");
1065+ end;
1066+ try seqSlice(y);
1067+ Gen.compareSeq(x.off, y.off, log2(e^.size), op = Scan.sEql);
1068+ makeConst(x, Sym.tBool, 0);
1069+ x.mode := mStack;
1070+ return nil;
1071+ end;
1072+
1073+ (* the type of the result, and the checks *)
1074+ t := nil; scale := 1; isPtr := false;
1075+ if Sym.isInt(xt) and Sym.isInt(yt) then
1076+ if op = Scan.sSlash then
1077+ return Scan.markHelp(Diag.join(x.pos, y.pos), "\"/\" divides reals, not integers",
1078+ say2("to divide integers, write {} div {}", Diag.source(x.pos), Diag.source(y.pos)));
1079+ end;
1080+ if (op = Scan.sShl) or (op = Scan.sShr) then
1081+ if xt^.form = Sym.fConst then t := Sym.tConst; else t := xt; end;
1082+ elsif (xt^.form = Sym.fConst) and (yt^.form = Sym.fConst) then t := Sym.tConst;
1083+ elsif xt^.form = Sym.fConst then
1084+ if (x.mode = mConst) and not Sym.fits(x.val, yt) then
1085+ return Scan.markAt(x.pos, Diag.say("{} doesn't fit {}", [Fmt.int(x.val), Fmt.str(Sym.typeName(yt))]));
1086+ end;
1087+ t := yt;
1088+ elsif yt^.form = Sym.fConst then
1089+ if (y.mode = mConst) and not Sym.fits(y.val, xt) then
1090+ return Scan.markAt(y.pos, Diag.say("{} doesn't fit {}", [Fmt.int(y.val), Fmt.str(Sym.typeName(xt))]));
1091+ end;
1092+ t := xt;
1093+ elsif Sym.same(xt, yt) then t := xt;
1094+ else return mismatchOps(x, y, xt, yt); end;
1095+ if not intOp(op) then return doesntApply(op, x, y, t); end;
1096+ elsif (xt^.form = Sym.fReal) and (yt^.form = Sym.fReal) then
1097+ if not (isRel(op) or oneOf(op, [Scan.sPlus, Scan.sMinus, Scan.sTimes, Scan.sSlash])) then
1098+ return doesntApply(op, x, y, xt);
1099+ end;
1100+ if xt = Sym.tRConst then t := yt;
1101+ elsif (yt = Sym.tRConst) or Sym.same(xt, yt) then t := xt;
1102+ else return mismatchOps(x, y, xt, yt); end;
1103+ if (x.mode = mConst) and (x.typ # t) then realTo(x, t); end;
1104+ if (y.mode = mConst) and (y.typ # t) then realTo(y, t); end;
1105+ elsif (xt^.form = Sym.fBool) and (yt^.form = Sym.fBool) then
1106+ if (op # Scan.sEql) and (op # Scan.sNeq) then return doesntApply(op, x, y, xt); end;
1107+ t := Sym.tBool;
1108+ elsif (xt^.form = Sym.fPtr) and Sym.isInt(yt) and ((op = Scan.sPlus) or (op = Scan.sMinus)) then
1109+ t := xt; scale := INT(xt^.base^.size); isPtr := true;
1110+ if y.mode = mConst then y.typ := Sym.tInt; end;
1111+ elsif (xt^.form = Sym.fPtr) and (yt^.form = Sym.fPtr) and (op = Scan.sMinus) then
1112+ if not Sym.same(xt, yt) then return mismatchOps(x, y, xt, yt); end;
1113+ t := Sym.tInt; scale := INT(xt^.base^.size); isPtr := true;
1114+ elsif (xt^.form in {Sym.fPtr, Sym.fProc, Sym.fNil, Sym.fError}) and (yt^.form in {Sym.fPtr, Sym.fProc, Sym.fNil, Sym.fError}) then
1115+ if not isRel(op) then return doesntApply(op, x, y, xt); end;
1116+ if (xt^.form in {Sym.fProc, Sym.fError}) or (yt^.form in {Sym.fProc, Sym.fError}) then
1117+ if (op # Scan.sEql) and (op # Scan.sNeq) then return doesntApply(op, x, y, xt); end;
1118+ end;
1119+ if (xt^.form # Sym.fNil) and (yt^.form # Sym.fNil) and not Sym.same(xt, yt) then
1120+ if not ((xt^.form = Sym.fPtr) and (yt^.form = Sym.fPtr) and Sym.same(xt^.base, yt^.base)) then
1121+ return mismatchOps(x, y, xt, yt);
1122+ end;
1123+ end;
1124+ t := Sym.tU64;
1125+ elsif (xt^.form = Sym.fEnum) and Sym.same(xt, yt) then
1126+ if not isRel(op) then return doesntApply(op, x, y, xt); end;
1127+ t := xt;
1128+ elsif (xt^.form = Sym.fSet) and Sym.same(xt, yt) then
1129+ if not oneOf(op, [Scan.sPlus, Scan.sTimes, Scan.sMinus, Scan.sEql, Scan.sNeq, Scan.sLeq, Scan.sGeq]) then
1130+ return doesntApply(op, x, y, xt);
1131+ end;
1132+ t := xt;
1133+ elsif (op = Scan.sIn) and (yt^.form = Sym.fSet) and Sym.same(xt, yt^.base) then
1134+ t := yt;
1135+ else
1136+ return mismatchOps(x, y, xt, yt);
1137+ end;
1138+
1139+ (* constants *)
1140+ if (x.mode = mConst) and (y.mode = mConst) and not isPtr then
1141+ if t^.form = Sym.fReal then
1142+ if not foldReal(op, x, y, t, r) then return doesntApply(op, x, y, xt); end;
1143+ x := r;
1144+ elsif t^.form = Sym.fSet then
1145+ a := x.val; b := y.val;
1146+ match op of
1147+ | sPlus: makeConst(x, t, a | b);
1148+ | sTimes: makeConst(x, t, a & b);
1149+ | sMinus: makeConst(x, t, a & ~b);
1150+ | sIn: makeConst(x, Sym.tBool, (b shr a) & 1);
1151+ | sLeq: makeConst(x, Sym.tBool, bit((a & ~b) = 0));
1152+ | sGeq: makeConst(x, Sym.tBool, bit((b & ~a) = 0));
1153+ | else: makeConst(x, Sym.tBool, bit((a = b) = (op = Scan.sEql)));
1154+ end;
1155+ elsif isRel(op) then
1156+ v := try foldInt(op, x.val, y.val, t, Diag.join(x.pos, y.pos));
1157+ makeConst(x, Sym.tBool, v);
1158+ else
1159+ v := try foldInt(op, x.val, y.val, t, Diag.join(x.pos, y.pos));
1160+ makeConst(x, t, cut(v, t));
1161+ end;
1162+ return nil;
1163+ end;
1164+
1165+ (* x and y on the stack, x under y; a constant x goes on after y, and
1166+ is left on top where the order doesn't matter, as Gen takes a
1167+ constant best on the right: 0.25 * e is mulsd xmm8, [0.25] *)
1168+ try value(y);
1169+ if x.mode = mConst then
1170+ try value(x);
1171+ if not oneOf(op, [Scan.sPlus, Scan.sTimes, Scan.sAmp, Scan.sBar, Scan.sXor]) or isPtr then Gen.swap(); end;
1172+ end;
1173+
1174+ if t^.form = Sym.fReal then
1175+ if isRel(op) then Gen.compare(op, Gen.kindOf(t), false);
1176+ else Gen.op(op, Gen.kindOf(t), 8, false); end;
1177+ elsif t^.form = Sym.fSet then
1178+ setOp(op);
1179+ elsif isRel(op) then
1180+ x.mode := mCond;
1181+ x.rel := op;
1182+ x.relSigned := signed(t);
1183+ x.fj := Gen.NoLabel;
1184+ x.tj := Gen.NoLabel;
1185+ x.typ := Sym.tBool;
1186+ return nil;
1187+ elsif isPtr then
1188+ if t # Sym.tInt then scaleBy(scale); end;
1189+ Gen.op(op, Gen.kWord, 8, false);
1190+ if (t = Sym.tInt) and (scale # 1) then
1191+ Gen.pushConst(Gen.kWord, scale);
1192+ Gen.op(Scan.sDiv, Gen.kWord, 8, true);
1193+ end;
1194+ else
1195+ Gen.op(op, Gen.kindOf(t), intSize(t), signed(t));
1196+ end;
1197+ x.mode := mStack;
1198+ if isRel(op) or (op = Scan.sIn) then x.typ := Sym.tBool; else x.typ := t; end;
1199+ return nil;
1200+end;
1201+
1202+(* INT and UINT, the integers as big as an address, through which
1203+ integers and pointers convert (report section 6.7) *)
1204+proc isWord*(t: ^Sym.Type): BOOL;
1205+begin
1206+ return Sym.same(t, Sym.tInt) or Sym.same(t, Sym.tUInt);
1207+end;
1208+
1209+proc convert*(var x: Item; t: ^Sym.Type): ERROR;
1210+var s: ^Sym.Type; r: F64;
1211+begin
1212+ s := x.typ;
1213+ if x.mode in {mType, mBuiltin, mNone, mCase, mStr} then
1214+ if x.mode = mStr then return Scan.markAt(x.pos, "can't convert a string"); end;
1215+ return notValue(x);
1216+ end;
1217+ if Sym.same(s, t) then return nil; end;
1218+ if (Sym.isInt(s) or (s^.form in {Sym.fEnum, Sym.fSet})) and (t^.form = Sym.fInt) then
1219+ if x.mode = mConst then x.val := cut(x.val, t);
1220+ else try value(x); Gen.narrow(INT(t^.size), t^.signed); end;
1221+ elsif Sym.isInt(s) and (t^.form = Sym.fEnum) then
1222+ if x.mode = mConst then
1223+ if (x.val < 0) or (x.val >= t^.len) then
1224+ return Scan.markAt(x.pos, Diag.say("{} isn't a position of {}", [Fmt.int(x.val), Fmt.str(Sym.typeName(t))]));
1225+ end;
1226+ else try value(x); Gen.checkEnum(t^.len, nameChunk(t), x.pos); end;
1227+ elsif Sym.isInt(s) and (t^.form = Sym.fSet) then
1228+ if x.mode = mConst then
1229+ if t^.len < 64 then x.val := x.val & ((I64(1) shl t^.len) - 1); end;
1230+ else
1231+ try value(x);
1232+ if t^.len < 64 then
1233+ Gen.pushConst(Gen.kWord, (I64(1) shl t^.len) - 1);
1234+ Gen.op(Scan.sAmp, Gen.kWord, 8, false);
1235+ end;
1236+ end;
1237+ elsif Sym.isInt(s) and (t^.form = Sym.fReal) then
1238+ if x.mode = mConst then
1239+ if (s^.form = Sym.fInt) and not s^.signed then r := F64(U64(x.val)); else r := F64(x.val); end;
1240+ makeReal(x, r);
1241+ realTo(x, t);
1242+ else
1243+ try value(x);
1244+ Gen.intToReal(Gen.kindOf(t), (s^.form = Sym.fInt) and not s^.signed and (s^.size = 8));
1245+ end;
1246+ elsif (s^.form = Sym.fReal) and (t^.form = Sym.fReal) then
1247+ (* F32 to F64, F64 to F32, or a real constant to either *)
1248+ if x.mode = mConst then realTo(x, t);
1249+ else try value(x); Gen.realToReal(Gen.kindOf(s)); end;
1250+ elsif (s^.form = Sym.fReal) and (t^.form = Sym.fInt) then
1251+ if x.mode = mConst then
1252+ r := realOf(x);
1253+ (* NaN or out of range folds to low(int64), the "integer
1254+ indefinite" cvttsd2si gives at run time *)
1255+ if (r # r) or (r >= 9.2233720368547758E18) or (r < -9.2233720368547758E18) then
1256+ x.val := cut(MinI64, t);
1257+ else x.val := cut(I64(r), t); end;
1258+ else
1259+ try value(x); Gen.realToInt(Gen.kindOf(s)); Gen.narrow(INT(t^.size), t^.signed);
1260+ end;
1261+ elsif (isWord(s) or (s^.form in {Sym.fConst, Sym.fPtr, Sym.fProc, Sym.fNil})) and (t^.form in {Sym.fPtr, Sym.fProc}) then
1262+ if x.mode # mConst then try value(x); end;
1263+ elsif (s^.form in {Sym.fPtr, Sym.fProc}) and isWord(t) then
1264+ try value(x);
1265+ else
1266+ return Scan.markAt(x.pos, say2("can't convert {} to {}", Sym.typeName(s), Sym.typeName(t)));
1267+ end;
1268+ x.typ := t;
1269+ return nil;
1270+end;
1271+
1272+(* Calls *)
1273+
1274+proc beginCall*(var c: Gen.CallInfo; var x: Item): ERROR;
1275+begin
1276+ if x.mode = mProc then
1277+ c.sig := x.obj^.typ; c.chunk := x.obj^.chunk; c.target := 0;
1278+ c.obj := x.obj; c.ext := x.obj^.ext;
1279+ else
1280+ c.obj := nil; c.ext := false;
1281+ if x.typ^.form # Sym.fProc then
1282+ return Scan.markAt(x.pos, say1("expected a procedure, found {}", what(x)));
1283+ end;
1284+ c.sig := x.typ; c.chunk := -1;
1285+ c.target := try toSlot(x);
1286+ end;
1287+ c.param := c.sig^.fields;
1288+ c.n := 0;
1289+ return nil;
1290+end;
1291+
1292+(* Too many arguments or too few, at p *)
1293+proc wrongCount(var c: Gen.CallInfo; p: Diag.Pos; text: []U8): ERROR;
1294+begin
1295+ if c.obj = nil then return Scan.markAt(p, text); end;
1296+ Diag.error(p, Diag.say("{}: {} takes {}", [Fmt.str(text), Fmt.str(Scan.nameOf(c.obj^.name)), Fmt.int(c.sig^.len)]));
1297+ if c.obj^.home # nil then Diag.note(c.obj^.pos, "the signature is here"); end;
1298+ return Scan.Failed;
1299+end;
1300+
1301+(* Pushes the two words of x, a slice or two results (inTwoRegs), read
1302+ from memory now, so that what comes after can't change them. *)
1303+proc pushWords(var x: Item): ERROR;
1304+var adr: Gen.Adr; f: ^Sym.Obj;
1305+begin
1306+ if x.mode = mWords then return nil; end; (* there already *)
1307+ (* copied to a temporary unless its two words are in memory at a place
1308+ 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
1310+ try copyToTemp(x);
1311+ end;
1312+ adr := adrOf(x);
1313+ if x.typ^.form = Sym.fSlice then
1314+ Gen.pushVar(adr, 8, false, Gen.kWord);
1315+ INC(adr.off, 8);
1316+ Gen.pushVar(adr, 8, false, Gen.kWord);
1317+ else
1318+ f := x.typ^.fields;
1319+ while f # nil do
1320+ adr.off := adrOf(x).off + f^.val;
1321+ Gen.pushVar(adr, scalarSize(f^.typ), signed(f^.typ), Gen.kindOf(f^.typ));
1322+ f := f^.next;
1323+ end;
1324+ end;
1325+ return nil;
1326+end;
1327+
1328+proc passArg*(var c: Gen.CallInfo; var a: Item): ERROR;
1329+var p: ^Sym.Obj;
1330+begin
1331+ p := c.param;
1332+ if c.n >= LEN(c.isF) - 1 then return Scan.markAt(a.pos, "too many arguments"); end;
1333+ if p = nil then
1334+ (* past the parameters of a C procedure that ends in ...: a string
1335+ goes as a C string, an integer constant as an INT, a real
1336+ constant as an F64; C takes no F32 there *)
1337+ if not c.sig^.variadic then return wrongCount(c, a.pos, "too many arguments"); end;
1338+ if a.mode = mStr then try coerce(a, Sym.tPtrU8);
1339+ elsif a.typ^.form = Sym.fConst then try coerce(a, Sym.tInt);
1340+ elsif a.typ = Sym.tRConst then try coerce(a, Sym.tReal);
1341+ elsif isF32(a.typ) then return Scan.markAt(a.pos, "an F32 goes to ... as F64(x)");
1342+ elsif not Sym.isScalar(a.typ) then return Scan.markAt(a.pos, "only a single value goes to ..."); end;
1343+ c.isF[c.n] := a.typ^.form = Sym.fReal;
1344+ c.pair[c.n] := false;
1345+ try value(a);
1346+ INC(c.n);
1347+ return nil;
1348+ end;
1349+ c.isF[c.n] := (p^.typ^.form = Sym.fReal) and not p^.isVar;
1350+ passing := p;
1351+ passingAt := a.pos;
1352+ if p^.isVar then
1353+ try notReadOnly(a);
1354+ if (a.mode # mVar) or not a.isVar then return Scan.markAt(a.pos, "a var parameter needs a variable"); end;
1355+ if a.odd then return Scan.markAt(a.pos, "a field of a packed record can't be a var parameter"); end;
1356+ if not Sym.same(a.typ, p^.typ) then
1357+ return mismatch(a, say2("a var parameter needs exactly {}, found {}", Sym.typeName(p^.typ), what(a)));
1358+ end;
1359+ if a.vol then return Scan.markAt(a.pos, "can't pass through a volatile pointer to a var parameter"); end;
1360+ try address(a);
1361+ elsif p^.typ^.form = Sym.fSlice then
1362+ try coerce(a, p^.typ);
1363+ try pushWords(a);
1364+ c.pair[c.n] := true;
1365+ INC(c.n);
1366+ c.isF[c.n] := false;
1367+ elsif Sym.isAggregate(p^.typ) then
1368+ try coerce(a, p^.typ);
1369+ if a.isVar or a.vol or (a.base # Gen.bFrame) then try copyToTemp(a); end;
1370+ try address(a);
1371+ else
1372+ try coerce(a, p^.typ);
1373+ try value(a);
1374+ end;
1375+ c.pair[c.n] := false;
1376+ INC(c.n);
1377+ c.param := p^.next;
1378+ return nil;
1379+end;
1380+
1381+(* The call c made, with x its result as an item: none; a temporary, for a
1382+ slice or a record; two results on Gen's stack (mWords); else one value
1383+ on the stack. *)
1384+proc endCall*(var c: Gen.CallInfo; var x: Item): ERROR;
1385+var res: ^Sym.Type;
1386+begin
1387+ if c.param # nil then try wrongCount(c, Scan.tokPos(), "too few arguments"); end;
1388+ Gen.call(c);
1389+ res := c.sig^.base;
1390+ x := {};
1391+ if res = nil then
1392+ x.mode := mNone; x.typ := Sym.tNone; x.obj := c.obj;
1393+ elsif c.ret # 0 then
1394+ tempItem(x, res, c.ret);
1395+ else
1396+ x.mode := mStack; x.typ := res;
1397+ if res^.tuple then x.mode := mWords; end;
1398+ end;
1399+ return nil;
1400+end;
1401+
1402+(* Variants *)
1403+
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;
1407+begin
1408+ tmp := Gen.allocTemp(t^.size, t^.align);
1409+ Gen.zeroVar(frameAdr(tmp), t^.size);
1410+ tempItem(x, t, tmp);
1411+end;
1412+
1413+proc construct*(var x: Item; c: ^Sym.Obj);
1414+begin
1415+ zeroTemp(x, c^.typ);
1416+ Gen.pushConst(Gen.kWord, c^.val);
1417+ Gen.popVar(frameAdr(x.off), 8);
1418+end;
1419+
1420+proc setField*(x: Item; f: ^Sym.Obj; var a: Item): ERROR;
1421+begin
1422+ try coerce(a, f^.typ);
1423+ if Sym.isScalar(f^.typ) then
1424+ try value(a);
1425+ Gen.popVar(frameAdr(x.off + f^.val), scalarSize(f^.typ));
1426+ else
1427+ if a.vol then return Scan.markAt(a.pos, "can't copy through a volatile pointer"); end;
1428+ try address(a);
1429+ Gen.copyTo(frameAdr(x.off + f^.val), f^.typ^.size);
1430+ end;
1431+ return nil;
1432+end;
1433+
1434+(* The slot match tests: a variant's address, or an enumeration's or an
1435+ integer's value. *)
1436+proc matchBegin*(var x: Item): (I64, ERROR);
1437+var p: I64;
1438+begin
1439+ if x.typ^.form in {Sym.fEnum, Sym.fInt} then return toSlot(x); end;
1440+ if (x.mode # mVar) or (x.typ^.form # Sym.fVariant) then
1441+ return 0, Scan.markAt(x.pos, say1("match needs a variant, an enumeration or an integer, found {}", what(x)));
1442+ end;
1443+ if x.ro then try copyToTemp(x); end; (* its arms' names stand for a copy's fields *)
1444+ try address(x);
1445+ p := Gen.allocTemp(8, 8);
1446+ Gen.popVar(frameAdr(p), 8);
1447+ return p, nil;
1448+end;
1449+
1450+(* To L unless the tag of the variant whose address is in slot p is tag *)
1451+proc matchTag*(p: I64; tag: I64; var L: INT);
1452+var a: Gen.Adr;
1453+begin
1454+ Gen.pushVar(frameAdr(p), 8, false, Gen.kWord);
1455+ a.base := Gen.bStack; a.chunk := -1; a.off := 0; a.hi := 0;
1456+ Gen.pushVar(a, 8, false, Gen.kWord);
1457+ Gen.pushConst(Gen.kWord, tag);
1458+ Gen.jumpCmp(Scan.sNeq, false, L);
1459+end;
1460+
1461+(* To body if the integer in slot p is from lo to hi: less its lo, it is
1462+ then at most hi - lo, compared unsigned, which holds for a signed type
1463+ or not, with no second jump. *)
1464+proc matchRange*(p, lo, hi: I64; var body: INT);
1465+begin
1466+ Gen.pushVar(frameAdr(p), 8, false, Gen.kWord);
1467+ if lo = hi then
1468+ Gen.pushConst(Gen.kWord, lo);
1469+ Gen.jumpCmp(Scan.sEql, false, body);
1470+ return;
1471+ end;
1472+ if lo # 0 then
1473+ Gen.pushConst(Gen.kWord, lo);
1474+ Gen.op(Scan.sMinus, Gen.kWord, 8, false);
1475+ end;
1476+ Gen.pushConst(Gen.kWord, hi - lo);
1477+ Gen.jumpCmp(Scan.sLeq, false, body);
1478+end;
1479+
1480+(* A for loop's variable o, stepped by step, wrapping as its type does *)
1481+proc forStep*(o: ^Sym.Obj; step: I64): ERROR;
1482+var v, w: Item;
1483+begin
1484+ try makeItem(v, o);
1485+ if v.base = Gen.bReg then
1486+ (* a variable in a register is stepped in it *)
1487+ Gen.pushConst(Gen.kWord, step);
1488+ Gen.incDecReg(v.chunk, intSize(o^.typ), signed(o^.typ), false);
1489+ return nil;
1490+ end;
1491+ try makeItem(w, o);
1492+ try value(w);
1493+ Gen.pushConst(Gen.kWord, step);
1494+ Gen.op(Scan.sPlus, Gen.kWord, intSize(o^.typ), signed(o^.typ));
1495+ return assign(v, w);
1496+end;
1497+
1498+(* For a for loop: pushes the variable o and the limit lim, a constant or
1499+ the slot it was put in, and jumps to L if the one is op the other, as
1500+ the type of o compares *)
1501+proc forCmp*(o: ^Sym.Obj; lim: Item; op: Scan.Sym; var L: INT): ERROR;
1502+var v, b: Item;
1503+begin
1504+ try makeItem(v, o);
1505+ try value(v);
1506+ b := lim;
1507+ try value(b);
1508+ Gen.jumpCmp(op, o^.typ^.signed, L);
1509+ return nil;
1510+end;
1511+
1512+(* The end of a round of a for loop, for a positive step s, as the report
1513+ has it: if v <= b and b - v < s, the loop ends; otherwise v becomes
1514+ v + s and the loop goes on while v <= b. Counting the distance left,
1515+ rather than comparing after the step, can't be fooled by v wrapping
1516+ around. A negative step is the same the other way round: before, past
1517+ and within are chosen by up, whether the step is positive.
1518+ For a step of 1: v < b goes on to top, where v is stepped; v = b
1519+ ends; otherwise the body moved v past b.
1520+ For another step: v past b goes to past; else b - v (unsigned, as
1521+ v <= b) >= |step| goes on to top, and else the loop ends.
1522+ Past: v is stepped here and tested, going to body if within b. *)
1523+proc forNext*(o: ^Sym.Obj; lim: Item; step: I64; var exitL: INT; top, body: INT): ERROR;
1524+var v, b: Item; L, pastL: INT; up: BOOL; before, past, within: Scan.Sym; a: I64;
1525+begin
1526+ up := step > 0;
1527+ (* by a negative step, by a positive *)
1528+ if up then before := Scan.sLss; past := Scan.sGtr; within := Scan.sLeq;
1529+ else before := Scan.sGtr; past := Scan.sLss; within := Scan.sGeq; end;
1530+ a := step;
1531+ if a < 0 then a := -a; end;
1532+ L := Gen.NoLabel;
1533+ pastL := Gen.NoLabel;
1534+ if a = 1 then
1535+ try forCmp(o, lim, before, L);
1536+ Gen.fixTo(L, top);
1537+ try forCmp(o, lim, Scan.sEql, exitL);
1538+ else
1539+ try forCmp(o, lim, past, pastL);
1540+ try makeItem(v, o);
1541+ b := lim;
1542+ if up then try value(b); try value(v);
1543+ else try value(v); try value(b); end;
1544+ Gen.op(Scan.sMinus, Gen.kWord, 8, false);
1545+ Gen.pushConst(Gen.kWord, a);
1546+ Gen.jumpCmp(Scan.sGeq, false, L);
1547+ Gen.fixTo(L, top);
1548+ Gen.jump(exitL);
1549+ end;
1550+ Gen.fix(pastL);
1551+ try forStep(o, step);
1552+ L := Gen.NoLabel;
1553+ try forCmp(o, lim, within, L);
1554+ Gen.fixTo(L, body);
1555+ return nil;
1556+end;
1557+
1558+(* Jumps to L if the condition x is false. The jumps waiting in x.fj join
1559+ L; those in x.tj are placed here, as x is true past this. *)
1560+proc condJump*(var x: Item; var L: INT): ERROR;
1561+begin
1562+ if x.typ^.form # Sym.fBool then
1563+ return Scan.markAt(x.pos, say1("a condition is a BOOL, found {}", what(x)));
1564+ end;
1565+ if x.mode = mCond then
1566+ Gen.jumpCmp(negated(x.rel), x.relSigned, L);
1567+ L := Gen.joinJumps(L, x.fj);
1568+ Gen.fix(x.tj);
1569+ return nil;
1570+ end;
1571+ try value(x);
1572+ Gen.jumpIf(L, false);
1573+ return nil;
1574+end;
1575+
1576+(* As condJump, but the jump to L is taken where the condition is true;
1577+ x.tj joins L and x.fj is placed here *)
1578+proc condJumpTrue*(var x: Item; var L: INT): ERROR;
1579+begin
1580+ if x.typ^.form # Sym.fBool then
1581+ return Scan.markAt(x.pos, say1("a condition is a BOOL, found {}", what(x)));
1582+ end;
1583+ if x.mode = mCond then
1584+ Gen.jumpCmp(x.rel, x.relSigned, L);
1585+ L := Gen.joinJumps(L, x.tj);
1586+ Gen.fix(x.fj);
1587+ return nil;
1588+ end;
1589+ try value(x);
1590+ Gen.jumpIf(L, true);
1591+ return nil;
1592+end;
1593+
1594+(* Procedures *)
1595+
1596+proc beginProc*(sig: ^Sym.Type; params: ^Sym.Obj);
1597+begin
1598+ result := sig^.base;
1599+ Gen.beginProc(sig, params);
1600+end;
1601+
1602+(* The result of return x: a value on top, a slice's two words on top,
1603+ or one copied behind the hidden pointer *)
1604+proc returnValue*(var x: Item): ERROR;
1605+begin
1606+ if result = nil then return Scan.markAt(x.pos, "this procedure returns nothing"); end;
1607+ try coerce(x, result);
1608+ if Sym.inTwoRegs(result) then try pushWords(x);
1609+ elsif Sym.isAggregate(result) then
1610+ if x.vol then return Scan.markAt(x.pos, "can't copy through a volatile pointer"); end;
1611+ try address(x);
1612+ Gen.copyResult(0, result^.size);
1613+ else try value(x); end;
1614+ return nil;
1615+end;
1616+
1617+(* One of several results: of two words, a value left on top for
1618+ returnJump to put in rax or rdx; else into its place behind the
1619+ hidden pointer. *)
1620+proc returnField*(f: ^Sym.Obj; var x: Item): ERROR;
1621+begin
1622+ try coerce(x, f^.typ);
1623+ if Sym.inTwoRegs(result) then try value(x);
1624+ elsif Sym.isScalar(f^.typ) then
1625+ try value(x);
1626+ Gen.resultTo(f^.val, scalarSize(f^.typ));
1627+ else
1628+ if x.vol then return Scan.markAt(x.pos, "can't copy through a volatile pointer"); end;
1629+ try address(x);
1630+ Gen.copyResult(f^.val, f^.typ^.size);
1631+ end;
1632+ return nil;
1633+end;
1634+
1635+(* Several results at once, the call's that return f(x) passes on. *)
1636+proc returnAll*(var x: Item): ERROR;
1637+begin
1638+ if Sym.inTwoRegs(result) then try pushWords(x);
1639+ else
1640+ try address(x);
1641+ Gen.copyResult(0, result^.size);
1642+ end;
1643+ return nil;
1644+end;
1645+
1646+proc returnNone*: ERROR;
1647+begin
1648+ if result # nil then
1649+ return Scan.mark(say1("return needs a result of {}", Sym.typeName(result)));
1650+ end;
1651+ Gen.returnJump();
1652+ return nil;
1653+end;
1654+
1655+(* Keeps a variable's address in a frame slot, rather than on the stack,
1656+ while other code runs. *)
1657+proc pin*(var x: Item): ERROR;
1658+var s: I64;
1659+begin
1660+ if (x.mode = mVar) and (x.base = Gen.bStack) then
1661+ try address(x);
1662+ s := Gen.allocTemp(8, 8);
1663+ Gen.popVar(frameAdr(s), 8);
1664+ x.base := Gen.bSlot;
1665+ x.chunk := INT(s);
1666+ end;
1667+ return nil;
1668+end;
1669+
1670+(* INC(v, k) or DEC: v's address is on the stack, from address. *)
1671+proc incDec*(var v, k: Item; dec: BOOL): ERROR;
1672+begin
1673+ try coerceExact(k, v.typ, "");
1674+ try value(k);
1675+ if v.base = Gen.bReg then Gen.incDecReg(v.chunk, scalarSize(v.typ), v.typ^.signed, dec);
1676+ else Gen.incDec(scalarSize(v.typ), v.typ^.signed, dec); end;
1677+ return nil;
1678+end;
1679+
1680+(* COPY(d, s): d, an array variable or a slice, as a slice in the frame,
1681+ before s is read *)
1682+proc copyDest*(var d: Item): ERROR;
1683+begin
1684+ if not isSeq(d.typ) or (d.mode = mStr) or ((d.typ^.form = Sym.fArray) and ((d.mode # mVar) or not d.isVar)) then
1685+ return Scan.markAt(d.pos, say1("COPY copies into an array variable or a slice, found {}", what(d)));
1686+ end;
1687+ if d.typ^.form = Sym.fArray then try notReadOnly(d); end;
1688+ return seqSlice(d);
1689+end;
1690+
1691+(* ... and the elements of s copied to its start *)
1692+proc copyFrom*(var d, s: Item): ERROR;
1693+begin
1694+ if not isSeq(s.typ) or not Sym.same(elemOf(s.typ), d.typ^.base) then
1695+ return Scan.markAt(s.pos, say2("COPY copies elements of {}, found {}", Sym.typeName(d.typ^.base), what(s)));
1696+ end;
1697+ try seqSlice(s);
1698+ Gen.copySlice(d.off, s.off, d.typ^.base^.size, checks, s.pos);
1699+ return nil;
1700+end;
1701+
1702+(* An error is the address of its length, followed by its message. *)
1703+proc errorChunk*(var x: Item; home, name: INT): (INT, ERROR);
1704+var c, xs, xl: INT; p: ^U8; q: ^I64;
1705+begin
1706+ if x.mode # mStr then return 0, Scan.markAt(x.pos, "an error is made from a string"); end;
1707+ xl := INT(x.val);
1708+ p := Scan.grab(xl + 8);
1709+ q := ^I64(p);
1710+ q^ := x.val;
1711+ xs := Chunk.chunks[x.chunk].start;
1712+ COPY(p[8..8 + xl], Chunk.rodata[xs..xs + xl]);
1713+ c := Chunk.newChunk(Chunk.secRodata, home, name);
1714+ Chunk.setData(c, p, xl + 8, 8);
1715+ return c, nil;
1716+end;
1717+
1718+proc msg*(var x: Item): ERROR;
1719+var s: I64;
1720+begin
1721+ try coerce(x, Sym.tError);
1722+ try value(x);
1723+ s := Gen.allocTemp(16, 8);
1724+ Gen.errorText(s);
1725+ tempItem(x, Sym.tBytes, s);
1726+ return nil;
1727+end;
1728+
1729+end Item.

src/Link.raz (history) added +380 -0

@@ -0,0 +1,380 @@
1+(* Link: tree shaking, layout and patching.
2+
3+ Starting from the entry chunk, marks every chunk the program can
4+ reach through fixups; the rest is left out. Then gives each live
5+ chunk its address and builds the images of text and rodata, with
6+ every fixup patched.
7+
8+ The file is laid out so that each section can be mapped as it lies:
9+ text right after the headers, rodata on the next page, then a
10+ writable page that starts with the table the dynamic loader reads
11+ (none in a static program) and goes on as bss, in memory only. The
12+ loader's other tables come at the end of rodata; Elf writes them
13+ in the room left there.
14+
15+ Depends on: Chunk for chunks and fixups, Scan for names and memory,
16+ Diag for errors and paths.
17+ Leaves out: the file format; that is Elf. *)
18+module Link;
19+import Fmt, Diag, Scan, Chunk;
20+
21+const
22+ Base* = 400000H;
23+ Page* = 4096;
24+
25+var
26+ textOff*, textSize*: INT; (* file offset and size of text, at Base + textOff *)
27+ roOff*, roSize*: INT; (* rodata, the room for the loader's tables included *)
28+ roAdr*: INT; (* where rodata is loaded *)
29+ extraAdr*: INT; (* that room *)
30+ bssAdr*, bssSize*: INT; (* the writable segment, the loader's table first *)
31+ bssOff*: INT; (* the file offset of that table *)
32+ textImg*, roImg*: ^U8;
33+ placesChunk*: INT; (* the rodata chunk of the places, made by the caller *)
34+ linesOff*, linesSize*: INT; (* the line table, in the places: .debug_line *)
35+
36+proc setPlaces*(c: INT);
37+begin
38+ placesChunk := c;
39+end;
40+
41+(* Marks live each chunk reached from entry through the fixups. *)
42+proc markLive*(entry: INT);
43+var stack: ^INT; sp, c, f, t: INT; fx: ^Chunk.Fixup;
44+begin
45+ stack := ^INT(Scan.grab(Chunk.numChunks * SIZE(INT)));
46+ Chunk.setLive(entry);
47+ stack[0] := entry;
48+ sp := 1;
49+ while sp > 0 do
50+ DEC(sp);
51+ c := stack[sp];
52+ if Chunk.chunks[c].size < 0 then
53+ Diag.fatal(Diag.say("{} is declared but never defined", [Fmt.str(Chunk.chunkName(c))]));
54+ end;
55+ (* code and constants have fixups; variables start at zero, holding
56+ no addresses *)
57+ match Chunk.chunks[c].sec of
58+ | secText: fx := Chunk.fixups;
59+ | secRodata: fx := Chunk.dataFixups;
60+ | secBss: fx := nil;
61+ end;
62+ if fx # nil then
63+ for f := Chunk.chunks[c].firstFix to Chunk.chunks[c].firstFix + Chunk.chunks[c].numFix - 1 do
64+ t := fx[f].chunk;
65+ if not Chunk.chunks[t].live then
66+ Chunk.setLive(t);
67+ stack[sp] := t;
68+ INC(sp);
69+ end;
70+ end;
71+ end;
72+ end;
73+end;
74+
75+(* Gives the live chunks of one section their places, from start;
76+ returns the end. *)
77+proc place(sec: Chunk.Section; start: INT): INT;
78+var c, a: INT;
79+begin
80+ a := start;
81+ for c := 0 to Chunk.numChunks - 1 do
82+ if Chunk.chunks[c].live and (Chunk.chunks[c].sec = sec) then
83+ a := (a + Chunk.chunks[c].align - 1) div Chunk.chunks[c].align * Chunk.chunks[c].align;
84+ Chunk.setAdr(c, a);
85+ a := a + Chunk.chunks[c].size;
86+ end;
87+ end;
88+ return a;
89+end;
90+
91+(* The line table, DWARF 4's line program, which gdb reads as
92+ .debug_line and Rt to say where code comes from: one sequence for
93+ each live procedure with lines, a row for each place noted, its
94+ address, file, line and column. A row whose address and line move a
95+ little is one byte, a special opcode; the others are made of the
96+ standard ones. Made in lp, lpLen bytes long. *)
97+const
98+ LineBase = -5; LineRange = 14; OpcodeBase = 13; (* the special opcodes' *)
99+
100+var
101+ lp: ^U8;
102+ lpLen, lpCap: INT;
103+
104+proc putB(v: INT);
105+begin
106+ if lpLen = lpCap then
107+ lp := Scan.regrab(lp, lpLen, lpCap * 2 + 256);
108+ lpCap := lpCap * 2 + 256;
109+ end;
110+ lp[lpLen] := U8(v & 0FFH);
111+ INC(lpLen);
112+end;
113+
114+(* The n low bytes of v, least significant first *)
115+proc putN(v: INT; n: INT);
116+var i: INT;
117+begin
118+ for i := 1 to n do putB(v); v := v shr 8; end;
119+end;
120+
121+(* LEB128, unsigned and signed *)
122+proc putU(v: INT);
123+begin
124+ while v >= 80H do putB(v & 7FH | 80H); v := v shr 7; end;
125+ putB(v);
126+end;
127+
128+proc putS(v: INT);
129+begin
130+ while (v < -64) or (v >= 64) do putB(v & 7FH | 80H); v := v shr 7; end;
131+ putB(v & 7FH);
132+end;
133+
134+(* v as the four bytes at at in p *)
135+proc patch4(p: ^U8; at, v: INT);
136+var i: INT;
137+begin
138+ for i := 0 to 3 do p[at + i] := U8((v shr (8 * i)) & 0FFH); end;
139+end;
140+
141+(* v as the eight bytes at at in p *)
142+proc patch8(p: ^U8; at, v: INT);
143+var i: INT;
144+begin
145+ for i := 0 to 7 do p[at + i] := U8((v shr (8 * i)) & 0FFH); end;
146+end;
147+
148+(* Whether the standard opcode i takes an operand *)
149+proc takesOperand(i: INT): BOOL;
150+begin
151+ return (i = 2) or (i = 3) or (i = 4) or (i = 5) or (i = 9) or (i = 12);
152+end;
153+
154+(* The line program of the files paths, nfiles of them, numbered from
155+ 1, as they are written in the table *)
156+proc makeLines(paths: ^INT; nfiles: INT);
157+var i, f, c, cf, cl, cc, op, at, da, dl: INT; s: []U8;
158+begin
159+ lpLen := 0;
160+ putN(0, 4); (* unit_length, patched below *)
161+ putN(4, 2); (* version *)
162+ putN(0, 4); (* header_length, patched below *)
163+ putB(1); putB(1); (* minimum_instruction_length, maximum_operations *)
164+ putB(1); (* default_is_stmt *)
165+ putB(LineBase); putB(LineRange); putB(OpcodeBase);
166+ for i := 1 to OpcodeBase - 1 do
167+ if takesOperand(i) then putB(1); else putB(0); end; (* their operands *)
168+ end;
169+ putB(0); (* no include directories *)
170+ for f := 0 to nfiles - 1 do
171+ s := Diag.shownPath(Scan.nameOf(paths[f]));
172+ for i := 0 to LEN(s) - 1 do putB(INT(s[i])); end;
173+ putN(0, 4); (* its end, directory, time, length *)
174+ end;
175+ putB(0);
176+ patch4(lp, 6, lpLen - 10);
177+ i := 0;
178+ while i < Chunk.numLines do
179+ c := Chunk.lines[i].chunk;
180+ if not Chunk.chunks[c].live then
181+ INC(i);
182+ else
183+ putB(0); putU(9); putB(2); (* DW_LNE_set_address *)
184+ putN(Chunk.chunks[c].adr + Chunk.lines[i].at - Chunk.chunks[c].start, 8);
185+ at := Chunk.lines[i].at; cf := 1; cl := 1; cc := 0;
186+ while (i < Chunk.numLines) and (Chunk.lines[i].chunk = c) do
187+ f := 1;
188+ while paths[f - 1] # Chunk.lines[i].path do INC(f); end;
189+ if f # cf then putB(4); putU(f); cf := f; end; (* DW_LNS_set_file *)
190+ if Chunk.lines[i].col # cc then putB(5); putU(Chunk.lines[i].col); cc := Chunk.lines[i].col; end; (* DW_LNS_set_column *)
191+ da := Chunk.lines[i].at - at;
192+ dl := Chunk.lines[i].line - cl;
193+ op := (dl - LineBase) + LineRange * da + OpcodeBase;
194+ if (dl >= LineBase) and (dl < LineBase + LineRange) and (op <= 255) then
195+ putB(op); (* a special opcode: a row *)
196+ else
197+ if da > 0 then putB(2); putU(da); end; (* DW_LNS_advance_pc *)
198+ if dl # 0 then putB(3); putS(dl); end; (* DW_LNS_advance_line *)
199+ putB(1); (* DW_LNS_copy: a row *)
200+ end;
201+ at := Chunk.lines[i].at; cl := Chunk.lines[i].line;
202+ INC(i);
203+ end;
204+ putB(2); putU(Chunk.chunks[c].start + Chunk.chunks[c].size - at);
205+ putB(0); putU(1); putB(1); (* DW_LNE_end_sequence *)
206+ end;
207+ end;
208+ patch4(lp, 0, lpLen - 4);
209+end;
210+
211+var
212+ buf: ^U8; (* the places, being made *)
213+ at, names, poolAt: INT; (* where the next number goes, the next name, the pool's start *)
214+
215+(* The name s, in the pool, and its offset from the pool's start, at at *)
216+proc putName(s: []U8);
217+begin
218+ patch4(buf, at, names - poolAt);
219+ COPY(buf[names..names + LEN(s)], s);
220+ buf[names + LEN(s)] := 0;
221+ names := names + LEN(s) + 1;
222+ at := at + 4;
223+end;
224+
225+(* Whether chunk c is a live procedure, whose places Rt knows *)
226+proc isProc(c: INT): BOOL;
227+begin
228+ return Chunk.chunks[c].live and (Chunk.chunks[c].sec = Chunk.secText) and (Chunk.chunks[c].home >= 0);
229+end;
230+
231+(* The places that Rt reads to say where a failed check or a signal
232+ was, and what calls were under way: where the line table is in them,
233+ where text starts and stops, the numbers of procedures and of their
234+ variables (I64s); for each live procedure where it starts and stops,
235+ the offset of its name, its first variable and how many it has, and
236+ the registers of variables it saves, as bits of Gen's VarRegs, and
237+ the frame offset they are saved at (U32s); for each variable the
238+ offset of its name, its place in the frame and its kind, as
239+ Parse's VarKind (U32s); then the names, each ending in a zero
240+ byte; then the line table (makeLines), at linesOff. They are in no
241+ order, since Rt looks at them only as the program stops. *)
242+proc makePlaces(start, stop: INT);
243+var
244+ files, first, count: ^INT;
245+ i, f, nfiles, np, nv, c, v: INT;
246+begin
247+ files := ^INT(Scan.grab(Chunk.numLines * SIZE(INT) + SIZE(INT)));
248+ first := ^INT(Scan.grab(Chunk.numChunks * SIZE(INT)));
249+ count := ^INT(Scan.grab(Chunk.numChunks * SIZE(INT)));
250+ for c := 0 to Chunk.numChunks - 1 do first[c] := 0; count[c] := 0; end;
251+ for v := Chunk.numVarNotes - 1 to 0 by -1 do
252+ first[Chunk.varNotes[v].chunk] := v;
253+ INC(count[Chunk.varNotes[v].chunk]);
254+ end;
255+ nfiles := 0; poolAt := 0; np := 0; nv := 0;
256+ for i := 0 to Chunk.numLines - 1 do
257+ if Chunk.chunks[Chunk.lines[i].chunk].live then
258+ f := 0;
259+ while (f < nfiles) and (files[f] # Chunk.lines[i].path) do INC(f); end;
260+ if f = nfiles then
261+ files[f] := Chunk.lines[i].path;
262+ INC(nfiles);
263+ end;
264+ end;
265+ end;
266+ makeLines(files, nfiles);
267+ for c := 0 to Chunk.numChunks - 1 do
268+ if isProc(c) then
269+ INC(np);
270+ poolAt := poolAt + LEN(Chunk.chunkName(c)) + 1;
271+ for v := first[c] to first[c] + count[c] - 1 do
272+ poolAt := poolAt + LEN(Scan.nameOf(Chunk.varNotes[v].name)) + 1;
273+ end;
274+ nv := nv + count[c];
275+ end;
276+ end;
277+ buf := Scan.grab(40 + 28 * np + 12 * nv + poolAt + lpLen);
278+ (* the pool of names starts at poolAt, the line table after it *)
279+ poolAt := 40 + 28 * np + 12 * nv;
280+ names := poolAt;
281+ at := 40;
282+ v := 0;
283+ for c := 0 to Chunk.numChunks - 1 do
284+ if isProc(c) then
285+ patch4(buf, at, Chunk.chunks[c].adr);
286+ patch4(buf, at + 4, Chunk.chunks[c].adr + Chunk.chunks[c].size);
287+ at := at + 8;
288+ putName(Chunk.chunkName(c));
289+ patch4(buf, at, v);
290+ patch4(buf, at + 4, count[c]);
291+ patch4(buf, at + 8, Chunk.chunks[c].saveMask);
292+ patch4(buf, at + 12, Chunk.chunks[c].saveAt);
293+ at := at + 16;
294+ v := v + count[c];
295+ end;
296+ end;
297+ for c := 0 to Chunk.numChunks - 1 do
298+ if isProc(c) then
299+ for v := first[c] to first[c] + count[c] - 1 do
300+ putName(Scan.nameOf(Chunk.varNotes[v].name));
301+ patch4(buf, at, Chunk.varNotes[v].off);
302+ patch4(buf, at + 4, Chunk.varNotes[v].kind);
303+ at := at + 8;
304+ end;
305+ end;
306+ end;
307+ linesOff := names;
308+ linesSize := lpLen;
309+ COPY(buf[names..names + lpLen], lp[0..lpLen]);
310+ patch8(buf, 0, linesOff);
311+ patch8(buf, 8, start);
312+ patch8(buf, 16, stop);
313+ patch8(buf, 24, np);
314+ patch8(buf, 32, nv);
315+ Chunk.setData(placesChunk, buf, names + lpLen, 8);
316+end;
317+
318+(* Places the live chunks, leaving roExtra bytes at the end of rodata
319+ and dynSize at the start of the writable segment. The segments follow
320+ each other in the file with no padding, and each is loaded a page
321+ further from its file offset than the one before: rodata at Base +
322+ Page + roOff, the writable segment at Base + 2 * Page + bssOff. So an
323+ address and its offset agree within a page, as the loader needs, and
324+ no two segments, with their different permissions, share a page.
325+ The bss of a program without the loader's table has no bytes in the
326+ file, and starts on a page of its own. *)
327+proc linkAll*(headerSize, roExtra, dynSize: INT);
328+var c, f, at, p, e, v: INT;
329+begin
330+ textOff := (headerSize + 31) div 32 * 32; (* as each code chunk is *)
331+ e := place(Chunk.secText, Base + textOff);
332+ textSize := e - (Base + textOff);
333+ if placesChunk >= 0 then makePlaces(Base + textOff, e); end;
334+ roOff := (textOff + textSize + 31) div 32 * 32;
335+ roAdr := Base + Page + roOff;
336+ e := place(Chunk.secRodata, roAdr);
337+ extraAdr := (e + 7) div 8 * 8;
338+ if roExtra > 0 then e := extraAdr + roExtra; end;
339+ roSize := e - roAdr;
340+ bssOff := (roOff + roSize + 31) div 32 * 32;
341+ if dynSize > 0 then
342+ bssAdr := Base + 2 * Page + bssOff;
343+ else
344+ bssAdr := (roAdr + roSize + Page - 1) div Page * Page;
345+ end;
346+ e := place(Chunk.secBss, bssAdr + dynSize);
347+ bssSize := e - bssAdr;
348+
349+ textImg := Scan.grab(textSize + 1);
350+ (* the gaps between code chunks are int3, a trap if ever run *)
351+ for p := 0 to textSize do textImg[p] := 0CCH; end;
352+ roImg := Scan.grab(roSize + 1);
353+ for p := 0 to roSize do roImg[p] := 0; end;
354+ for c := 0 to Chunk.numChunks - 1 do
355+ if Chunk.chunks[c].live then
356+ if Chunk.chunks[c].sec = Chunk.secText then
357+ p := Chunk.chunks[c].adr - (Base + textOff);
358+ COPY(textImg[p..p + Chunk.chunks[c].size], Chunk.text[Chunk.chunks[c].start..Chunk.chunks[c].start + Chunk.chunks[c].size]);
359+ for f := Chunk.chunks[c].firstFix to Chunk.chunks[c].firstFix + Chunk.chunks[c].numFix - 1 do
360+ at := Chunk.fixups[f].at - Chunk.chunks[c].start;
361+ (* rel32: from the end of the field to the target *)
362+ v := Chunk.chunks[Chunk.fixups[f].chunk].adr + Chunk.fixups[f].addend
363+ - (Chunk.chunks[c].adr + at + 4);
364+ patch4(textImg, p + at, v);
365+ end;
366+ elsif Chunk.chunks[c].sec = Chunk.secRodata then
367+ p := Chunk.chunks[c].adr - roAdr;
368+ COPY(roImg[p..p + Chunk.chunks[c].size], Chunk.rodata[Chunk.chunks[c].start..Chunk.chunks[c].start + Chunk.chunks[c].size]);
369+ for f := Chunk.chunks[c].firstFix to Chunk.chunks[c].firstFix + Chunk.chunks[c].numFix - 1 do
370+ patch8(roImg, p + Chunk.dataFixups[f].at,
371+ Chunk.chunks[Chunk.dataFixups[f].chunk].adr + Chunk.dataFixups[f].addend);
372+ end;
373+ end;
374+ end;
375+ end;
376+end;
377+
378+begin
379+ placesChunk := -1;
380+end Link.

src/Parse.raz (history) added +3775 -0

@@ -0,0 +1,3775 @@
1+(* Parse: the parser.
2+
3+ Reads modules by recursive descent and has Gen emit code as it goes:
4+ one pass, no tree. Importing a module that isn't compiled yet
5+ compiles it there and then, so modules are finished in an order where
6+ each comes after the modules it imports; that is the order in which
7+ their bodies run.
8+
9+ A module may come in one file per target (Name.linux-x86_64.raz and
10+ so on). The file for this target is compiled; the others beside it
11+ are read for their declarations only, and must export the same
12+ interface.
13+
14+ Depends on: Scan, Sym, Chunk for data, Item and Gen for code.
15+ Leaves out: linking; a module only records the libraries it names,
16+ and whether it uses C or says link static.
17+
18+ The seed's errors ended in a jump back to the statement or
19+ declaration being read (Scan.mark, longjmp). Here every routine that
20+ can find an error returns an ERROR as its last result, and the ones
21+ that call it pass it up with try, as Item does; the statement or
22+ declaration that is a recovery point (guard) looks at what comes back
23+ and reads on. What has been made by then is what the seed had made
24+ when it jumped. A seed `var` that only gave a value back is a result
25+ where that is shorter; the others stay as they were. A set of
26+ Scan.Sym is a chain of tests, since it has more names than a set
27+ holds. *)
28+module Parse;
29+import Fmt, Diag, Scan, Sym, Chunk, Gen, Item, Sys, Str, Buf, Heap;
30+
31+type
32+ PType = ^Sym.Type;
33+ PObj = ^Sym.Obj;
34+ PModule = ^Sym.Module;
35+ TItem = Item.Item;
36+
37+ (* The innermost loop: the chain of its breaks and the deferred
38+ statements in force outside it *)
39+ Loop = record
40+ brk: INT;
41+ base: INT;
42+ end;
43+ PLoop = ^Loop;
44+
45+ (* A generic module's import whose instance isn't made yet (deferred,
46+ numDeferred); not to be confused with a defer statement (defers) *)
47+ Deferred = record
48+ o: PObj; (* the name it imports as *)
49+ home: PModule; (* the module that imports it *)
50+ mname: INT; (* the generic module *)
51+ args: Scan.State; (* at the "(" of its arguments *)
52+ at: Diag.Pos; (* the import *)
53+ end;
54+
55+const
56+ (* Whether the target has reals (report, appendix A): x86-64 always has
57+ SSE2. Without them, used code that computes with one is an error,
58+ which Raz reports once it knows what the program uses. *)
59+ HasReals* = true;
60+
61+ MaxNames = 64; (* names in one declaration, and the like *)
62+ MaxFwd = 256; (* pointers to types not yet declared *)
63+ MaxDefers = 64; (* defer statements in force *)
64+ MaxDrops = 4096; (* calls that drop results, in one module *)
65+ MaxDeferred = 64; (* generic imports not yet made *)
66+ MaxLabels = 1024; (* labels of one match *)
67+ MaxElements = 1024; (* elements of an array literal *)
68+ MaxFixes = 4096; (* addresses in one constant *)
69+ MaxPending = 64; (* modules being compiled at once *)
70+ Suffixes: [4][]U8 = [".linux-x86_64", ".linux", ".x86_64", ""];
71+
72+var
73+ libDir*, mainDir: []U8;
74+ incDirs*: [16][]U8;
75+ numInc*: INT;
76+ firstModule*, lastModule*: PModule; (* in the order they were finished *)
77+
78+ checkMode: BOOL; (* reading a file only for its interface *)
79+ inTypes: BOOL; (* in a type section: ^T may name a later type *)
80+ fwdTypes: [MaxFwd]PType;
81+ fwdPos: [MaxFwd]Diag.Pos; (* where each names its type *)
82+ numFwd: INT;
83+ lastCalled: PObj; (* the procedure the last call was of, if it had a name *)
84+ passOn: BOOL; (* the next factor may be a call with several results, for return *)
85+ curProc: PObj; (* the procedure being compiled, or nil *)
86+ declExported: BOOL; (* the export mark of the declaration being read *)
87+ curLoop: PLoop; (* the innermost loop, or nil *)
88+ defers: [MaxDefers]INT; (* the defer statements in force, their code's addresses *)
89+ numDefers: INT;
90+ deferring: BOOL; (* compiling a defer statement's statement *)
91+ directDefer: BOOL; (* ... as the statement itself, not in a list *)
92+ deferSlot: I64; (* keeps a result while deferred statements run *)
93+ curResult: PType; (* the result type of the procedure being compiled *)
94+ inExtern: BOOL; (* reading an extern's signature: ... allowed *)
95+ tArgv, tBodySig: PType;
96+ nameRt, nameFail, nameBody, nameStatic, nameCheck, nameOff, nameAdr: INT;
97+ declaring: [MaxNames]INT; (* the names the declaration being read declares *)
98+ numDeclaring: INT;
99+ skipped: BOOL; (* the last statement had an error and was skipped *)
100+ deferred: [MaxDeferred]Deferred; (* generic imports not yet made, not defer statements *)
101+ numDeferred: INT;
102+ making: BOOL; (* reading an instance's arguments, at its first use *)
103+ stray: BOOL; (* an "end" in this procedure stood left of its statement's line *)
104+ strayAt: Diag.Pos; (* ... the first such statement *)
105+ elseIf: BOOL; (* an "else if" in this procedure *)
106+ drops: [MaxDrops]record
107+ at: Diag.Pos; (* a call standing on its own that drops results *)
108+ n: INT; (* ... how many *)
109+ end;
110+ numDrops: INT; (* the module being compiled has those from its
111+ first one, saved by compileFile, to here *)
112+ ends: BOOL; (* the statements just read never go on past
113+ their end: each way through them returns *)
114+ useAt: Diag.Pos; (* ... which is here *)
115+ guards: INT; (* the recovery points open *)
116+
117+proc expression(var x: TItem; want: PType): ERROR; forward;
118+proc parseType: (PType, ERROR); forward;
119+proc statements: ERROR; forward;
120+proc statement: ERROR; forward;
121+
122+(* Little helpers *)
123+
124+proc setLibDir*(dir: []U8);
125+begin
126+ libDir := dir;
127+end;
128+
129+proc addIncDir*(dir: []U8);
130+begin
131+ incDirs[numInc] := dir;
132+ INC(numInc);
133+end;
134+
135+proc nameOf(n: INT): []U8;
136+begin
137+ return Scan.nameOf(n);
138+end;
139+
140+(* The name number of s, which isn't empty *)
141+proc internName(s: []U8): INT;
142+begin
143+ return Scan.intern(ADR(s[0]), LEN(s));
144+end;
145+
146+proc say1(f, a: []U8): []U8;
147+begin
148+ return Diag.say(f, [Fmt.str(a)]);
149+end;
150+
151+proc say2(f, a, b: []U8): []U8;
152+begin
153+ return Diag.say(f, [Fmt.str(a), Fmt.str(b)]);
154+end;
155+
156+proc say3(f, a, b, c: []U8): []U8;
157+begin
158+ return Diag.say(f, [Fmt.str(a), Fmt.str(b), Fmt.str(c)]);
159+end;
160+
161+(* More than n of what, as a message *)
162+proc tooMany(n: INT; what: []U8): []U8;
163+begin
164+ return Diag.say("more than {} {}", [Fmt.int(n), Fmt.str(what)]);
165+end;
166+
167+(* A missing symbol is reported just after the one before it. *)
168+proc expected(what: []U8): ERROR;
169+begin
170+ if Scan.tok = Scan.sBlank then
171+ return Scan.mark("_ isn't a name: it is the blank, which stands only left of :=");
172+ end;
173+ return Scan.markAt(Scan.missingPos(), say2("expected {}, found {}", what, Scan.found()));
174+end;
175+
176+proc expect(s: Scan.Sym): ERROR;
177+begin
178+ if (Scan.tok = Scan.sLbrace) and ((s = Scan.sThen) or (s = Scan.sDo)) then
179+ return Scan.markHelp(Scan.missingPos(), say2("expected {}, found {}", Scan.symText(s), Scan.found()),
180+ say1("a block is written {} ... end", Scan.symText(s)));
181+ end;
182+ if Scan.tok # s then return expected(Scan.symText(s)); end;
183+ Scan.next;
184+ return nil;
185+end;
186+
187+(* The end of a block statement at start, whose line is indented to
188+ ind. An "end" left of that was most likely meant for a block around
189+ the statement, which leaves the statement's own "end" missing: the
190+ first such is kept for endMissing. *)
191+proc closeEnd(start: Diag.Pos; ind: INT): ERROR;
192+begin
193+ if (Scan.tok = Scan.sEnd) and not stray and (Scan.indent() < ind) then
194+ stray := true;
195+ strayAt := start;
196+ end;
197+ return expect(Scan.sEnd);
198+end;
199+
200+(* The error of a procedure or module whose own "end" isn't where it
201+ should be, with what closeEnd saw *)
202+proc endMissing(p: Diag.Pos; msg: []U8): ERROR;
203+begin
204+ Diag.error(p, msg);
205+ if stray then Diag.note(strayAt, "is this statement's \"end\" missing? one further left closes it"); end;
206+ if elseIf then Diag.help("raz writes elsif: \"else if\" begins an if that needs its own \"end\""); end;
207+ return Scan.Failed;
208+end;
209+
210+(* A name being declared, and whether it is exported; at is the name *)
211+proc identDef(var n: INT; var exp: BOOL; var at: Diag.Pos): ERROR;
212+begin
213+ if Scan.tok # Scan.sIdent then return expected("a name"); end;
214+ n := Scan.id;
215+ at := Scan.tokPos();
216+ Scan.next;
217+ exp := false;
218+ if Scan.tok = Scan.sTimes then
219+ exp := true;
220+ Scan.next;
221+ end;
222+ return nil;
223+end;
224+
225+(* Declares o in the innermost scope. Its module keeps its declarations
226+ in order: its own, for the interface check, and its procedures', to
227+ warn of those never used. *)
228+proc declare(o: PObj): ERROR;
229+var m: PModule;
230+begin
231+ m := Sym.curModule;
232+ try Sym.insert(o, Sym.topScope());
233+ if Sym.topScope() = m^.scope then
234+ if m^.last = nil then m^.first := o; else m^.last^.chain := o; end;
235+ m^.last := o;
236+ else
237+ if m^.lastLocal = nil then m^.locals := o; else m^.lastLocal^.chain := o; end;
238+ m^.lastLocal := o;
239+ end;
240+ return nil;
241+end;
242+
243+(* o is named: a procedure naming itself doesn't count *)
244+proc named(o: PObj);
245+begin
246+ if o # curProc then
247+ o^.used := true;
248+ o^.read := true;
249+ end;
250+end;
251+
252+(* Recovery
253+
254+ After an error the parser goes on with the next statement or
255+ declaration, so that one run reports every error. Each statement and
256+ declaration is a recovery point: it notes the state of the scanner
257+ and the parser where it starts, and when what it read comes back with
258+ an error, the state is put back, the scanner reads the construct
259+ again from its start, skipping to its end, and the parser carries on
260+ after it. Nothing is generated after an error, so the code half made
261+ for the construct does no harm. A name that isn't declared is
262+ declared where it is used, with type tPoison, and what follows from
263+ it is not reported again; so are the names of a declaration that had
264+ an error.
265+
266+ Skipping counts the words that open and close blocks. A symbol at
267+ the start of a line is taken to start a declaration of the module,
268+ as layout has it: a statement skipped up to one gives up its
269+ procedure, and the procedure is skipped up to its end. *)
270+
271+type
272+ Recover = record
273+ scan: Scan.State;
274+ scopes, depth, pushed, numDefers: INT;
275+ guards: INT;
276+ loop: PLoop;
277+ result: PType;
278+ deferring, directDefer, quiet: BOOL;
279+ end;
280+
281+proc guard(var r: Recover);
282+begin
283+ Scan.saveScan(r.scan);
284+ r.guards := guards;
285+ r.scopes := Sym.scopeDepth(); r.depth := Gen.depth; r.pushed := Gen.pushed; r.numDefers := numDefers;
286+ r.loop := curLoop; r.result := curResult;
287+ r.deferring := deferring; r.directDefer := directDefer; r.quiet := Diag.quiet;
288+ INC(guards);
289+ Diag.setQuiet(false);
290+end;
291+
292+proc unguard(var r: Recover);
293+begin
294+ guards := r.guards;
295+ Diag.setQuiet(r.quiet);
296+ Scan.setSkipping(false);
297+end;
298+
299+(* After an error: the state as it was at the start of r's construct,
300+ whose first symbol is again the current one *)
301+proc restore(var r: Recover);
302+begin
303+ Scan.restoreScan(r.scan);
304+ Scan.setSkipping(true);
305+ Sym.cutScopes(r.scopes);
306+ Gen.resetStack(r.depth, r.pushed);
307+ numDefers := r.numDefers;
308+ curLoop := r.loop; curResult := r.result;
309+ deferring := r.deferring; directDefer := r.directDefer;
310+ inTypes := false; declExported := false; inExtern := false; making := false;
311+end;
312+
313+(* Gives up the construct r is for, and the one around it: the error
314+ goes on up to the next recovery point, or ends the compile if there
315+ is none *)
316+proc giveUp(var r: Recover): ERROR;
317+begin
318+ unguard(r);
319+ if guards = 0 then Diag.finish(); end;
320+ return Scan.Failed;
321+end;
322+
323+(* Reads to the end of a statement or declaration, from its first
324+ symbol: up to the ";" that ends it, not read, or to the "end",
325+ "else", "elsif", "until" or "|" of the statement around it (an arm's
326+ "|" comes after a ";", the operator's after an operand). False if it
327+ stopped at a symbol that starts a line, or the end of the file. *)
328+proc skipConstruct: BOOL;
329+var d, p: INT; prev: Scan.Sym;
330+begin
331+ d := 0; p := 0; prev := Scan.sSemicolon;
332+ repeat
333+ match Scan.tok of
334+ | sIf, sWhile, sFor, sMatch, sRepeat, sRecord, sVariant: INC(d);
335+ | sEnd, sUntil:
336+ if d = 0 then return true; end;
337+ DEC(d);
338+ | sElse, sElsif: if (d = 0) and (p = 0) then return true; end;
339+ | sBar: if (d = 0) and (p = 0) and (prev = Scan.sSemicolon) then return true; end;
340+ | sLparen, sLbrak, sLbrace: INC(p);
341+ | sRparen, sRbrak, sRbrace: if p > 0 then DEC(p); end;
342+ | sSemicolon: if (d = 0) and (p = 0) then return true; end;
343+ | sEof: return false;
344+ | else:
345+ end;
346+ prev := Scan.tok;
347+ Scan.next;
348+ until Scan.atLineStart();
349+ return false;
350+end;
351+
352+(* Declares n where it is used, after it was reported as not declared,
353+ or after the declaration of it had an error *)
354+proc poison(n: INT);
355+var o: PObj;
356+begin
357+ o := Sym.newObj(Sym.oConst, n, Sym.tPoison);
358+ _ := Sym.insert(o, Sym.topScope()); (* n isn't in this scope, so it can't be twice *)
359+end;
360+
361+proc willDeclare(n: INT);
362+begin
363+ if numDeclaring < MaxNames then declaring[numDeclaring] := n; end;
364+ INC(numDeclaring);
365+end;
366+
367+(* After a declaration had an error: its names are poison, and reading
368+ goes on after it *)
369+proc skipDeclaration;
370+var i: INT;
371+begin
372+ for i := 0 to numDeclaring - 1 do
373+ if (i < MaxNames) and (Sym.find(Sym.topScope(), declaring[i]) = nil) then
374+ poison(declaring[i]);
375+ end;
376+ end;
377+ if skipConstruct() and (Scan.tok = Scan.sSemicolon) then Scan.next; end;
378+end;
379+
380+proc constValue(var x: TItem): (I64, ERROR);
381+begin
382+ if x.mode # Item.mConst then return 0, Scan.markAt(x.pos, "expected a constant"); end;
383+ return x.val, nil;
384+end;
385+
386+proc constExpr: (I64, ERROR);
387+var x: TItem;
388+begin
389+ try expression(x, nil);
390+ if not Sym.isInt(x.typ) then
391+ return 0, Scan.markAt(x.pos, say1("expected an integer constant, found {}", Item.what(x)));
392+ end;
393+ return constValue(x);
394+end;
395+
396+(* Help after a name that isn't found: o, the closest name in reach *)
397+proc didYouMean(o: PObj);
398+begin
399+ if o # nil then Diag.help(say1("did you mean {}?", nameOf(o^.name))); end;
400+end;
401+
402+(* Where module n is found, if it is: dir and the file in it *)
403+proc moduleFile(n: INT): ([]U8, []U8, BOOL); forward;
404+
405+(* name in lower case, in memory that is never freed, as messages are *)
406+proc lowerCase(s: []U8): []U8;
407+var p: ^U8; i: INT;
408+begin
409+ if LEN(s) = 0 then return ""; end;
410+ p := Scan.grab(LEN(s));
411+ for i := 0 to LEN(s) - 1 do
412+ if (s[i] >= 'A') and (s[i] <= 'Z') then p[i] := s[i] + 32; else p[i] := s[i]; end;
413+ end;
414+ return p[0..LEN(s)];
415+end;
416+
417+(* Reports name n at p as not declared, with what it may have meant *)
418+proc notDeclared(p: Diag.Pos; n: INT);
419+var found: BOOL; low: []U8;
420+begin
421+ Diag.error(p, say1("{} isn't declared", nameOf(n)));
422+ _, _, found := moduleFile(n);
423+ low := lowerCase(nameOf(n));
424+ if found then Diag.help(say2("{} is a module: import {}", nameOf(n), nameOf(n)));
425+ elsif (nameOf(n) = "elif") or (nameOf(n) = "elseif") then Diag.help("raz writes elsif");
426+ elsif Scan.reserved(internName(low)) then Diag.help(say1("a reserved word is written in lower case: {}", low));
427+ else didYouMean(Sym.closest(n, -1));
428+ end;
429+end;
430+
431+proc firstUse(o: PObj; at: Diag.Pos): ERROR; forward;
432+proc instancesFor(wholeRest: BOOL): ERROR; forward;
433+proc addImport(m, im: PModule); forward;
434+
435+proc qualIdent: (PObj, ERROR);
436+var o: PObj; m: PModule; at: Diag.Pos;
437+begin
438+ if Scan.tok # Scan.sIdent then return nil, expected("a name"); end;
439+ at := Scan.tokPos();
440+ o := Sym.lookup(Scan.id);
441+ if o = nil then
442+ if not making then poison(Scan.id); end; (* it may yet be declared *)
443+ Diag.setQuiet(false);
444+ notDeclared(at, Scan.id);
445+ if making then Diag.note(useAt, "the instance is made here, where it is first used"); end;
446+ return nil, Scan.Failed;
447+ end;
448+ if o^.typ = Sym.tPoison then Diag.setQuiet(true); end;
449+ named(o);
450+ Scan.next;
451+ if o^.cls = Sym.oModule then
452+ if o^.home = nil then try firstUse(o, at); end;
453+ try expect(Scan.sPeriod);
454+ if Scan.tok # Scan.sIdent then return nil, expected("a name"); end;
455+ m := o^.home;
456+ o := Sym.find(m^.scope, Scan.id);
457+ if (o = nil) or not o^.exported then
458+ Diag.error(Scan.tokPos(), say2("{} isn't exported by {}", nameOf(Scan.id), nameOf(m^.name)));
459+ if o # nil then Diag.note(o^.pos, say1("{} is declared here, without a *", nameOf(Scan.id)));
460+ else didYouMean(Sym.closest(Scan.id, m^.scope));
461+ end;
462+ return nil, Scan.Failed;
463+ end;
464+ Scan.next;
465+ end;
466+ return o, nil;
467+end;
468+
469+(* The field of record type t named by the current symbol *)
470+proc fieldOf(t: PType): (PObj, ERROR);
471+var f: PObj;
472+begin
473+ f := Sym.find(t^.scope, Scan.id);
474+ if f = nil then
475+ Diag.error(Scan.tokPos(), say2("{} has no field {}", Sym.typeName(t), nameOf(Scan.id)));
476+ didYouMean(Sym.closest(Scan.id, t^.scope));
477+ return nil, Scan.Failed;
478+ end;
479+ if not f^.exported and (t^.home # Sym.curModule) then
480+ Diag.error(Scan.tokPos(), say2("field {} of {} isn't exported", nameOf(Scan.id), Sym.typeName(t)));
481+ Diag.note(f^.pos, say1("{} is declared here, without a *", nameOf(Scan.id)));
482+ return nil, Scan.Failed;
483+ end;
484+ return f, nil;
485+end;
486+
487+proc newPtr(base: PType; vol: BOOL): PType;
488+var t: PType;
489+begin
490+ t := Sym.newType(Sym.fPtr, 8, 8);
491+ t^.base := base;
492+ t^.vol := vol;
493+ return t;
494+end;
495+
496+(* Types *)
497+
498+proc recordType: (PType, ERROR);
499+var
500+ t, ft: PType; f, last: PObj; names: [MaxNames]INT;
501+ exps: [MaxNames]BOOL; poss: [MaxNames]Diag.Pos;
502+ n, i: INT; off, a, maxA: I64;
503+begin
504+ t := Sym.newType(Sym.fRecord, 0, 1);
505+ if Scan.tok = Scan.sPacked then t^.packd := true; Scan.next; end;
506+ try expect(Scan.sRecord);
507+ t^.scope := Sym.newScope();
508+ off := 0; maxA := 1; last := nil;
509+ while Scan.tok = Scan.sIdent do
510+ n := 0;
511+ repeat
512+ if n >= MaxNames then return nil, Scan.mark(tooMany(MaxNames, "names in one declaration")); end;
513+ try identDef(names[n], exps[n], poss[n]);
514+ INC(n);
515+ if Scan.tok # Scan.sComma then break; end;
516+ Scan.next;
517+ until false;
518+ try expect(Scan.sColon);
519+ ft := try parseType();
520+ if t^.packd then a := 1; else a := ft^.align; end;
521+ for i := 0 to n - 1 do
522+ off := Sym.alignUp(off, a);
523+ f := Sym.newObj(Sym.oField, names[i], ft);
524+ f^.exported := exps[i];
525+ f^.pos := poss[i];
526+ f^.val := off;
527+ try Sym.insert(f, t^.scope);
528+ if last = nil then t^.fields := f; else last^.next := f; end;
529+ last := f;
530+ off := off + ft^.size;
531+ end;
532+ if a > maxA then maxA := a; end;
533+ try expect(Scan.sSemicolon);
534+ end;
535+ try expect(Scan.sEnd);
536+ t^.align := maxA;
537+ t^.size := Sym.alignUp(off, maxA);
538+ return t, nil;
539+end;
540+
541+proc variantType: (PType, ERROR);
542+var t, ft: PType; c, lastC, f, lastF: PObj; tag, off, maxSize: I64;
543+begin
544+ try expect(Scan.sVariant);
545+ t := Sym.newType(Sym.fVariant, 8, 8);
546+ tag := 0; maxSize := 8; lastC := nil;
547+ while Scan.tok = Scan.sIdent do
548+ c := Sym.newObj(Sym.oCase, Scan.id, t);
549+ c^.val := tag;
550+ c^.exported := declExported;
551+ try declare(c);
552+ if lastC = nil then t^.fields := c; else lastC^.next := c; end;
553+ lastC := c;
554+ Scan.next;
555+ off := 8;
556+ if Scan.tok = Scan.sLparen then
557+ Scan.next;
558+ lastF := nil;
559+ repeat
560+ repeat
561+ if Scan.tok # Scan.sIdent then return nil, expected("a name"); end;
562+ f := Sym.newObj(Sym.oField, Scan.id, nil);
563+ f^.exported := true;
564+ if lastF = nil then c^.fields := f; else lastF^.next := f; end;
565+ lastF := f;
566+ Scan.next;
567+ if Scan.tok # Scan.sComma then break; end;
568+ Scan.next;
569+ until false;
570+ try expect(Scan.sColon);
571+ ft := try parseType();
572+ f := c^.fields;
573+ while f^.typ # nil do f := f^.next; end;
574+ while f # nil do
575+ f^.typ := ft;
576+ off := Sym.alignUp(off, ft^.align);
577+ f^.val := off;
578+ off := off + ft^.size;
579+ f := f^.next;
580+ end;
581+ if ft^.align > t^.align then t^.align := ft^.align; end;
582+ if Scan.tok # Scan.sSemicolon then break; end;
583+ Scan.next;
584+ until false;
585+ try expect(Scan.sRparen);
586+ end;
587+ if off > maxSize then maxSize := off; end;
588+ try expect(Scan.sSemicolon);
589+ INC(tag);
590+ end;
591+ try expect(Scan.sEnd);
592+ t^.len := tag;
593+ t^.size := Sym.alignUp(maxSize, t^.align);
594+ return t, nil;
595+end;
596+
597+(* Several results: a record of them, laid out as C would, and
598+ returned in rax and rdx if they are two words (inTwoRegs), or else
599+ through a hidden pointer. *)
600+proc results: (PType, ERROR);
601+var t, ft: PType; f, last: PObj; off: I64;
602+begin
603+ Scan.next;
604+ t := Sym.newType(Sym.fRecord, 0, 1);
605+ t^.tuple := true;
606+ off := 0; last := nil;
607+ repeat
608+ ft := try parseType();
609+ off := Sym.alignUp(off, ft^.align);
610+ f := Sym.newObj(Sym.oField, -1, ft);
611+ f^.val := off;
612+ off := off + ft^.size;
613+ if ft^.align > t^.align then t^.align := ft^.align; end;
614+ if last = nil then t^.fields := f; else last^.next := f; end;
615+ last := f;
616+ INC(t^.len);
617+ if Scan.tok # Scan.sComma then break; end;
618+ Scan.next;
619+ until false;
620+ try expect(Scan.sRparen);
621+ t^.size := Sym.alignUp(off, t^.align);
622+ if t^.len = 1 then return t^.fields^.typ, nil; end;
623+ return t, nil;
624+end;
625+
626+proc signature: (PType, ERROR);
627+var
628+ t, pt: PType; p, first, last: PObj; isVar: BOOL; n: INT;
629+begin
630+ t := Sym.newType(Sym.fProc, 8, 8);
631+ last := nil; n := 0;
632+ if Scan.tok = Scan.sLparen then
633+ Scan.next;
634+ if Scan.tok # Scan.sRparen then
635+ repeat
636+ if Scan.tok = Scan.sEllipsis then
637+ if not inExtern then return nil, Scan.mark("... is only for extern procedures"); end;
638+ Scan.next; t^.variadic := true; break;
639+ end;
640+ isVar := Scan.tok = Scan.sVar;
641+ if isVar then Scan.next; end;
642+ first := nil;
643+ repeat
644+ if Scan.tok # Scan.sIdent then return nil, expected("a name"); end;
645+ p := Sym.newObj(Sym.oVar, Scan.id, nil);
646+ p^.isVar := isVar;
647+ p^.lev := 1;
648+ if last = nil then t^.fields := p; else last^.next := p; end;
649+ last := p;
650+ if first = nil then first := p; end;
651+ INC(n);
652+ Scan.next;
653+ if Scan.tok # Scan.sComma then break; end;
654+ Scan.next;
655+ until false;
656+ try expect(Scan.sColon);
657+ pt := try parseType();
658+ while first # nil do first^.typ := pt; first := first^.next; end;
659+ if Scan.tok # Scan.sSemicolon then break; end;
660+ Scan.next;
661+ until false;
662+ end;
663+ try expect(Scan.sRparen);
664+ end;
665+ t^.len := n;
666+ if Scan.tok = Scan.sColon then
667+ Scan.next;
668+ if Scan.tok = Scan.sLparen then t^.base := try results(); else t^.base := try parseType(); end;
669+ end;
670+ return t, nil;
671+end;
672+
673+proc enumType: (PType, ERROR);
674+var t: PType; o, last: PObj; start: Diag.Pos;
675+begin
676+ start := Scan.tokPos();
677+ t := Sym.newType(Sym.fEnum, 1, 1);
678+ last := nil;
679+ repeat
680+ Scan.next;
681+ if Scan.tok # Scan.sIdent then return nil, expected("a name"); end;
682+ o := Sym.newObj(Sym.oConst, Scan.id, t);
683+ o^.val := t^.len;
684+ o^.exported := declExported;
685+ o^.used := true; (* an enumeration's names are its type's, warned of with it *)
686+ try declare(o);
687+ if last = nil then t^.fields := o; else last^.next := o; end;
688+ last := o;
689+ INC(t^.len);
690+ Scan.next;
691+ until Scan.tok # Scan.sComma;
692+ try expect(Scan.sRparen);
693+ if t^.len > 256 then return nil, Scan.markAt(Scan.spanFrom(start), "an enumeration has at most 256 names"); end;
694+ return t, nil;
695+end;
696+
697+proc setOf(e: PType; at: Diag.Pos): (PType, ERROR);
698+var t: PType;
699+begin
700+ if (e^.form # Sym.fEnum) or (e^.len > 64) then
701+ return nil, Scan.markAt(at, say1("a set needs an enumeration of at most 64 names, found {}", Sym.typeName(e)));
702+ end;
703+ t := Sym.newType(Sym.fSet, 8, 8);
704+ if e^.len <= 8 then t^.size := 1;
705+ elsif e^.len <= 16 then t^.size := 2;
706+ elsif e^.len <= 32 then t^.size := 4;
707+ end;
708+ t^.align := t^.size;
709+ t^.base := e;
710+ t^.len := e^.len;
711+ return t, nil;
712+end;
713+
714+proc parseType: (PType, ERROR);
715+var t: PType; o: PObj; n: I64; vol: BOOL; start: Diag.Pos;
716+begin
717+ start := Scan.tokPos();
718+ match Scan.tok of
719+ | sIdent:
720+ o := try qualIdent();
721+ if o^.cls # Sym.oType then
722+ return nil, Scan.markAt(Scan.spanFrom(start), say1("{} isn't a type", nameOf(o^.name)));
723+ end;
724+ t := o^.typ;
725+ | sLbrak:
726+ Scan.next;
727+ if Scan.tok = Scan.sRbrak then
728+ Scan.next;
729+ t := Sym.newType(Sym.fSlice, 16, 8);
730+ t^.base := try parseType();
731+ else
732+ start := Scan.tokPos();
733+ n := try constExpr();
734+ if (n <= 0) or (n > (I64(1) shl 40)) then
735+ return nil, Scan.markAt(Scan.spanFrom(start), Diag.say("an array's length is from 1 to 2^40, found {}", [Fmt.int(n)]));
736+ end;
737+ try expect(Scan.sRbrak);
738+ t := Sym.newType(Sym.fArray, 0, 1);
739+ t^.len := n;
740+ t^.base := try parseType();
741+ t^.size := n * t^.base^.size;
742+ t^.align := t^.base^.align;
743+ end;
744+ | sArrow:
745+ Scan.next;
746+ vol := Scan.tok = Scan.sVolatile;
747+ if vol then Scan.next; end;
748+ if inTypes and (Scan.tok = Scan.sIdent) and (Sym.lookup(Scan.id) = nil) then
749+ (* a type declared later in this section *)
750+ t := newPtr(nil, vol);
751+ t^.fwd := Scan.id;
752+ if numFwd >= MaxFwd then
753+ return nil, Scan.mark(tooMany(MaxFwd, "pointers to types not yet declared"));
754+ end;
755+ fwdTypes[numFwd] := t;
756+ fwdPos[numFwd] := Scan.tokPos();
757+ INC(numFwd);
758+ Scan.next;
759+ else
760+ t := newPtr(try parseType(), vol);
761+ end;
762+ | sPacked, sRecord: t := try recordType();
763+ | sVariant: t := try variantType();
764+ | sProc: Scan.next; t := try signature();
765+ | sLparen: t := try enumType();
766+ | sSet:
767+ Scan.next;
768+ try expect(Scan.sOf);
769+ start := Scan.tokPos();
770+ t := try setOf(try parseType(), start);
771+ | else: return nil, expected("a type");
772+ end;
773+ return t, nil;
774+end;
775+
776+(* Expressions *)
777+
778+proc call(var x: TItem): ERROR;
779+var c: Gen.CallInfo; a: TItem; want: PType;
780+begin
781+ try Item.beginCall(c, x);
782+ try expect(Scan.sLparen);
783+ if Scan.tok # Scan.sRparen then
784+ repeat
785+ if c.param # nil then want := c.param^.typ; else want := nil; end;
786+ try expression(a, want);
787+ try Item.passArg(c, a);
788+ if Scan.tok # Scan.sComma then break; end;
789+ Scan.next;
790+ until false;
791+ end;
792+ try expect(Scan.sRparen);
793+ return Item.endCall(c, x);
794+end;
795+
796+proc atomic(var x: TItem; which: INT): ERROR;
797+var p, a: TItem; t: PType; i, n: INT;
798+begin
799+ try expression(p, nil);
800+ if p.typ^.form # Sym.fPtr then
801+ return Scan.markAt(p.pos, say1("expected a pointer, found {}", Item.what(p)));
802+ end;
803+ t := p.typ^.base;
804+ if not (Item.isWord(t) or ((t^.form = Sym.fPtr) and (which # Sym.bXadd))) then
805+ if which = Sym.bXadd then
806+ return Scan.markAt(p.pos, say1("expected a pointer to an INT or a UINT, found {}", Sym.typeName(p.typ)));
807+ end;
808+ return Scan.markAt(p.pos, say1("expected a pointer to an INT, a UINT or a pointer, found {}", Sym.typeName(p.typ)));
809+ end;
810+ try Item.value(p);
811+ if which = Sym.bCas then n := 2; else n := 1; end;
812+ for i := 1 to n do
813+ try expect(Scan.sComma);
814+ try expression(a, t);
815+ try Item.coerce(a, t);
816+ try Item.value(a);
817+ end;
818+ Gen.atomic(which);
819+ Item.makeConst(x, t, 0);
820+ if which = Sym.bCas then x.typ := Sym.tBool; end;
821+ x.mode := Item.mStack;
822+ return nil;
823+end;
824+
825+(* NEW(p, a): p := a^.alloc(a, SIZE(T), alignment), zeroed if not nil.
826+ a is a ^Mem.Allocator, the one interface the compiler knows. *)
827+proc new_(var x: TItem): ERROR;
828+var y, z: TItem; t: PType; f: PObj; s: I64; c: Gen.CallInfo;
829+begin
830+ try expression(x, nil);
831+ try Item.notReadOnly(x);
832+ if (x.mode # Item.mVar) or not x.isVar or (x.typ^.form # Sym.fPtr) then
833+ return Scan.markAt(x.pos, "NEW needs a pointer variable");
834+ end;
835+ t := x.typ^.base;
836+ try expect(Scan.sComma);
837+ try expression(y, nil);
838+ if (y.typ^.form # Sym.fPtr) or (y.typ^.base^.obj = nil) or (y.typ^.base^.obj^.home = nil)
839+ or (nameOf(y.typ^.base^.obj^.name) # "Allocator")
840+ or (nameOf(y.typ^.base^.obj^.home^.name) # "Mem") then
841+ return Scan.markAt(y.pos, say1("NEW needs a ^Mem.Allocator, found {}", Item.what(y)));
842+ end;
843+ f := Sym.find(y.typ^.base^.scope, internName("alloc"));
844+ s := try Item.toSlot(y);
845+ Gen.pushVar(Item.frameAdr(s), 8, false, Gen.kWord);
846+ Item.makeConst(z, f^.typ, 0);
847+ z.mode := Item.mVar; z.base := Gen.bStack; z.off := f^.val;
848+ try Item.beginCall(c, z);
849+ Gen.pushVar(Item.frameAdr(s), 8, false, Gen.kWord);
850+ Item.makeConst(z, y.typ, 0);
851+ z.mode := Item.mStack;
852+ try Item.passArg(c, z);
853+ Item.makeConst(z, Sym.tInt, t^.size);
854+ try Item.passArg(c, z);
855+ Item.makeConst(z, Sym.tInt, t^.align);
856+ try Item.passArg(c, z);
857+ try Item.endCall(c, z);
858+ Gen.zeroNew(t^.size);
859+ z.typ := x.typ;
860+ try Item.assign(x, z);
861+ Item.makeConst(x, Sym.tNone, 0);
862+ x.mode := Item.mNone;
863+ return nil;
864+end;
865+
866+proc incOrDec(which: INT): []U8;
867+begin
868+ if which = Sym.bDec then return "DEC"; end;
869+ return "INC";
870+end;
871+
872+proc builtin(var x: TItem): ERROR;
873+var which, n: INT; y: TItem; t: PType;
874+begin
875+ which := INT(x.obj^.val);
876+ if (which = Sym.bFence) or (which = Sym.bArgc) or (which = Sym.bArgv) then
877+ if Scan.tok = Scan.sLparen then Scan.next; try expect(Scan.sRparen); end;
878+ Item.makeConst(x, Sym.tNone, 0);
879+ match which of
880+ | Sym.bFence: Gen.fence(); x.mode := Item.mNone;
881+ | Sym.bArgc:
882+ Gen.pushVar(Item.globalAdr(Gen.argcChunk), 8, false, Gen.kWord);
883+ x.typ := Sym.tInt; x.mode := Item.mStack;
884+ | else:
885+ Gen.pushVar(Item.globalAdr(Gen.argvChunk), 8, false, Gen.kWord);
886+ x.typ := tArgv; x.mode := Item.mStack;
887+ end;
888+ return nil;
889+ end;
890+ try expect(Scan.sLparen);
891+ match which of
892+ | Sym.bSize:
893+ t := try parseType();
894+ Item.makeConst(x, Sym.tConst, t^.size);
895+ | Sym.bAdr:
896+ try expression(y, nil);
897+ try Item.notReadOnly(y);
898+ if (y.mode # Item.mVar) or not y.isVar then return Scan.markAt(y.pos, "ADR needs a variable"); end;
899+ if y.odd then return Scan.markAt(y.pos, "a field of a packed record has no address"); end;
900+ t := newPtr(y.typ, y.vol);
901+ try Item.address(y);
902+ Item.makeConst(x, t, 0);
903+ x.mode := Item.mStack;
904+ | Sym.bLen:
905+ try expression(y, nil);
906+ if y.mode = Item.mStr then
907+ Item.makeConst(x, Sym.tConst, y.val);
908+ elsif y.typ^.form = Sym.fArray then
909+ try Item.discard(y);
910+ Item.makeConst(x, Sym.tConst, y.typ^.len);
911+ elsif (y.typ^.form = Sym.fSlice) and (y.mode = Item.mVar) then
912+ (* its length, the word after its pointer *)
913+ y.off := y.off + 8;
914+ y.typ := Sym.tInt;
915+ try Item.value(y);
916+ x := y;
917+ else
918+ return Scan.markAt(y.pos, say1("LEN needs an array or a slice, found {}", Item.what(y)));
919+ end;
920+ | Sym.bSyscall:
921+ n := 0;
922+ repeat
923+ if n > 0 then Scan.next; end;
924+ try expression(y, nil);
925+ if not (Sym.isScalar(y.typ) and (y.typ^.form # Sym.fReal)) then
926+ return Scan.markAt(y.pos, say1("expected an integer or a pointer, found {}", Item.what(y)));
927+ end;
928+ if y.typ^.form = Sym.fConst then try Item.coerce(y, Sym.tInt); end;
929+ try Item.value(y);
930+ INC(n);
931+ until (Scan.tok # Scan.sComma) or (n = 7);
932+ Gen.sysCall(n);
933+ Item.makeConst(x, Sym.tInt, 0);
934+ x.mode := Item.mStack;
935+ | Sym.bCas, Sym.bXchg, Sym.bXadd: try atomic(x, which);
936+ | Sym.bMsg:
937+ try expression(x, Sym.tError);
938+ try Item.msg(x);
939+ | Sym.bInc, Sym.bDec:
940+ try expression(x, nil);
941+ try Item.notReadOnly(x);
942+ if (x.mode # Item.mVar) or not x.isVar or (x.typ^.form # Sym.fInt) then
943+ return Scan.markAt(x.pos, say1("{} needs an integer variable", incOrDec(which)));
944+ end;
945+ if x.base # Gen.bReg then try Item.address(x); end;
946+ if Scan.tok = Scan.sComma then
947+ Scan.next;
948+ try expression(y, x.typ);
949+ else
950+ Item.makeConst(y, x.typ, 1);
951+ end;
952+ try Item.incDec(x, y, which = Sym.bDec);
953+ Item.makeConst(x, Sym.tNone, 0);
954+ x.mode := Item.mNone;
955+ | Sym.bNew: try new_(x);
956+ | Sym.bCopy:
957+ try expression(x, nil);
958+ try Item.copyDest(x);
959+ try expect(Scan.sComma);
960+ try expression(y, nil);
961+ try Item.copyFrom(x, y);
962+ Item.makeConst(x, Sym.tNone, 0);
963+ x.mode := Item.mNone;
964+ | else:
965+ end;
966+ return expect(Scan.sRparen);
967+end;
968+
969+proc constructCase(var x: TItem; c: PObj; at: Diag.Pos): ERROR;
970+var f: PObj; a: TItem;
971+begin
972+ Item.construct(x, c);
973+ f := c^.fields;
974+ if Scan.tok = Scan.sLparen then
975+ Scan.next;
976+ while f # nil do
977+ try expression(a, f^.typ);
978+ try Item.setField(x, f, a);
979+ f := f^.next;
980+ if f # nil then try expect(Scan.sComma); end;
981+ end;
982+ return expect(Scan.sRparen);
983+ elsif f # nil then
984+ return Scan.markAt(at, say1("{} needs its fields", nameOf(c^.name)));
985+ end;
986+ return nil;
987+end;
988+
989+(* x, before ".", has no fields; tok is what follows. Other languages
990+ write p.f through a pointer and s.len for a length. *)
991+proc fieldOfWhat(x: TItem): ERROR;
992+var msg, f: []U8;
993+begin
994+ msg := say1("expected a record, found {}", Item.what(x));
995+ if Scan.tok = Scan.sIdent then f := nameOf(Scan.id); else f := ""; end;
996+ if (x.typ^.form = Sym.fPtr) and (x.typ^.base^.form = Sym.fRecord) then
997+ return Scan.markHelp(x.pos, msg, say2("through a pointer, write {}^.{}", Diag.source(x.pos), f));
998+ elsif ((x.typ^.form = Sym.fArray) or (x.typ^.form = Sym.fSlice))
999+ and ((f = "len") or (f = "length") or (f = "size") or (f = "count")) then
1000+ return Scan.markHelp(x.pos, msg, say1("its length is LEN({})", Diag.source(x.pos)));
1001+ end;
1002+ return Scan.markAt(x.pos, msg);
1003+end;
1004+
1005+(* A designator, with any selectors and calls after it. called tells
1006+ whether the last thing done was a call. *)
1007+proc designator(var x: TItem; var called: BOOL): ERROR;
1008+var o, f: PObj; y, z: TItem; t: PType; start: Diag.Pos;
1009+begin
1010+ start := Scan.tokPos();
1011+ o := try qualIdent();
1012+ called := false;
1013+ if o^.cls = Sym.oModule then
1014+ return Scan.markAt(Scan.spanFrom(start), say1("{} is a module, not a value", nameOf(o^.name)));
1015+ end;
1016+ try Item.makeItem(x, o);
1017+ if x.mode = Item.mBuiltin then
1018+ try builtin(x);
1019+ called := true;
1020+ elsif x.mode = Item.mCase then
1021+ try constructCase(x, o, Scan.spanFrom(start));
1022+ end;
1023+ repeat
1024+ x.pos := Scan.spanFrom(start);
1025+ match Scan.tok of
1026+ | sPeriod:
1027+ Scan.next;
1028+ if (x.mode # Item.mVar) or (x.typ^.form # Sym.fRecord) then return fieldOfWhat(x); end;
1029+ if Scan.tok # Scan.sIdent then return expected("a field"); end;
1030+ f := try fieldOf(x.typ);
1031+ Scan.next;
1032+ try Item.field(x, f);
1033+ called := false;
1034+ | sArrow:
1035+ Scan.next;
1036+ try Item.deref(x);
1037+ called := false;
1038+ | sLbrak:
1039+ Scan.next;
1040+ try Item.indexPrep(x);
1041+ try expression(y, nil);
1042+ if Scan.tok = Scan.sUpto then
1043+ Scan.next;
1044+ try Item.sliceLo(y);
1045+ try expression(z, nil);
1046+ try Item.slice(x, y, z);
1047+ else
1048+ try Item.index(x, y);
1049+ end;
1050+ try expect(Scan.sRbrak);
1051+ called := false;
1052+ | sLparen:
1053+ if x.mode = Item.mType then
1054+ t := x.typ;
1055+ Scan.next;
1056+ try expression(x, nil);
1057+ try expect(Scan.sRparen);
1058+ try Item.convert(x, t);
1059+ else
1060+ if x.mode = Item.mProc then lastCalled := x.obj; else lastCalled := nil; end;
1061+ try call(x);
1062+ called := true;
1063+ end;
1064+ | else: break;
1065+ end;
1066+ until false;
1067+ x.pos := Scan.spanFrom(start);
1068+ Item.nilTest(x);
1069+ return nil;
1070+end;
1071+
1072+proc arrayLiteral(var x: TItem; want: PType): ERROR;
1073+var
1074+ et, at: PType; e: TItem; slots: [MaxElements]I64; n, i: INT;
1075+ off, es: I64; start: Diag.Pos;
1076+begin
1077+ start := Scan.tokPos();
1078+ if (want = nil) or not ((want^.form = Sym.fArray) or (want^.form = Sym.fSlice)) then
1079+ return Scan.mark("an array literal needs a known array or slice type");
1080+ end;
1081+ et := want^.base;
1082+ es := et^.size;
1083+ Scan.next;
1084+ n := 0;
1085+ if Scan.tok # Scan.sRbrak then
1086+ repeat
1087+ if n >= MaxElements then return Scan.mark(tooMany(MaxElements, "elements")); end;
1088+ try expression(e, et);
1089+ try Item.coerce(e, et);
1090+ if Sym.isScalar(et) then
1091+ slots[n] := try Item.toSlot(e);
1092+ else
1093+ if e.isVar or e.vol or (e.mode # Item.mVar) or (e.base # Gen.bFrame) then try Item.copyToTemp(e); end;
1094+ slots[n] := e.off;
1095+ end;
1096+ INC(n);
1097+ if Scan.tok # Scan.sComma then break; end;
1098+ Scan.next;
1099+ until false;
1100+ end;
1101+ try expect(Scan.sRbrak);
1102+ if (want^.form = Sym.fArray) and (I64(n) # want^.len) then
1103+ return Scan.markAt(Scan.spanFrom(start), Diag.say("expected {} elements, found {}", [Fmt.int(want^.len), Fmt.int(n)]));
1104+ end;
1105+ if n = 0 then
1106+ Gen.pushConst(Gen.kWord, 0);
1107+ Item.sliceOf(x, want, 0);
1108+ return nil;
1109+ end;
1110+ if want^.form = Sym.fArray then
1111+ at := want;
1112+ off := Gen.allocTemp(at^.size, at^.align);
1113+ else
1114+ at := Sym.newType(Sym.fArray, I64(n) * es, et^.align);
1115+ at^.len := n;
1116+ at^.base := et;
1117+ off := Gen.allocPerm(at^.size, at^.align); (* lives as long as the call *)
1118+ end;
1119+ for i := 0 to n - 1 do
1120+ if Sym.isScalar(et) then
1121+ Gen.pushVar(Item.frameAdr(slots[i]), 8, false, Gen.kindOf(et));
1122+ Gen.popVar(Item.frameAdr(off + I64(i) * es), Item.scalarSize(et));
1123+ else
1124+ Gen.pushAdr(Item.frameAdr(slots[i]));
1125+ Gen.copyTo(Item.frameAdr(off + I64(i) * es), es);
1126+ end;
1127+ end;
1128+ Item.tempItem(x, at, off);
1129+ return nil;
1130+end;
1131+
1132+(* A record literal: a zeroed temporary, with the fields named filled in. *)
1133+proc recordLiteral(var x: TItem; t: PType): ERROR;
1134+var f: PObj; a: TItem; seen: [MaxNames]INT; n, i: INT;
1135+begin
1136+ Scan.next;
1137+ Item.zeroTemp(x, t);
1138+ n := 0;
1139+ if Scan.tok # Scan.sRbrace then
1140+ repeat
1141+ if Scan.tok # Scan.sIdent then return expected("a field"); end;
1142+ f := try fieldOf(t);
1143+ for i := 0 to n - 1 do
1144+ if seen[i] = Scan.id then
1145+ return Scan.mark(say1("field {} is given twice", nameOf(Scan.id)));
1146+ end;
1147+ end;
1148+ if n < MaxNames then seen[n] := Scan.id; INC(n); end;
1149+ Scan.next;
1150+ try expect(Scan.sColon);
1151+ try expression(a, f^.typ);
1152+ try Item.setField(x, f, a);
1153+ if Scan.tok # Scan.sComma then break; end;
1154+ Scan.next;
1155+ until false;
1156+ end;
1157+ return expect(Scan.sRbrace);
1158+end;
1159+
1160+(* A set literal: the bits of the constant names, or'd at run time with
1161+ those of the others. *)
1162+proc setLiteral(var x: TItem; t: PType): ERROR;
1163+var e: TItem; bits, slot: I64; start: Diag.Pos; s: []U8;
1164+begin
1165+ start := Scan.tokPos();
1166+ Scan.next;
1167+ if (t # nil) and (t^.form # Sym.fSet) then
1168+ return Scan.markAt(Scan.spanFrom(start), say1("expected a set type, found {}", Sym.typeName(t)));
1169+ end;
1170+ bits := 0;
1171+ slot := 0;
1172+ if Scan.tok # Scan.sRbrace then
1173+ repeat
1174+ if t = nil then try expression(e, nil); else try expression(e, t^.base); end;
1175+ if t = nil then
1176+ if e.typ^.form # Sym.fEnum then
1177+ return Scan.markAt(e.pos, say1("a set holds names of an enumeration, found {}", Item.what(e)));
1178+ end;
1179+ t := try setOf(e.typ, e.pos);
1180+ end;
1181+ if not Sym.same(e.typ, t^.base) then
1182+ if e.obj # nil then s := nameOf(e.obj^.name); else s := Item.what(e); end;
1183+ return Scan.markAt(e.pos, say2("{} isn't a name of {}", s, Sym.typeName(t^.base)));
1184+ end;
1185+ if e.mode = Item.mConst then
1186+ bits := bits | (I64(1) shl e.val);
1187+ else
1188+ if slot = 0 then
1189+ slot := Gen.allocTemp(8, 8);
1190+ Gen.pushConst(Gen.kWord, 0);
1191+ Gen.popVar(Item.frameAdr(slot), 8);
1192+ end;
1193+ try Item.value(e);
1194+ Gen.pushConst(Gen.kWord, 1);
1195+ Gen.swap();
1196+ Gen.op(Scan.sShl, Gen.kWord, 8, false);
1197+ Gen.pushVar(Item.frameAdr(slot), 8, false, Gen.kWord);
1198+ Gen.op(Scan.sBar, Gen.kWord, 8, false);
1199+ Gen.popVar(Item.frameAdr(slot), 8);
1200+ end;
1201+ if Scan.tok # Scan.sComma then break; end;
1202+ Scan.next;
1203+ until false;
1204+ end;
1205+ try expect(Scan.sRbrace);
1206+ if t = nil then return Scan.markAt(Scan.spanFrom(start), "{} needs a known set type"); end;
1207+ Item.makeConst(x, t, bits);
1208+ if slot # 0 then
1209+ Gen.pushVar(Item.frameAdr(slot), 8, false, Gen.kWord);
1210+ Gen.pushConst(Gen.kWord, bits);
1211+ Gen.op(Scan.sBar, Gen.kWord, 8, false);
1212+ x.mode := Item.mStack;
1213+ end;
1214+ return nil;
1215+end;
1216+
1217+proc runDefers(base: INT); forward;
1218+
1219+(* The type of the last result of t, the results of a procedure: t if
1220+ it has one, else the last of its several. *)
1221+proc lastResult(t: PType): PType;
1222+var f: PObj;
1223+begin
1224+ if not t^.tuple then return t; end;
1225+ f := t^.fields;
1226+ while f^.next # nil do f := f^.next; end;
1227+ return f^.typ;
1228+end;
1229+
1230+(* The results of the tuple t but the last: the same fields, one fewer *)
1231+proc withoutLast(t: PType): PType;
1232+var r: PType;
1233+begin
1234+ r := Sym.newType(Sym.fRecord, t^.size, t^.align);
1235+ r^.tuple := true;
1236+ r^.fields := t^.fields;
1237+ r^.len := t^.len - 1;
1238+ return r;
1239+end;
1240+
1241+(* try c (the report, 7.8): the call c, then the error it returned, its
1242+ last result: if that isn't nil, the procedure returns it, and a zero
1243+ for each of its other results, after running the deferred statements
1244+ in force. x is left c's other results: none (mNone), one (a value) or
1245+ several (a tuple, for a multiple assignment). The error is kept in a
1246+ slot of the frame, and tested there; the code for it, out of line,
1247+ is made with the stack of values as it stands, and leaves it so,
1248+ since what follows is the code for an error that is nil. *)
1249+proc tryCall(var x: TItem): ERROR;
1250+var
1251+ called: BOOL; c: Gen.CallInfo; start, at: Diag.Pos; res: PType; last: PObj; slot: I64; ok: INT;
1252+begin
1253+ start := Scan.tokPos();
1254+ Scan.next;
1255+ if deferring then return Scan.markAt(Scan.spanFrom(start), "try can't leave a deferred statement"); end;
1256+ if curResult = nil then
1257+ return Scan.markAt(Scan.spanFrom(start), "try needs a procedure that ends in an ERROR result, and this returns nothing");
1258+ elsif lastResult(curResult) # Sym.tError then
1259+ return Scan.markAt(Scan.spanFrom(start),
1260+ say1("try needs a procedure that ends in an ERROR result, and this returns {}", Sym.typeName(curResult)));
1261+ end;
1262+ try designator(x, called);
1263+ if not called and ((x.mode = Item.mProc)
1264+ or (((x.mode = Item.mVar) or (x.mode = Item.mStack)) and (x.typ^.form = Sym.fProc))) then
1265+ (* a procedure without parameters, written without parentheses *)
1266+ at := x.pos;
1267+ try Item.beginCall(c, x);
1268+ try Item.endCall(c, x);
1269+ x.pos := at;
1270+ called := true;
1271+ end;
1272+ if not called then return Scan.markAt(x.pos, say1("try needs a call, found {}", Item.what(x))); end;
1273+ if x.mode = Item.mNone then
1274+ return Scan.markAt(x.pos, "try needs a call that returns an ERROR last, and this returns nothing");
1275+ end;
1276+ if lastResult(x.typ) # Sym.tError then
1277+ return Scan.markAt(x.pos, say1("try needs a call that returns an ERROR last, and this returns {}", Sym.typeName(x.typ)));
1278+ end;
1279+ res := x.typ;
1280+ if x.mode = Item.mStack then
1281+ (* an ERROR alone *)
1282+ slot := Gen.allocTemp(8, 8);
1283+ Gen.popVar(Item.frameAdr(slot), 8);
1284+ x.mode := Item.mNone; x.typ := Sym.tNone;
1285+ elsif x.mode = Item.mWords then
1286+ (* two words, the error on top *)
1287+ slot := Gen.allocTemp(8, 8);
1288+ Gen.popVar(Item.frameAdr(slot), 8);
1289+ x.mode := Item.mStack; x.typ := res^.fields^.typ;
1290+ else
1291+ (* several, in a temporary: the error is where it is *)
1292+ last := res^.fields;
1293+ while last^.next # nil do last := last^.next; end;
1294+ slot := x.off + last^.val;
1295+ if res^.len = 2 then try Item.field(x, res^.fields); else x.typ := withoutLast(res); end;
1296+ end;
1297+ 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);
1303+ Gen.fix(ok);
1304+ x.pos := Scan.spanFrom(start);
1305+ return nil;
1306+end;
1307+
1308+proc factor(var x: TItem; want: PType): ERROR;
1309+var called, vol, several: BOOL; t: PType; start: Diag.Pos; s: []U8;
1310+begin
1311+ several := passOn;
1312+ passOn := false;
1313+ start := Scan.tokPos();
1314+ match Scan.tok of
1315+ | sInt, sChar:
1316+ (* only a hex number can be above high(I64), and it is a U64 *)
1317+ if Scan.ival < 0 then Item.makeConst(x, Sym.tU64, Scan.ival); else Item.makeConst(x, Sym.tConst, Scan.ival); end;
1318+ Scan.next;
1319+ | sReal:
1320+ Item.makeReal(x, Scan.rval);
1321+ Item.usesReals(Scan.tokPos());
1322+ Scan.next;
1323+ | sString:
1324+ Item.makeStr(x);
1325+ Scan.next;
1326+ | sIdent:
1327+ try designator(x, called);
1328+ if x.mode = Item.mNone then
1329+ if lastCalled # nil then s := nameOf(lastCalled^.name); else s := "this procedure"; end;
1330+ return Scan.markAt(x.pos, say1("{} returns nothing", s));
1331+ end;
1332+ if x.typ^.tuple and not several then
1333+ if lastCalled # nil then s := nameOf(lastCalled^.name); else s := "this procedure"; end;
1334+ return Scan.markHelp(x.pos, say1("{} returns several results", s),
1335+ say1("they go to variables: a, b := {}(...)", s));
1336+ end;
1337+ | sLparen:
1338+ Scan.next;
1339+ try expression(x, want);
1340+ try expect(Scan.sRparen);
1341+ | sTry:
1342+ try tryCall(x);
1343+ if x.mode = Item.mNone then return Scan.markAt(x.pos, "this try has no value"); end;
1344+ if x.typ^.tuple then
1345+ return Scan.markHelp(x.pos, "this try has several values", "they go to variables: a, b := try f(...)");
1346+ end;
1347+ | sNot:
1348+ Scan.next;
1349+ try factor(x, nil);
1350+ try Item.notOp(x);
1351+ | sTilde:
1352+ Scan.next;
1353+ try factor(x, nil);
1354+ try Item.complement(x);
1355+ | sLbrak: try arrayLiteral(x, want);
1356+ | sLbrace:
1357+ if (want # nil) and (want^.form = Sym.fRecord) then try recordLiteral(x, want);
1358+ else try setLiteral(x, want);
1359+ end;
1360+ | sArrow:
1361+ Scan.next;
1362+ vol := Scan.tok = Scan.sVolatile;
1363+ if vol then Scan.next; end;
1364+ t := try parseType();
1365+ t := newPtr(t, vol);
1366+ try expect(Scan.sLparen);
1367+ try expression(x, nil);
1368+ try expect(Scan.sRparen);
1369+ try Item.convert(x, t);
1370+ (* a conversion is a factor, not a designator: nothing selects from it *)
1371+ if Scan.tok = Scan.sArrow then
1372+ return Scan.markHelp(Scan.tokPos(), "a conversion can't be dereferenced",
1373+ "convert into a pointer variable, then dereference that");
1374+ end;
1375+ | else: return expected("an expression");
1376+ end;
1377+ x.pos := Scan.spanFrom(start);
1378+ return nil;
1379+end;
1380+
1381+proc isMulOp: BOOL;
1382+begin
1383+ match Scan.tok of
1384+ | sTimes, sSlash, sDiv, sMod, sAmp, sShl, sShr: return true;
1385+ | else: return false;
1386+ end;
1387+end;
1388+
1389+proc isAddOp: BOOL;
1390+begin
1391+ match Scan.tok of
1392+ | sPlus, sMinus, sBar, sXor: return true;
1393+ | else: return false;
1394+ end;
1395+end;
1396+
1397+proc isRelOp: BOOL;
1398+begin
1399+ match Scan.tok of
1400+ | sEql, sNeq, sLss, sLeq, sGtr, sGeq, sIn: return true;
1401+ | else: return false;
1402+ end;
1403+end;
1404+
1405+proc term(var x: TItem; want: PType): ERROR;
1406+var op: Scan.Sym; y: TItem; L: INT; start: Diag.Pos;
1407+begin
1408+ start := Scan.tokPos();
1409+ try factor(x, want);
1410+ while isMulOp() do
1411+ op := Scan.tok;
1412+ Scan.next;
1413+ try Item.op1(op, x, L);
1414+ try factor(y, nil);
1415+ try Item.op2(op, x, y, L);
1416+ x.pos := Scan.spanFrom(start);
1417+ end;
1418+ return nil;
1419+end;
1420+
1421+proc simpleExpr(var x: TItem; want: PType): ERROR;
1422+var op: Scan.Sym; y: TItem; L: INT; start: Diag.Pos;
1423+begin
1424+ start := Scan.tokPos();
1425+ if Scan.tok = Scan.sMinus then
1426+ Scan.next;
1427+ try term(x, nil);
1428+ x.pos := Scan.spanFrom(start);
1429+ try Item.neg(x);
1430+ else
1431+ try term(x, want);
1432+ end;
1433+ while isAddOp() do
1434+ op := Scan.tok;
1435+ Scan.next;
1436+ try Item.op1(op, x, L);
1437+ try term(y, nil);
1438+ try Item.op2(op, x, y, L);
1439+ x.pos := Scan.spanFrom(start);
1440+ end;
1441+ return nil;
1442+end;
1443+
1444+proc relation(var x: TItem; want: PType): ERROR;
1445+var op: Scan.Sym; y: TItem; L: INT;
1446+begin
1447+ try simpleExpr(x, want);
1448+ if isRelOp() then
1449+ op := Scan.tok;
1450+ Scan.next;
1451+ try Item.op1(op, x, L);
1452+ if op = Scan.sIn then try simpleExpr(y, nil); else try simpleExpr(y, x.typ); end;
1453+ try Item.op2(op, x, y, L);
1454+ x.pos := Diag.join(x.pos, y.pos);
1455+ end;
1456+ return nil;
1457+end;
1458+
1459+(* and binds tighter than or, and both below the relations *)
1460+proc conjunct(var x: TItem; want: PType): ERROR;
1461+var y: TItem; L: INT; start: Diag.Pos;
1462+begin
1463+ start := Scan.tokPos();
1464+ try relation(x, want);
1465+ while Scan.tok = Scan.sAnd do
1466+ Scan.next;
1467+ try Item.op1(Scan.sAnd, x, L);
1468+ try relation(y, nil);
1469+ try Item.op2(Scan.sAnd, x, y, L);
1470+ x.pos := Scan.spanFrom(start);
1471+ end;
1472+ return nil;
1473+end;
1474+
1475+proc expression(var x: TItem; want: PType): ERROR;
1476+var y: TItem; L: INT; start: Diag.Pos;
1477+begin
1478+ start := Scan.tokPos();
1479+ try conjunct(x, want);
1480+ while Scan.tok = Scan.sOr do
1481+ Scan.next;
1482+ try Item.op1(Scan.sOr, x, L);
1483+ try conjunct(y, nil);
1484+ try Item.op2(Scan.sOr, x, y, L);
1485+ x.pos := Scan.spanFrom(start);
1486+ end;
1487+ return nil;
1488+end;
1489+
1490+(* Statements *)
1491+
1492+proc enterLoop(var lp: Loop; var old: PLoop);
1493+begin
1494+ lp.brk := Gen.NoLabel;
1495+ lp.base := numDefers;
1496+ old := curLoop;
1497+ curLoop := ADR(lp);
1498+end;
1499+
1500+(* Runs the deferred statements in force above base, newest first. *)
1501+proc runDefers(base: INT);
1502+var i: INT;
1503+begin
1504+ for i := numDefers - 1 to base by -1 do Gen.runDefer(defers[i]); end;
1505+end;
1506+
1507+(* Whether what follows "then" is a lone "break;", with no deferred
1508+ statement to run on the way out of the loop: the break must be the
1509+ branch's last statement, so ";" and then end, elsif or else follow. *)
1510+proc loneBreak: BOOL;
1511+var st: Scan.State; lone: BOOL;
1512+begin
1513+ if (Scan.tok # Scan.sBreak) or (curLoop = nil) or (numDefers # curLoop^.base) then return false; end;
1514+ Scan.saveScan(st);
1515+ lone := false;
1516+ Scan.next;
1517+ if Scan.tok = Scan.sSemicolon then
1518+ Scan.next;
1519+ lone := (Scan.tok = Scan.sEnd) or (Scan.tok = Scan.sElsif) or (Scan.tok = Scan.sElse);
1520+ end;
1521+ Scan.restoreScan(st);
1522+ return lone;
1523+end;
1524+
1525+(* The condition x of if or elsif, and the statements it guards, which
1526+ L skips when it is false. "if c then break; end" is one jump out of
1527+ the loop when c holds, not one past a jump out. *)
1528+proc thenPart(var x: TItem; var L: INT): ERROR;
1529+begin
1530+ try expect(Scan.sThen);
1531+ L := Gen.NoLabel; (* stays so with a lone break: there is nothing to skip *)
1532+ if loneBreak() then
1533+ Chunk.noteLine(Scan.curLine(), Scan.curCol()); (* the jump gets the break's line *)
1534+ try Item.condJumpTrue(x, curLoop^.brk);
1535+ Scan.next; Scan.next; (* skip "break" and ";" *)
1536+ ends := true;
1537+ else
1538+ try Item.condJump(x, L);
1539+ try statements();
1540+ end;
1541+ return nil;
1542+end;
1543+
1544+(* if, elsif and else: each condition's jump skips its branch to the
1545+ next; each branch that doesn't end jumps to the end. A branch that
1546+ ends, in return or break, needs no jump past the others, and all of
1547+ them ending is told to the caller in the global ends. *)
1548+proc ifStatement(start: Diag.Pos; ind: INT): ERROR;
1549+var x: TItem; L, endL: INT; all: BOOL;
1550+begin
1551+ Scan.next;
1552+ try expression(x, nil);
1553+ try thenPart(x, L);
1554+ all := ends;
1555+ endL := Gen.NoLabel;
1556+ while Scan.tok = Scan.sElsif do
1557+ if not ends then Gen.jump(endL); end;
1558+ Gen.fix(L);
1559+ Scan.next;
1560+ try expression(x, nil);
1561+ try thenPart(x, L);
1562+ all := all and ends;
1563+ end;
1564+ if Scan.tok = Scan.sElse then
1565+ if not ends then Gen.jump(endL); end;
1566+ Gen.fix(L);
1567+ Scan.next;
1568+ if Scan.tok = Scan.sIf then elseIf := true; end;
1569+ try statements();
1570+ all := all and ends;
1571+ else
1572+ Gen.fix(L);
1573+ all := false;
1574+ end;
1575+ try closeEnd(start, ind);
1576+ Gen.fix(endL);
1577+ ends := all;
1578+ return nil;
1579+end;
1580+
1581+(* while c do s end: the test comes after the body, and the loop jumps to
1582+ it first, so that a round takes one jump, back to the top if c holds:
1583+
1584+ jmp test rather than top: c, jump to out if false
1585+ top: s s
1586+ test: c, jump to top if true jmp top
1587+ out:
1588+
1589+ One pass reads c before s: so c is compiled where it is written, for
1590+ its messages, and its code taken back (rewind); then read again, and
1591+ compiled, after s (saveScan, restoreScan). *)
1592+proc whileStatement(start: Diag.Pos; ind: INT): ERROR;
1593+var
1594+ x: TItem; top, L, test: INT; lp: Loop; old: PLoop; cond, after: Scan.State; m: Gen.CodeMark;
1595+begin
1596+ Scan.next;
1597+ Scan.saveScan(cond);
1598+ Gen.markCode(m);
1599+ try expression(x, nil);
1600+ try Item.discard(x);
1601+ Gen.rewind(m);
1602+ try expect(Scan.sDo);
1603+ test := Gen.NoLabel;
1604+ Gen.jump(test);
1605+ Gen.alignLoop();
1606+ top := Chunk.pc;
1607+ enterLoop(lp, old);
1608+ try statements();
1609+ curLoop := old;
1610+ Scan.saveScan(after);
1611+ Scan.restoreScan(cond);
1612+ Gen.fix(test);
1613+ Chunk.noteLine(Scan.curLine(), Scan.curCol());
1614+ try expression(x, nil);
1615+ ends := (x.mode = Item.mConst) and (x.val # 0) and (lp.brk = Gen.NoLabel); (* while true *)
1616+ if (x.mode = Item.mConst) and (x.typ^.form = Sym.fBool) then
1617+ if x.val # 0 then Gen.jumpBack(top); end;
1618+ else
1619+ L := Gen.NoLabel;
1620+ try Item.condJumpTrue(x, L);
1621+ Gen.fixTo(L, top);
1622+ end;
1623+ Scan.restoreScan(after);
1624+ try closeEnd(start, ind);
1625+ Gen.fix(lp.brk);
1626+ return nil;
1627+end;
1628+
1629+proc repeatStatement: ERROR;
1630+var x: TItem; top, L: INT; lp: Loop; old: PLoop;
1631+begin
1632+ Scan.next;
1633+ top := Chunk.pc;
1634+ enterLoop(lp, old);
1635+ try statements();
1636+ curLoop := old;
1637+ try expect(Scan.sUntil);
1638+ try expression(x, nil);
1639+ ends := (x.mode = Item.mConst) and (x.val = 0) and (lp.brk = Gen.NoLabel); (* until false *)
1640+ L := Gen.NoLabel;
1641+ try Item.condJump(x, L);
1642+ Gen.fixTo(L, top);
1643+ Gen.fix(lp.brk);
1644+ return nil;
1645+end;
1646+
1647+(* for v := a to b by s do ... end, laid out as
1648+ v := a; the limit b, in a slot unless it is a constant
1649+ if v is past b then goto exit
1650+ goto body
1651+ top: v := v + s
1652+ body: the statements
1653+ the end of a round: goto top, or exit (forNext)
1654+ exit:
1655+ so that a round of a loop by 1 takes one compare and one jump. *)
1656+proc forStatement(start: Diag.Pos; ind: INT): ERROR;
1657+var
1658+ o: PObj; v, a, b, s: TItem; step: I64; top, body, bodyL, exitL: INT;
1659+ lp: Loop; old: PLoop; f: Sym.Form; slot: I64;
1660+begin
1661+ Scan.next;
1662+ if Scan.tok # Scan.sIdent then return expected("a name"); end;
1663+ o := Sym.lookup(Scan.id);
1664+ if o = nil then
1665+ notDeclared(Scan.tokPos(), Scan.id);
1666+ return Scan.Failed;
1667+ end;
1668+ named(o);
1669+ if o^.cls # Sym.oVar then return Scan.mark(say1("{} isn't a variable", nameOf(Scan.id))); end;
1670+ f := o^.typ^.form;
1671+ if (f # Sym.fInt) and (f # Sym.fEnum) then
1672+ return Scan.mark(say1("a for loop needs an integer or enumeration variable, found {}", Sym.typeName(o^.typ)));
1673+ end;
1674+ Scan.next;
1675+ try expect(Scan.sBecomes);
1676+ try Item.makeItem(v, o);
1677+ try expression(a, o^.typ);
1678+ try Item.coerceExact(a, o^.typ, "");
1679+ try Item.assign(v, a);
1680+ try expect(Scan.sTo);
1681+ try expression(b, o^.typ);
1682+ try Item.coerceExact(b, o^.typ, "");
1683+ (* the limit, evaluated once: a constant as it is, else in a slot *)
1684+ if b.mode # Item.mConst then
1685+ slot := try Item.toSlot(b);
1686+ Item.tempItem(b, b.typ, slot);
1687+ end;
1688+ step := 1;
1689+ if Scan.tok = Scan.sBy then
1690+ Scan.next;
1691+ try expression(s, nil);
1692+ step := try constValue(s);
1693+ if step = 0 then return Scan.markAt(s.pos, "the step can't be zero"); end;
1694+ end;
1695+ try expect(Scan.sDo);
1696+ exitL := Gen.NoLabel;
1697+ if step > 0 then try Item.forCmp(o, b, Scan.sGtr, exitL); else try Item.forCmp(o, b, Scan.sLss, exitL); end;
1698+ bodyL := Gen.NoLabel;
1699+ Gen.jump(bodyL);
1700+ Gen.alignLoop();
1701+ top := Chunk.pc;
1702+ try Item.forStep(o, step);
1703+ Gen.fix(bodyL);
1704+ body := Chunk.pc;
1705+ enterLoop(lp, old);
1706+ try statements();
1707+ curLoop := old;
1708+ try closeEnd(start, ind);
1709+ try Item.forNext(o, b, step, exitL, top, body);
1710+ Gen.fix(exitL);
1711+ Gen.fix(lp.brk);
1712+ return nil;
1713+end;
1714+
1715+type
1716+ Labels = record
1717+ lo, hi: [MaxLabels]I64; (* the ranges of the labels so far *)
1718+ at: [MaxLabels]INT; (* where the arm of each starts *)
1719+ n: INT;
1720+ end;
1721+
1722+(* a < b, for values of an integer type, unsigned or not *)
1723+proc below(a, b: I64; unsign: BOOL): BOOL;
1724+begin
1725+ if unsign then return U64(a) < U64(b); end;
1726+ return a < b;
1727+end;
1728+
1729+(* An arm of a match on an integer of type t: its labels, each a
1730+ constant or a range, none overlapping another (report section 7.4),
1731+ then its statements. No code tests the labels here; dispatch does,
1732+ after the last arm, for which each label notes where its arm starts. *)
1733+proc intArm(t: PType; var ls: Labels; var endL: INT): ERROR;
1734+var lo, hi: TItem; first, i: INT; u: BOOL; start: Diag.Pos;
1735+begin
1736+ u := not t^.signed;
1737+ first := ls.n;
1738+ repeat
1739+ start := Scan.tokPos();
1740+ try expression(lo, t);
1741+ try Item.coerce(lo, t);
1742+ _ := try constValue(lo);
1743+ hi := lo;
1744+ if Scan.tok = Scan.sUpto then
1745+ Scan.next;
1746+ try expression(hi, t);
1747+ try Item.coerce(hi, t);
1748+ _ := try constValue(hi);
1749+ if below(hi.val, lo.val, u) then return Scan.markAt(Scan.spanFrom(start), "the range is empty"); end;
1750+ end;
1751+ for i := 0 to ls.n - 1 do
1752+ if not below(hi.val, ls.lo[i], u) and not below(ls.hi[i], lo.val, u) then
1753+ if lo.val = hi.val then
1754+ return Scan.markAt(Scan.spanFrom(start), say1("{} is in another label too", Diag.source(Scan.spanFrom(start))));
1755+ end;
1756+ return Scan.markAt(Scan.spanFrom(start), say1("{} overlaps another label", Diag.source(Scan.spanFrom(start))));
1757+ end;
1758+ end;
1759+ if ls.n >= MaxLabels then
1760+ return Scan.markAt(Scan.spanFrom(start), tooMany(MaxLabels, "labels in one match"));
1761+ end;
1762+ ls.lo[ls.n] := lo.val; ls.hi[ls.n] := hi.val;
1763+ INC(ls.n);
1764+ if Scan.tok # Scan.sComma then break; end;
1765+ Scan.next;
1766+ until false;
1767+ try expect(Scan.sColon);
1768+ for i := first to ls.n - 1 do ls.at[i] := Chunk.pc; end;
1769+ try statements();
1770+ Gen.jump(endL);
1771+ return nil;
1772+end;
1773+
1774+const
1775+ MinTable = 4; (* fewer labels are tested one by one *)
1776+ TableDensity = 8; (* a table has at most this many entries to a label *)
1777+
1778+(* The code that picks the arm, after the last one, which the match's
1779+ start jumped to: label by label, as a chain of compares each to its
1780+ arm; or, for four or more labels not far apart, a jump table (jumpTable),
1781+ which takes the same few instructions for any of them. It is here and
1782+ not before the arms, since a table can only be made once every arm's
1783+ place is known; an arm is entered by a jump back to it. elseAt is where
1784+ the else arm starts, or NoLabel. *)
1785+proc dispatch(t: PType; p: I64; var ls: Labels; elseAt: INT; var endL: INT);
1786+var
1787+ lo, hi: I64; i, start, v, body: INT; u: BOOL;
1788+ entry: [MaxLabels]INT;
1789+begin
1790+ u := (t^.form = Sym.fInt) and not t^.signed;
1791+ lo := 0; hi := 0;
1792+ if ls.n > 0 then
1793+ lo := ls.lo[0]; hi := ls.hi[0];
1794+ for i := 1 to ls.n - 1 do
1795+ if below(ls.lo[i], lo, u) then lo := ls.lo[i]; end;
1796+ if below(hi, ls.hi[i], u) then hi := ls.hi[i]; end;
1797+ end;
1798+ end;
1799+ if (ls.n >= MinTable) and (lo >= -2147483648) and (lo <= 2147483647)
1800+ and (U64(hi - lo) < U64(TableDensity * ls.n)) and (hi - lo < MaxLabels) then
1801+ start := Gen.jumpTable(p, lo, INT(hi - lo) + 1, elseAt, endL);
1802+ for v := 0 to INT(hi - lo) do
1803+ if elseAt # Gen.NoLabel then entry[v] := elseAt; else entry[v] := start; end;
1804+ end;
1805+ for i := 0 to ls.n - 1 do
1806+ for v := INT(ls.lo[i] - lo) to INT(ls.hi[i] - lo) do entry[v] := ls.at[i]; end;
1807+ end;
1808+ for v := 0 to INT(hi - lo) do Gen.tableEntry(start, entry[v]); end;
1809+ return;
1810+ end;
1811+ for i := 0 to ls.n - 1 do
1812+ body := Gen.NoLabel;
1813+ Item.matchRange(p, ls.lo[i], ls.hi[i], body);
1814+ Gen.fixTo(body, ls.at[i]);
1815+ end;
1816+ if elseAt # Gen.NoLabel then Gen.jumpBack(elseAt); end;
1817+end;
1818+
1819+proc matchStatement(start: Diag.Pos; ind: INT): ERROR;
1820+var
1821+ x: TItem; t: PType; c, f, o: PObj; p: I64; L, endL, n, first, disp, elseAt: INT;
1822+ seen: [256]BOOL; hasElse, all, byValue: BOOL; endAt: Diag.Pos; ls: Labels;
1823+begin
1824+ Scan.next;
1825+ try expression(x, nil);
1826+ if x.typ^.form = Sym.fConst then try Item.coerce(x, Sym.tI64); end;
1827+ p := try Item.matchBegin(x);
1828+ t := x.typ;
1829+ try expect(Scan.sOf);
1830+ hasElse := false;
1831+ all := true;
1832+ endL := Gen.NoLabel;
1833+ ls.n := 0;
1834+ (* an integer or an enumeration is matched by its value, and the arms
1835+ are picked by dispatch, after them; a variant by its tag, arm by arm *)
1836+ byValue := (t^.form = Sym.fInt) or (t^.form = Sym.fEnum);
1837+ disp := Gen.NoLabel;
1838+ elseAt := Gen.NoLabel;
1839+ if byValue then Gen.jump(disp); end;
1840+ while Scan.tok = Scan.sBar do
1841+ Scan.next;
1842+ if hasElse then return Scan.mark("else must be the last arm"); end;
1843+ if Scan.tok = Scan.sElse then
1844+ Scan.next;
1845+ try expect(Scan.sColon);
1846+ elseAt := Chunk.pc;
1847+ try statements();
1848+ if byValue then Gen.jump(endL); end;
1849+ hasElse := true;
1850+ elsif t^.form = Sym.fInt then
1851+ try intArm(t, ls, endL);
1852+ else
1853+ first := ls.n;
1854+ L := Gen.NoLabel;
1855+ repeat
1856+ if Scan.tok # Scan.sIdent then return expected("a case"); end;
1857+ c := t^.fields;
1858+ while (c # nil) and (c^.name # Scan.id) do c := c^.next; end;
1859+ if c = nil then
1860+ return Scan.mark(say2("{} isn't a case of {}", nameOf(Scan.id), Sym.typeName(t)));
1861+ end;
1862+ if (c^.val <= 255) and seen[c^.val] then
1863+ return Scan.mark(say1("{} has two arms", nameOf(c^.name)));
1864+ end;
1865+ if c^.val <= 255 then seen[c^.val] := true; end;
1866+ Scan.next;
1867+ if t^.form # Sym.fEnum then
1868+ Item.matchTag(p, c^.val, L);
1869+ break;
1870+ end;
1871+ (* an enumeration's arm may name several, which share its place *)
1872+ ls.lo[ls.n] := c^.val; ls.hi[ls.n] := c^.val;
1873+ INC(ls.n);
1874+ if Scan.tok # Scan.sComma then break; end;
1875+ Scan.next;
1876+ until false;
1877+ try Sym.openScope(Sym.newScope());
1878+ if Scan.tok = Scan.sLparen then
1879+ Scan.next;
1880+ f := c^.fields;
1881+ n := 0;
1882+ repeat
1883+ if Scan.tok # Scan.sIdent then return expected("a name"); end;
1884+ if f = nil then
1885+ return Scan.mark(say1("more names than {} has fields", nameOf(c^.name)));
1886+ end;
1887+ o := Sym.newObj(Sym.oVar, Scan.id, f^.typ);
1888+ o^.lev := 1; o^.ind := true; o^.isVar := true;
1889+ o^.val := p; o^.off := f^.val;
1890+ try declare(o);
1891+ f := f^.next;
1892+ INC(n);
1893+ Scan.next;
1894+ if Scan.tok # Scan.sComma then break; end;
1895+ Scan.next;
1896+ until false;
1897+ if f # nil then
1898+ return Scan.mark(say1("name all the fields of {}, or none", nameOf(c^.name)));
1899+ end;
1900+ try expect(Scan.sRparen);
1901+ end;
1902+ try expect(Scan.sColon);
1903+ for n := first to ls.n - 1 do ls.at[n] := Chunk.pc; end;
1904+ try statements();
1905+ Sym.closeScope();
1906+ Gen.jump(endL);
1907+ if t^.form # Sym.fEnum then Gen.fix(L); end;
1908+ end;
1909+ all := all and ends;
1910+ end;
1911+ endAt := Scan.tokPos();
1912+ try closeEnd(start, ind);
1913+ ends := all;
1914+ if (t^.form = Sym.fInt) and not hasElse then
1915+ return Scan.markHelp(endAt, "a match on an integer needs an else arm", "it may be empty: | else:");
1916+ end;
1917+ if not hasElse then
1918+ c := t^.fields;
1919+ while c # nil do
1920+ if (c^.val > 255) or not seen[c^.val] then
1921+ return Scan.markAt(endAt, say1("no arm for {}", nameOf(c^.name)));
1922+ end;
1923+ c := c^.next;
1924+ end;
1925+ end;
1926+ if byValue then
1927+ Gen.fix(disp);
1928+ dispatch(t, p, ls, elseAt, endL);
1929+ end;
1930+ Gen.fix(endL);
1931+ return nil;
1932+end;
1933+
1934+(* What a message calls x: its name n when x is just that name, else what
1935+ it is. *)
1936+proc subject(x: TItem; n: INT): []U8;
1937+begin
1938+ if x.pos.b - x.pos.a = LEN(nameOf(n)) then return nameOf(n); end;
1939+ if x.mode = Item.mConst then return "a constant"; end;
1940+ return "a value";
1941+end;
1942+
1943+(* x, named first n, is a variable the program may assign: not an
1944+ array constant, nor any part of one. *)
1945+proc assignable(x: TItem; n: INT): ERROR;
1946+begin
1947+ if (x.mode = Item.mConst) and (subject(x, n) = nameOf(n)) then
1948+ return Scan.markAt(x.pos, say1("{} is a constant, and can't be changed", nameOf(n)));
1949+ end;
1950+ if (x.mode = Item.mVar) and (x.obj # nil) and (x.obj^.cls = Sym.oConst) then
1951+ return Scan.markAt(x.pos, say1("{} is a constant, and can't be changed", nameOf(x.obj^.name)));
1952+ end;
1953+ if (x.mode # Item.mVar) or not x.isVar then
1954+ return Scan.markAt(x.pos, say1("can't assign to {}", subject(x, n)));
1955+ end;
1956+ return nil;
1957+end;
1958+
1959+(* The designator a statement starts with. A variable named whole
1960+ before := is assigned, not read: naming it there leaves it as unread
1961+ as it was. *)
1962+proc leftSide(var x: TItem; var called: BOOL): ERROR;
1963+var o: PObj; wasRead: BOOL; n: INT;
1964+begin
1965+ n := Scan.id;
1966+ o := Sym.lookup(n);
1967+ wasRead := (o # nil) and o^.read;
1968+ try designator(x, called);
1969+ if ((Scan.tok = Scan.sBecomes) or (Scan.tok = Scan.sComma)) and (x.pos.b - x.pos.a = LEN(nameOf(n))) then
1970+ o^.read := wasRead;
1971+ end;
1972+ return nil;
1973+end;
1974+
1975+(* a, b := f(x): the variables first, left to right, then the call;
1976+ then each result to its variable, in order. x is the first variable,
1977+ first its name, blank whether it is _. *)
1978+proc multiAssign(var x: TItem; first: INT; blank: BOOL): ERROR;
1979+var
1980+ d: [16]TItem; dn: [16]INT; blanks: [16]BOOL;
1981+ y, z: TItem; n, i: INT; called: BOOL; f: PObj;
1982+begin
1983+ n := 0;
1984+ d[0] := x;
1985+ dn[0] := first;
1986+ blanks[0] := blank;
1987+ repeat
1988+ if not blanks[n] then
1989+ try Item.notReadOnly(d[n]);
1990+ try assignable(d[n], dn[n]);
1991+ try Item.pin(d[n]); (* works out the address now, so that the call can't change it *)
1992+ end;
1993+ INC(n);
1994+ if Scan.tok # Scan.sComma then break; end;
1995+ if n > 15 then return Scan.mark(tooMany(16, "variables in one assignment")); end;
1996+ Scan.next;
1997+ blanks[n] := Scan.tok = Scan.sBlank;
1998+ if blanks[n] then
1999+ Scan.next;
2000+ else
2001+ dn[n] := Scan.id;
2002+ try leftSide(d[n], called);
2003+ end;
2004+ until false;
2005+ try expect(Scan.sBecomes);
2006+ if Scan.tok = Scan.sTry then
2007+ try tryCall(y);
2008+ called := true;
2009+ else
2010+ try designator(y, called);
2011+ end;
2012+ if not called or not y.typ^.tuple or (y.typ^.len # I64(n)) then
2013+ return Scan.markAt(y.pos, Diag.say("expected a call with {} results", [Fmt.int(n)]));
2014+ end;
2015+ (* two results on the stack: the first is brought to the top, and each
2016+ is popped into its variable in turn, as one value; else each is
2017+ read from the temporary they came back in *)
2018+ if y.mode = Item.mWords then Gen.swap(); end;
2019+ f := y.typ^.fields;
2020+ for i := 0 to n - 1 do
2021+ z := y;
2022+ if y.mode = Item.mWords then
2023+ z.mode := Item.mStack; z.typ := f^.typ;
2024+ else
2025+ try Item.field(z, f);
2026+ end;
2027+ if blanks[i] then
2028+ try Item.discard(z);
2029+ else
2030+ try Item.coerceExact(z, d[i].typ, "several results go to variables of just their types");
2031+ try Item.assign(d[i], z);
2032+ end;
2033+ f := f^.next;
2034+ end;
2035+ return nil;
2036+end;
2037+
2038+(* return a, b; or return f(x); with f's several results passed on *)
2039+proc returnResults: ERROR;
2040+var f: PObj; x: TItem;
2041+begin
2042+ f := curResult^.fields;
2043+ passOn := true;
2044+ while f # nil do
2045+ try expression(x, f^.typ);
2046+ if x.typ^.tuple then
2047+ if not Sym.same(x.typ, curResult) then
2048+ return Scan.markAt(x.pos, say2("expected the results {}, found {}", Sym.typeName(curResult), Sym.typeName(x.typ)));
2049+ end;
2050+ return Item.returnAll(x);
2051+ end;
2052+ try Item.returnField(f, x);
2053+ f := f^.next;
2054+ if f # nil then try expect(Scan.sComma); end;
2055+ end;
2056+ return nil;
2057+end;
2058+
2059+(* defer s: s is compiled where it stands, as a little subroutine of the
2060+ procedure, jumped over; each way out of the statement list calls it. *)
2061+proc deferStatement: ERROR;
2062+var L, pos, saved: INT; oldLoop: PLoop; oldDeferring: BOOL; start: Diag.Pos;
2063+begin
2064+ start := Scan.tokPos();
2065+ Scan.next;
2066+ if directDefer then return Scan.markAt(Scan.spanFrom(start), "defer can't be deferred"); end;
2067+ if numDefers >= MaxDefers then
2068+ return Scan.markAt(Scan.spanFrom(start), tooMany(MaxDefers, "deferred statements in one procedure"));
2069+ end;
2070+ L := Gen.NoLabel;
2071+ pos, saved := Gen.deferBegin(L);
2072+ oldLoop := curLoop; oldDeferring := deferring;
2073+ curLoop := nil;
2074+ deferring := true;
2075+ directDefer := true;
2076+ try statement();
2077+ directDefer := false;
2078+ curLoop := oldLoop; deferring := oldDeferring;
2079+ Gen.deferEnd(L, saved);
2080+ defers[numDefers] := pos;
2081+ INC(numDefers);
2082+ return nil;
2083+end;
2084+
2085+(* Whether the expression of x := ..., which starts at the current
2086+ symbol, is x changed by adding to it, taking from it or its bits:
2087+ x + e, x - e, x | e or x xor e, with x nowhere in e, so that it can be
2088+ worked out in x's own register, if x is in one (Gen's inPlace). *)
2089+proc changesItself(x: TItem): BOOL;
2090+var st: Scan.State; wasSkipping, changes: BOOL; d: INT;
2091+begin
2092+ if (x.mode # Item.mVar) or (x.base # Gen.bReg) or (x.typ^.form = Sym.fSlice)
2093+ or (Scan.tok # Scan.sIdent) or (Scan.id # x.obj^.name) then
2094+ return false;
2095+ end;
2096+ changes := false;
2097+ Scan.saveScan(st);
2098+ wasSkipping := Scan.skipping;
2099+ Scan.setSkipping(true); (* its slips are told when it is compiled *)
2100+ Scan.next;
2101+ if isAddOp() then
2102+ changes := true;
2103+ d := 0;
2104+ while not ((d = 0) and ((Scan.tok = Scan.sSemicolon) or (Scan.tok = Scan.sEnd))) and (Scan.tok # Scan.sEof) do
2105+ if (Scan.tok = Scan.sIdent) and (Scan.id = x.obj^.name) then changes := false; end;
2106+ match Scan.tok of
2107+ | sLparen, sLbrak, sLbrace: INC(d);
2108+ | sRparen, sRbrak, sRbrace: DEC(d);
2109+ | else:
2110+ end;
2111+ Scan.next;
2112+ end;
2113+ end;
2114+ Scan.restoreScan(st);
2115+ Scan.setSkipping(wasSkipping);
2116+ return changes;
2117+end;
2118+
2119+(* A call standing on its own, which drops the results x holds, if any,
2120+ to be warned of *)
2121+proc noteDrop(x: TItem);
2122+begin
2123+ if (x.mode # Item.mNone) and (numDrops < MaxDrops) then
2124+ drops[numDrops].at := x.pos;
2125+ if x.typ^.tuple then drops[numDrops].n := INT(x.typ^.len); else drops[numDrops].n := 1; end;
2126+ INC(numDrops);
2127+ end;
2128+end;
2129+
2130+proc oneStatement: ERROR;
2131+var
2132+ x, y: TItem; called: BOOL; m: I64; c: Gen.CallInfo; start: Diag.Pos; first, n, i: INT; k: Gen.Kind;
2133+begin
2134+ start := Scan.tokPos();
2135+ first := Scan.id;
2136+ Chunk.noteLine(Scan.curLine(), Scan.curCol());
2137+ m := Gen.tempMark();
2138+ ends := false;
2139+ match Scan.tok of
2140+ | sIdent:
2141+ try leftSide(x, called);
2142+ if Scan.tok = Scan.sBecomes then
2143+ try Item.notReadOnly(x);
2144+ try assignable(x, first);
2145+ Scan.next;
2146+ if changesItself(x) then Gen.setInPlace(x.chunk); end;
2147+ try expression(y, x.typ);
2148+ Gen.setInPlace(-1);
2149+ try Item.assign(x, y);
2150+ elsif Scan.tok = Scan.sComma then
2151+ try multiAssign(x, first, false);
2152+ elsif not called then
2153+ if (x.mode = Item.mProc)
2154+ or (((x.mode = Item.mVar) or (x.mode = Item.mStack)) and (x.typ^.form = Sym.fProc)) then
2155+ try Item.beginCall(c, x);
2156+ try Item.endCall(c, x);
2157+ try Item.discard(x);
2158+ elsif Scan.tok = Scan.sEql then
2159+ return Scan.markHelp(x.pos, say1("{} isn't a statement", subject(x, first)), "assignment is written :=");
2160+ else
2161+ return Scan.markAt(x.pos, say1("{} isn't a statement", subject(x, first)));
2162+ end;
2163+ else
2164+ noteDrop(x);
2165+ try Item.discard(x);
2166+ end;
2167+ | sBlank:
2168+ Scan.next;
2169+ if Scan.tok = Scan.sComma then
2170+ try multiAssign(x, 0, true);
2171+ else
2172+ try expect(Scan.sBecomes);
2173+ try expression(x, nil);
2174+ (* evaluated and dropped: a single value is loaded, so that a
2175+ volatile one is read *)
2176+ if (x.mode = Item.mType) or (x.mode = Item.mBuiltin) or (x.mode = Item.mNone) or (x.mode = Item.mCase)
2177+ or ((x.mode # Item.mStr) and not Sym.isAggregate(x.typ)) then
2178+ try Item.value(x);
2179+ end;
2180+ try Item.discard(x);
2181+ end;
2182+ | sIf: try ifStatement(start, Scan.indent());
2183+ | sWhile: try whileStatement(start, Scan.indent());
2184+ | sRepeat: try repeatStatement();
2185+ | sFor: try forStatement(start, Scan.indent());
2186+ | sMatch: try matchStatement(start, Scan.indent());
2187+ | sReturn:
2188+ Scan.next;
2189+ if deferring then return Scan.markAt(Scan.spanFrom(start), "return can't leave a deferred statement"); end;
2190+ if Scan.tok = Scan.sSemicolon then
2191+ runDefers(0);
2192+ try Item.returnNone();
2193+ else
2194+ if (curResult # nil) and curResult^.tuple then
2195+ try returnResults();
2196+ else
2197+ try expression(x, curResult);
2198+ try Item.returnValue(x);
2199+ end;
2200+ (* the result, one value or two words on top, waits in the frame
2201+ while the deferred statements run *)
2202+ if (numDefers > 0) and (curResult # nil) and not Sym.behindPointer(curResult) then
2203+ n := 1; k := Gen.kindOf(curResult);
2204+ if Sym.inTwoRegs(curResult) then n := 2; k := Gen.kWord; end;
2205+ if deferSlot = 0 then deferSlot := Gen.allocPerm(16, 8); end;
2206+ for i := n - 1 to 0 by -1 do Gen.popVar(Item.frameAdr(deferSlot + I64(8 * i)), 8); end;
2207+ runDefers(0);
2208+ for i := 0 to n - 1 do Gen.pushVar(Item.frameAdr(deferSlot + I64(8 * i)), 8, false, k); end;
2209+ else
2210+ runDefers(0);
2211+ end;
2212+ Gen.returnJump();
2213+ ends := true;
2214+ end;
2215+ | sBreak:
2216+ Scan.next;
2217+ if curLoop = nil then return Scan.markAt(Scan.spanFrom(start), "break outside a loop"); end;
2218+ runDefers(curLoop^.base);
2219+ Gen.jump(curLoop^.brk);
2220+ | sDefer: try deferStatement();
2221+ | sTry:
2222+ try tryCall(x);
2223+ noteDrop(x);
2224+ try Item.discard(x);
2225+ | sArrow:
2226+ return Scan.markHelp(Scan.tokPos(), "a statement starts with a name",
2227+ "convert into a pointer variable, then assign through that");
2228+ | else:
2229+ if Scan.atLineStart() then
2230+ return endMissing(Scan.missingPos(), say1("expected \"end\", found {}", Scan.found()));
2231+ end;
2232+ return expected("a statement");
2233+ end;
2234+ Gen.releaseTemps(m);
2235+ return nil;
2236+end;
2237+
2238+proc statement: ERROR;
2239+var r: Recover; m: I64; err: ERROR;
2240+begin
2241+ m := Gen.tempMark();
2242+ guard(r);
2243+ err := oneStatement();
2244+ if err = nil then
2245+ skipped := false;
2246+ else
2247+ restore(r);
2248+ (* a statement never starts a line: this is the next declaration *)
2249+ if Scan.atLineStart() or not skipConstruct() then return giveUp(r); end;
2250+ Gen.releaseTemps(m);
2251+ skipped := true;
2252+ end;
2253+ unguard(r);
2254+ return nil;
2255+end;
2256+
2257+proc endsStatements: BOOL;
2258+begin
2259+ match Scan.tok of
2260+ | sEnd, sElse, sElsif, sUntil, sBar, sEof: return true;
2261+ | else: return false;
2262+ end;
2263+end;
2264+
2265+proc statements: ERROR;
2266+var base: INT; old: BOOL;
2267+begin
2268+ base := numDefers;
2269+ old := directDefer;
2270+ directDefer := false;
2271+ ends := false;
2272+ while not endsStatements() do
2273+ try statement();
2274+ if not skipped or (Scan.tok = Scan.sSemicolon) then try expect(Scan.sSemicolon); end;
2275+ end;
2276+ runDefers(base);
2277+ numDefers := base;
2278+ directDefer := old;
2279+ return nil;
2280+end;
2281+
2282+(* Declarations *)
2283+
2284+(* In a file read for its interface only: skip a procedure's body, from
2285+ its local declarations to the end that closes it. *)
2286+proc skipBody: ERROR;
2287+var d: INT; sawBegin: BOOL;
2288+begin
2289+ d := 0;
2290+ sawBegin := false;
2291+ repeat
2292+ match Scan.tok of
2293+ | sBegin:
2294+ if d = 0 then sawBegin := true; end;
2295+ INC(d);
2296+ | sIf, sWhile, sFor, sMatch, sRecord, sVariant: INC(d);
2297+ | sEnd:
2298+ DEC(d);
2299+ if (d = 0) and sawBegin then
2300+ Scan.next;
2301+ return nil;
2302+ end;
2303+ | sEof: return expected("\"end\"");
2304+ | else:
2305+ end;
2306+ Scan.next;
2307+ until false;
2308+ return nil;
2309+end;
2310+
2311+proc declarations(top: BOOL); forward;
2312+
2313+(* How Rt shows a variable of o's type in the trap report: 1 a signed
2314+ integer, 2 an unsigned one, 3 a BOOL, 4 an address, 5 a real; plus
2315+ its size times 16, and 256 if the frame holds its address, or 512
2316+ times 1 + i if it is in register ShownRegs[i]; 0 if it isn't shown. *)
2317+proc varKind(o: PObj): INT;
2318+var k, i, v: INT;
2319+begin
2320+ match o^.typ^.form of
2321+ | fInt: if o^.typ^.signed then k := 1; else k := 2; end;
2322+ | fEnum, fSet: k := 2;
2323+ | fBool: k := 3;
2324+ | fPtr, fProc, fError: k := 4;
2325+ | fReal: k := 5;
2326+ | else: return 0;
2327+ end;
2328+ v := k + INT(o^.typ^.size) * 16;
2329+ if o^.ind then v := v + 256; end;
2330+ for i := 0 to LEN(Gen.ShownRegs) - 1 do
2331+ if o^.reg = Gen.ShownRegs[i] then v := k + INT(o^.typ^.size) * 16 + (i + 1) * 512; end;
2332+ end;
2333+ return v;
2334+end;
2335+
2336+(* Whether variable o could live in registers: a single value, a real
2337+ in an xmm register, or a slice, in two, that isn't C's *)
2338+proc regFit(o: PObj): BOOL;
2339+var f: Sym.Form;
2340+begin
2341+ if (o^.cls # Sym.oVar) or o^.ind or o^.ext then return false; end;
2342+ f := o^.typ^.form;
2343+ return (f = Sym.fInt) or (f = Sym.fBool) or (f = Sym.fEnum) or (f = Sym.fPtr) or (f = Sym.fProc)
2344+ or (f = Sym.fError) or (f = Sym.fSlice) or (f = Sym.fReal)
2345+ or ((f = Sym.fSet) and (o^.typ^.size <= 8));
2346+end;
2347+
2348+(* The first local of the procedure being compiled. Locals are chained
2349+ by chain in the order declared, the module's own first; before is the
2350+ last one declared before the procedure's, or nil if there was none. *)
2351+proc firstLocal(before: PObj): PObj;
2352+begin
2353+ if before = nil then return Sym.curModule^.locals; end;
2354+ return before^.chain;
2355+end;
2356+
2357+const MaxCand = 64; (* variables of a procedure that may go in registers *)
2358+
2359+var
2360+ cand: [MaxCand]PObj; (* chooseRegs's candidates and their weights *)
2361+ weight: [MaxCand]INT;
2362+ numCand: INT;
2363+
2364+proc candidate(n: INT): INT;
2365+var j: INT;
2366+begin
2367+ for j := 0 to numCand - 1 do
2368+ if cand[j]^.name = n then return j; end;
2369+ end;
2370+ return -1;
2371+end;
2372+
2373+proc addCandidate(o: PObj);
2374+begin
2375+ if regFit(o) and (numCand < MaxCand) then
2376+ cand[numCand] := o;
2377+ weight[numCand] := 0;
2378+ INC(numCand);
2379+ end;
2380+end;
2381+
2382+(* Whether naming o may make a call: a procedure, a procedure variable,
2383+ or NEW, SYSCALL or COPY, which use the registers a call would *)
2384+proc calls(o: PObj): BOOL;
2385+begin
2386+ if o = nil then return false; end;
2387+ return (o^.cls = Sym.oProc) or ((o^.cls = Sym.oVar) and (o^.typ^.form = Sym.fProc))
2388+ or ((o^.cls = Sym.oBuiltin) and ((o^.val = Sym.bNew) or (o^.val = Sym.bSyscall) or (o^.val = Sym.bCopy)));
2389+end;
2390+
2391+(* Puts the busiest variables of the procedure, whose parameters are
2392+ params and whose locals follow before, in registers: read ahead from
2393+ its "begin" to its end, a use counts 1, in a loop 4, in two 16, in
2394+ three or more 64, and a variable ADR is taken of can't have one. A register costs a save
2395+ and a restore, so a variable used less than three times keeps its
2396+ place in memory. A slice takes two, its pointer's and its length's;
2397+ a real one of the xmm registers, stored and loaded again around each
2398+ call, as System V keeps none through one. In a procedure that names no procedure, so calls nothing, the
2399+ parameters that arrive in the registers no call needs stay there
2400+ (keepArrived), at no cost. *)
2401+proc chooseRegs(params, before: PObj);
2402+var
2403+ isLoop: [256]BOOL;
2404+ i, k, kx, d, loops, best, need: INT; o, q, qual: PObj; st: Scan.State;
2405+ afterDot, wasSkipping, leaf: BOOL;
2406+begin
2407+ numCand := 0;
2408+ o := params;
2409+ while o # nil do addCandidate(o); o := o^.next; end;
2410+ o := firstLocal(before);
2411+ while o # nil do addCandidate(o); o := o^.chain; end;
2412+ if numCand = 0 then return; end;
2413+ Scan.saveScan(st);
2414+ wasSkipping := Scan.skipping;
2415+ Scan.setSkipping(true); (* its slips are told when it is compiled *)
2416+ d := 0; loops := 0; afterDot := false; leaf := true; qual := nil;
2417+ 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;
2427+ end;
2428+ match Scan.tok of
2429+ | sBegin, sIf, sMatch, sWhile, sFor, sRepeat:
2430+ if d < 255 then
2431+ INC(d);
2432+ isLoop[d] := (Scan.tok = Scan.sWhile) or (Scan.tok = Scan.sFor) or (Scan.tok = Scan.sRepeat);
2433+ if isLoop[d] then INC(loops); end;
2434+ end;
2435+ | sEnd, sUntil:
2436+ if isLoop[d] then DEC(loops); end;
2437+ DEC(d);
2438+ | sIdent:
2439+ if Scan.id = nameAdr then
2440+ Scan.next;
2441+ if Scan.tok = Scan.sLparen then Scan.next; end;
2442+ (* a hugely negative weight bars it from a register, whatever
2443+ its uses add *)
2444+ if (Scan.tok = Scan.sIdent) and (candidate(Scan.id) >= 0) then weight[candidate(Scan.id)] := -1073741824; end;
2445+ elsif not afterDot and (candidate(Scan.id) >= 0) then
2446+ k := candidate(Scan.id);
2447+ if loops > 2 then INC(weight[k], 64); else INC(weight[k], 1 shl (2 * loops)); end;
2448+ end;
2449+ | else:
2450+ end;
2451+ afterDot := Scan.tok = Scan.sPeriod; (* a name after a dot is a field, not a variable *)
2452+ if (d > 0) and (Scan.tok # Scan.sEof) then Scan.next; end;
2453+ until (d = 0) or (Scan.tok = Scan.sEof);
2454+ Scan.restoreScan(st);
2455+ Scan.setSkipping(wasSkipping);
2456+ if leaf then
2457+ o := params;
2458+ while o # nil do
2459+ k := candidate(o^.name);
2460+ if (k >= 0) and (weight[k] >= 0) then Gen.keepArrived(o); end; (* a candidate whose ADR isn't taken *)
2461+ o := o^.next;
2462+ end;
2463+ end;
2464+ (* a slice's weight is shared by its two registers *)
2465+ for i := 0 to numCand - 1 do
2466+ if cand[i]^.typ^.form = Sym.fSlice then weight[i] := weight[i] div 2; end;
2467+ end;
2468+ (* the heaviest, each used at least three times a register, take the
2469+ five registers in turn, while there are enough for each, and the
2470+ reals the four xmm registers of XVarRegs *)
2471+ k := 0; kx := 0;
2472+ repeat
2473+ best := -1;
2474+ for i := 0 to numCand - 1 do
2475+ if (cand[i]^.reg = 0) and (weight[i] >= 3) and ((best < 0) or (weight[i] > weight[best])) then best := i; end;
2476+ end;
2477+ if best < 0 then break; end;
2478+ need := 1;
2479+ if cand[best]^.typ^.form = Sym.fSlice then need := 2; end;
2480+ if cand[best]^.typ^.form = Sym.fReal then
2481+ if kx < 4 then
2482+ cand[best]^.reg := Gen.XVarRegs[kx];
2483+ INC(kx);
2484+ else
2485+ weight[best] := 0;
2486+ end;
2487+ elsif k + need <= 5 then
2488+ cand[best]^.reg := Gen.VarRegs[k];
2489+ if need = 2 then cand[best]^.reg2 := Gen.VarRegs[k + 1]; end;
2490+ INC(k, need);
2491+ else
2492+ weight[best] := 0; (* too big for what is left *)
2493+ end;
2494+ until false;
2495+end;
2496+
2497+(* The registers the variables of the procedure are in, as bits: bit i
2498+ is VarRegs[i], bit XBit + i XVarRegs[i] *)
2499+proc regBits(o: PObj): INT;
2500+var m, k: INT;
2501+begin
2502+ m := 0;
2503+ for k := 0 to 4 do
2504+ if (o^.reg = Gen.VarRegs[k]) or (o^.reg2 = Gen.VarRegs[k]) then m := m | (1 shl k); end;
2505+ end;
2506+ for k := 0 to 3 do
2507+ if o^.reg = Gen.XVarRegs[k] then m := m | (1 shl (Gen.XBit + k)); end;
2508+ end;
2509+ return m;
2510+end;
2511+
2512+proc regsOf(params, before: PObj): INT;
2513+var o: PObj; m: INT;
2514+begin
2515+ m := 0;
2516+ o := params;
2517+ while o # nil do
2518+ m := m | regBits(o);
2519+ o := o^.next;
2520+ end;
2521+ o := firstLocal(before);
2522+ while o # nil do
2523+ if o^.cls = Sym.oVar then m := m | regBits(o); end;
2524+ o := o^.chain;
2525+ end;
2526+ return m;
2527+end;
2528+
2529+(* Gives each local not in a register its slot in the frame, the slots
2530+ the prologue zeroes, and then tells Gen which registers the
2531+ variables are in. A variable in a register has no slot: it starts at
2532+ zero in its register, and the trap report finds it there. *)
2533+proc placeLocals(params, before: PObj);
2534+var o: PObj;
2535+begin
2536+ Gen.resetLocals();
2537+ o := firstLocal(before);
2538+ while o # nil do
2539+ if (o^.cls = Sym.oVar) and (o^.reg = 0) then
2540+ o^.val := Gen.allocPerm(o^.typ^.size, o^.typ^.align);
2541+ elsif (o^.cls = Sym.oVar) and (o^.reg >= Gen.XmmVar) then
2542+ o^.val := Gen.allocPerm(8, 8);
2543+ Gen.xHome(o^.reg, o^.val);
2544+ end;
2545+ o := o^.chain;
2546+ end;
2547+ o := params;
2548+ while o # nil do
2549+ if o^.reg >= Gen.XmmVar then Gen.xHome(o^.reg, o^.val); end;
2550+ o := o^.next;
2551+ end;
2552+ Gen.useRegs(regsOf(params, before));
2553+end;
2554+
2555+proc body(p: PObj; sig: PType; line: INT): ERROR;
2556+var
2557+ q, params, last, o, before: PObj; old: PType; st: Scan.State;
2558+ mark: Gen.CodeMark; drops0, errs: INT;
2559+begin
2560+ try Sym.openScope(Sym.newScope());
2561+ params := nil; last := nil;
2562+ q := sig^.fields;
2563+ while q # nil do
2564+ o := Sym.newObj(Sym.oVar, q^.name, q^.typ);
2565+ o^.pos := q^.pos;
2566+ o^.lev := 1;
2567+ o^.isVar := q^.isVar;
2568+ o^.param := true;
2569+ if last = nil then params := o; else last^.next := o; end;
2570+ last := o;
2571+ q := q^.next;
2572+ end;
2573+ Item.beginProc(sig, params);
2574+ deferSlot := 0;
2575+ o := params;
2576+ while o # nil do
2577+ q := o^.next;
2578+ try declare(o);
2579+ o := q;
2580+ end;
2581+ curProc := p;
2582+ before := Sym.curModule^.lastLocal;
2583+ declarations(false);
2584+ chooseRegs(params, before);
2585+ placeLocals(params, before);
2586+ (* the body, made again if a variable in a register must be in memory *)
2587+ Scan.saveScan(st);
2588+ Gen.markCode(mark); drops0 := numDrops; errs := Diag.errors;
2589+ old := curResult;
2590+ repeat
2591+ Item.setDemoted(false);
2592+ try expect(Scan.sBegin);
2593+ curResult := sig^.base;
2594+ Gen.enterBody(p^.chunk, line);
2595+ stray := false; elseIf := false; deferSlot := 0;
2596+ try statements();
2597+ p^.openEnd := (curResult # nil) and not ends;
2598+ Chunk.noteLine(Scan.curLine(), Scan.curCol());
2599+ try expect(Scan.sEnd);
2600+ if not (Item.demoted or Gen.lost) or (Diag.errors # errs) then break; end;
2601+ (* a parameter kept where it arrived goes to memory: a call or a copy
2602+ wanted its register *)
2603+ if Gen.lost then
2604+ o := params;
2605+ while o # nil do
2606+ if Gen.keptIn(o) then o^.reg := 0; o^.reg2 := 0; end;
2607+ o := o^.next;
2608+ end;
2609+ end;
2610+ numDrops := drops0;
2611+ Gen.redo(mark);
2612+ placeLocals(params, before);
2613+ Scan.restoreScan(st);
2614+ until false;
2615+ try Gen.endProc(p^.chunk, p^.openEnd);
2616+ (* its parameters and variables, for the trap report *)
2617+ o := firstLocal(before);
2618+ q := params;
2619+ while q # nil do
2620+ if varKind(q) # 0 then Chunk.noteVar(p^.chunk, q^.name, INT(q^.val), varKind(q)); end;
2621+ q := q^.next;
2622+ end;
2623+ while o # nil do
2624+ if (o^.cls = Sym.oVar) and (varKind(o) # 0) then Chunk.noteVar(p^.chunk, o^.name, INT(o^.val), varKind(o)); end;
2625+ o := o^.chain;
2626+ end;
2627+ curResult := old;
2628+ curProc := nil;
2629+ Sym.closeScope();
2630+ return nil;
2631+end;
2632+
2633+(* An integer constant in a code procedure, for the assembler: a whole
2634+ expression, or a single factor where an expression would read on
2635+ too far *)
2636+proc asmConst(whole: BOOL): (I64, ERROR);
2637+var x: TItem;
2638+begin
2639+ if whole then return constExpr(); end;
2640+ try factor(x, nil);
2641+ if not Sym.isInt(x.typ) then
2642+ return 0, Scan.markAt(x.pos, say1("expected an integer constant, found {}", Item.what(x)));
2643+ end;
2644+ return constValue(x);
2645+end;
2646+
2647+proc codeBody(p: PObj; sig: PType; at: Diag.Pos): ERROR;
2648+var q: PObj; ni, nf: INT;
2649+begin
2650+ ni := 0; nf := 0;
2651+ q := sig^.fields;
2652+ while q # nil do
2653+ if not q^.isVar and (q^.typ^.form = Sym.fSlice) then
2654+ INC(ni, 2); (* address, then length *)
2655+ else
2656+ if not q^.isVar and not Sym.isScalar(q^.typ) then
2657+ return Scan.markAt(at, "a code procedure takes integers, BOOL, reals, pointers, procedures and slices");
2658+ end;
2659+ if (q^.typ^.form = Sym.fReal) and not q^.isVar then INC(nf); else INC(ni); end;
2660+ end;
2661+ q := q^.next;
2662+ end;
2663+ if (ni > 6) or (nf > 8) or sig^.variadic then
2664+ return Scan.markAt(at, "too many parameters for a code procedure");
2665+ end;
2666+ if sig^.base # nil then
2667+ if sig^.base^.tuple then
2668+ q := sig^.base^.fields;
2669+ if (sig^.base^.len # 2) or (q^.typ^.size # 8) or (q^.next^.typ^.size # 8)
2670+ or not Sym.isScalar(q^.typ) or not Sym.isScalar(q^.next^.typ)
2671+ or (q^.typ^.form = Sym.fReal) or (q^.next^.typ^.form = Sym.fReal) then
2672+ return Scan.markAt(at, "a code procedure returns two results only in rax and rdx");
2673+ end;
2674+ elsif not Sym.isScalar(sig^.base) and (sig^.base^.form # Sym.fSlice) then
2675+ return Scan.markAt(at, "a code procedure returns a single value");
2676+ end;
2677+ end;
2678+ try Gen.codeProc(p^.chunk, asmConst);
2679+ return expect(Scan.sEnd);
2680+end;
2681+
2682+proc procDecl: ERROR;
2683+var n, line: INT; exp: BOOL; sig: PType; p: PObj; at: Diag.Pos;
2684+begin
2685+ try instancesFor(false);
2686+ line := Scan.curLine();
2687+ Scan.next;
2688+ try identDef(n, exp, at);
2689+ sig := try signature();
2690+ try expect(Scan.sSemicolon);
2691+ p := Sym.find(Sym.topScope(), n);
2692+ if (p # nil) and (p^.cls = Sym.oProc) and p^.fwd then
2693+ if not Sym.same(p^.typ, sig) then
2694+ Diag.error(at, say1("{} doesn't have the signature it was declared forward with", nameOf(n)));
2695+ Diag.note(p^.pos, "the signature is here");
2696+ return Scan.Failed;
2697+ end;
2698+ if Scan.tok = Scan.sForward then return Scan.mark(say1("{} is declared forward twice", nameOf(n))); end;
2699+ p^.exported := p^.exported or exp;
2700+ else
2701+ p := Sym.newObj(Sym.oProc, n, sig);
2702+ p^.pos := at;
2703+ p^.exported := exp;
2704+ if (Sym.curModule^.name = nameRt) and not checkMode and (n = nameFail) then
2705+ p^.chunk := Gen.rtFail;
2706+ else
2707+ p^.chunk := Chunk.newChunk(Chunk.secText, Sym.curModule^.sname, n);
2708+ end;
2709+ try declare(p);
2710+ end;
2711+ if Scan.tok = Scan.sForward then
2712+ Scan.next;
2713+ p^.fwd := true;
2714+ return nil;
2715+ end;
2716+ p^.fwd := false;
2717+ if Scan.tok = Scan.sCode then
2718+ Scan.next;
2719+ p^.isCode := true;
2720+ try codeBody(p, sig, at);
2721+ elsif checkMode then
2722+ try skipBody();
2723+ else
2724+ try body(p, sig, line);
2725+ end;
2726+ if Scan.tok = Scan.sIdent then
2727+ if Scan.id = Sym.curModule^.name then
2728+ return endMissing(Scan.tokPos(), say1("{} has no \"end\": this one closes the module", nameOf(n)));
2729+ elsif Scan.id # n then
2730+ return endMissing(Scan.tokPos(), say2("expected {}, found {}", nameOf(n), nameOf(Scan.id)));
2731+ end;
2732+ Scan.next;
2733+ end;
2734+ return nil;
2735+end;
2736+
2737+(* An extern procedure or variable: C's, reached through the quadword
2738+ that holds its address. *)
2739+proc externDecl: ERROR;
2740+var n: INT; exp: BOOL; o, q: PObj; t: PType; at: Diag.Pos;
2741+begin
2742+ Scan.next;
2743+ Sym.curModule^.usesC := true;
2744+ if Scan.tok = Scan.sProc then
2745+ Scan.next;
2746+ try identDef(n, exp, at);
2747+ willDeclare(n);
2748+ inExtern := true;
2749+ t := try signature();
2750+ inExtern := false;
2751+ q := t^.fields;
2752+ while q # nil do
2753+ if q^.isVar or not Sym.isScalar(q^.typ) then
2754+ return Scan.markAt(at, "C takes integers, BOOL, reals, pointers and procedures");
2755+ end;
2756+ q := q^.next;
2757+ end;
2758+ if (t^.base # nil) and not Sym.isScalar(t^.base) then
2759+ return Scan.markAt(at, "C returns a single value");
2760+ end;
2761+ o := Sym.newObj(Sym.oProc, n, t);
2762+ else
2763+ if Scan.tok # Scan.sVar then return expected("\"proc\" or \"var\""); end;
2764+ Scan.next;
2765+ try identDef(n, exp, at);
2766+ willDeclare(n);
2767+ try expect(Scan.sColon);
2768+ declExported := exp;
2769+ t := try parseType();
2770+ declExported := false;
2771+ o := Sym.newObj(Sym.oVar, n, t);
2772+ end;
2773+ o^.pos := at;
2774+ o^.exported := exp;
2775+ o^.ext := true;
2776+ o^.chunk := Chunk.externChunk(n);
2777+ return declare(o);
2778+end;
2779+
2780+(* An array or record constant: a literal of constants, which become
2781+ the bytes of a read-only chunk, as a string constant's do (report
2782+ section 4). An address in it, of a string, an array constant, a
2783+ procedure or an ERROR, waits in fixes until the chunk is made, then
2784+ is a fixup the linker patches. The bytes are the compiler's own
2785+ machine's, little-endian, as the target's are. *)
2786+var
2787+ constBytes: ^U8;
2788+ fixes: [MaxFixes]record off, chunk: INT; end;
2789+ numFixes: INT;
2790+
2791+proc constFix(off, chunk: INT): ERROR;
2792+begin
2793+ if numFixes >= MaxFixes then
2794+ return Scan.mark(tooMany(MaxFixes, "addresses in one constant"));
2795+ end;
2796+ fixes[numFixes].off := off;
2797+ fixes[numFixes].chunk := chunk;
2798+ INC(numFixes);
2799+ return nil;
2800+end;
2801+
2802+(* The n bytes of v, at off in the constant: little-endian, as the machine is *)
2803+proc putBytes(off, n: INT; v: I64);
2804+var src: ^U8;
2805+begin
2806+ src := ^U8(ADR(v));
2807+ COPY(constBytes[off..off + n], src[0..n]);
2808+end;
2809+
2810+(* The part of type t at offset off of the constant *)
2811+proc constPart(t: PType; off: INT): ERROR;
2812+var e: TItem; f: PObj; k: INT; r: F32; start: Diag.Pos; src: ^U8; st: INT;
2813+begin
2814+ start := Scan.tokPos();
2815+ if (t^.form = Sym.fArray) and (Scan.tok = Scan.sLbrak) then
2816+ Scan.next;
2817+ k := 0;
2818+ if Scan.tok # Scan.sRbrak then
2819+ repeat
2820+ if I64(k) < t^.len then
2821+ try constPart(t^.base, off + k * INT(t^.base^.size));
2822+ else
2823+ try constPart(t^.base, off);
2824+ end;
2825+ INC(k);
2826+ if Scan.tok # Scan.sComma then break; end;
2827+ Scan.next;
2828+ until false;
2829+ end;
2830+ try expect(Scan.sRbrak);
2831+ if I64(k) # t^.len then
2832+ return Scan.markAt(Scan.spanFrom(start), Diag.say("expected {} elements, found {}", [Fmt.int(t^.len), Fmt.int(k)]));
2833+ end;
2834+ return nil;
2835+ end;
2836+ if (t^.form = Sym.fRecord) and not t^.tuple and (Scan.tok = Scan.sLbrace) then
2837+ Scan.next;
2838+ if Scan.tok # Scan.sRbrace then
2839+ repeat
2840+ if Scan.tok # Scan.sIdent then return expected("a field"); end;
2841+ f := try fieldOf(t);
2842+ Scan.next;
2843+ try expect(Scan.sColon);
2844+ try constPart(f^.typ, off + INT(f^.val));
2845+ if Scan.tok # Scan.sComma then break; end;
2846+ Scan.next;
2847+ until false;
2848+ end;
2849+ return expect(Scan.sRbrace);
2850+ end;
2851+ try expression(e, t);
2852+ if (e.mode = Item.mStr) and ((t^.form = Sym.fSlice) or (t^.form = Sym.fArray)) and (t^.base = Sym.tU8) then
2853+ if t^.form = Sym.fSlice then
2854+ try constFix(off, e.chunk);
2855+ putBytes(off + 8, 8, e.val);
2856+ elsif e.val > t^.len then
2857+ return Scan.markAt(e.pos, say1("the string is longer than {}", Sym.typeName(t)));
2858+ else
2859+ st := Chunk.chunks[e.chunk].start;
2860+ COPY(constBytes[off..off + INT(e.val)], Chunk.rodata[st..st + INT(e.val)]);
2861+ end;
2862+ elsif t^.form = Sym.fSlice then
2863+ if (e.mode # Item.mVar) or (e.obj = nil) or (e.obj^.cls # Sym.oConst) or (e.typ^.form # Sym.fArray)
2864+ or (e.pos.b - e.pos.a # LEN(nameOf(e.obj^.name))) or not Sym.same(e.typ^.base, t^.base) then
2865+ return Scan.markAt(e.pos, say1("a constant slice is a string or an array constant of its elements, found {}", Item.what(e)));
2866+ end;
2867+ try constFix(off, e.chunk);
2868+ putBytes(off + 8, 8, e.typ^.len);
2869+ elsif t^.form = Sym.fVariant then
2870+ return Scan.markAt(e.pos, "a constant holds no variant");
2871+ elsif (t^.form = Sym.fArray) or (t^.form = Sym.fRecord) then
2872+ return Scan.markAt(e.pos, say1("expected a literal of {}", Sym.typeName(t)));
2873+ else
2874+ try Item.coerce(e, t);
2875+ if (e.mode = Item.mProc) and not e.obj^.ext then
2876+ try constFix(off, e.obj^.chunk);
2877+ elsif e.mode # Item.mConst then
2878+ return Scan.markAt(e.pos, say1("expected a constant, found {}", Item.what(e)));
2879+ elsif (t^.form = Sym.fError) and (e.val > 0) then
2880+ try constFix(off, INT(e.val) - 1);
2881+ elsif (t^.form = Sym.fPtr) and (e.val # 0) then
2882+ return Scan.markAt(e.pos, "a constant pointer is nil");
2883+ elsif (t^.form = Sym.fReal) and (t^.size = 4) then
2884+ r := F32(Item.realOf(e));
2885+ src := ^U8(ADR(r));
2886+ COPY(constBytes[off..off + 4], src[0..4]);
2887+ else
2888+ putBytes(off, INT(t^.size), e.val);
2889+ end;
2890+ end;
2891+ return nil;
2892+end;
2893+
2894+(* The chunk of n, a constant of type t whose literal is next *)
2895+proc aggregateConst(t: PType; n: INT): (INT, ERROR);
2896+var c, i, size: INT;
2897+begin
2898+ size := INT(t^.size);
2899+ constBytes := Scan.grab(size + 8);
2900+ for i := 0 to size + 7 do constBytes[i] := 0; end;
2901+ numFixes := 0;
2902+ try constPart(t, 0);
2903+ c := Chunk.newChunk(Chunk.secRodata, Sym.curModule^.sname, n);
2904+ Chunk.setData(c, constBytes, size, INT(t^.align));
2905+ for i := 0 to numFixes - 1 do Chunk.addDataFixup(c, fixes[i].off, fixes[i].chunk, 0); end;
2906+ return c, nil;
2907+end;
2908+
2909+proc constDecl(top: BOOL): ERROR;
2910+var n, c: INT; exp: BOOL; x: TItem; o: PObj; t: PType; start, at: Diag.Pos;
2911+begin
2912+ try identDef(n, exp, at);
2913+ willDeclare(n);
2914+ t := nil;
2915+ if Scan.tok = Scan.sColon then
2916+ Scan.next;
2917+ start := Scan.tokPos();
2918+ t := try parseType();
2919+ if (t # Sym.tError) and not ((t^.form = Sym.fArray) or ((t^.form = Sym.fRecord) and not t^.tuple)) then
2920+ return Scan.markAt(Scan.spanFrom(start), "only an ERROR, an array or a record constant has a type");
2921+ end;
2922+ end;
2923+ try expect(Scan.sEql);
2924+ if (t # nil) and ((t^.form = Sym.fArray) or (t^.form = Sym.fRecord)) then
2925+ o := Sym.newObj(Sym.oConst, n, t);
2926+ o^.chunk := try aggregateConst(t, n);
2927+ o^.pos := at;
2928+ o^.exported := exp and top;
2929+ try declare(o);
2930+ return expect(Scan.sSemicolon);
2931+ end;
2932+ try expression(x, nil);
2933+ o := Sym.newObj(Sym.oConst, n, x.typ);
2934+ o^.pos := at;
2935+ o^.exported := exp and top;
2936+ if t = Sym.tError then
2937+ o^.typ := Sym.tError;
2938+ c := try Item.errorChunk(x, Sym.curModule^.sname, n);
2939+ o^.val := c + 1;
2940+ elsif x.mode = Item.mStr then
2941+ o^.val := x.val;
2942+ o^.chunk := x.chunk;
2943+ else
2944+ o^.val := try constValue(x);
2945+ end;
2946+ try declare(o);
2947+ return expect(Scan.sSemicolon);
2948+end;
2949+
2950+proc typeDecl(top: BOOL): ERROR;
2951+var n: INT; exp: BOOL; o: PObj; t: PType; at: Diag.Pos;
2952+begin
2953+ try identDef(n, exp, at);
2954+ willDeclare(n);
2955+ try expect(Scan.sEql);
2956+ declExported := exp and top;
2957+ inTypes := true;
2958+ t := try parseType();
2959+ o := Sym.newObj(Sym.oType, n, t);
2960+ o^.pos := at;
2961+ o^.exported := exp and top;
2962+ if t^.obj = nil then t^.obj := o; end;
2963+ try declare(o);
2964+ return expect(Scan.sSemicolon);
2965+end;
2966+
2967+proc varDecl(top: BOOL): ERROR;
2968+var
2969+ i, k: INT; o: PObj; t: PType;
2970+ names: [MaxNames]INT; exps: [MaxNames]BOOL; poss: [MaxNames]Diag.Pos;
2971+begin
2972+ k := 0;
2973+ repeat
2974+ if k >= MaxNames then return Scan.mark(tooMany(MaxNames, "names in one declaration")); end;
2975+ try identDef(names[k], exps[k], poss[k]);
2976+ willDeclare(names[k]);
2977+ INC(k);
2978+ if Scan.tok # Scan.sComma then break; end;
2979+ Scan.next;
2980+ until false;
2981+ try expect(Scan.sColon);
2982+ declExported := top and exps[0];
2983+ t := try parseType();
2984+ declExported := false;
2985+ for i := 0 to k - 1 do
2986+ o := Sym.newObj(Sym.oVar, names[i], t);
2987+ o^.pos := poss[i];
2988+ o^.exported := exps[i] and top;
2989+ o^.isVar := false;
2990+ if top then
2991+ o^.lev := 0;
2992+ o^.chunk := Chunk.newChunk(Chunk.secBss, Sym.curModule^.sname, names[i]);
2993+ Chunk.setBss(o^.chunk, INT(t^.size), INT(t^.align));
2994+ else
2995+ o^.lev := 1; (* its slot comes from placeLocals, if it needs one *)
2996+ end;
2997+ try declare(o);
2998+ end;
2999+ return expect(Scan.sSemicolon);
3000+end;
3001+
3002+(* After a procedure had an error: its name is poison if it wasn't
3003+ declared, and reading goes on after the "end Name;" that closes it,
3004+ or at the next procedure if that is missing *)
3005+proc skipProc;
3006+var st: Scan.State;
3007+begin
3008+ Scan.next;
3009+ if (Scan.tok = Scan.sIdent) and (Sym.find(Sym.topScope(), Scan.id) = nil) then poison(Scan.id); end;
3010+ repeat
3011+ repeat Scan.next; until Scan.atLineStart() or (Scan.tok = Scan.sEof);
3012+ match Scan.tok of
3013+ | sProc, sExtern, sEof: return;
3014+ | sEnd:
3015+ Scan.saveScan(st);
3016+ Scan.next;
3017+ if Scan.tok = Scan.sIdent then Scan.next; end;
3018+ if Scan.tok = Scan.sSemicolon then
3019+ Scan.next;
3020+ return;
3021+ end;
3022+ Scan.restoreScan(st);
3023+ return;
3024+ | else:
3025+ end;
3026+ until false;
3027+end;
3028+
3029+(* What one declaration, of the kind k, reads *)
3030+proc declarationOf(k: Scan.Sym; top: BOOL): ERROR;
3031+begin
3032+ match k of
3033+ | sConst: return constDecl(top);
3034+ | sType: return typeDecl(top);
3035+ | sVar: return varDecl(top);
3036+ | sProc:
3037+ if not top then return Scan.mark("procedures don't nest"); end;
3038+ try procDecl();
3039+ return expect(Scan.sSemicolon);
3040+ | sExtern:
3041+ if not top then return Scan.mark("extern is only for the top of a module"); end;
3042+ try externDecl();
3043+ return expect(Scan.sSemicolon);
3044+ | else: return nil;
3045+ end;
3046+end;
3047+
3048+(* One declaration, as a recovery point: an error is reported, the
3049+ declaration skipped, and reading goes on after it *)
3050+proc declaration(k: Scan.Sym; top: BOOL);
3051+var r: Recover;
3052+begin
3053+ guard(r);
3054+ numDeclaring := 0;
3055+ if declarationOf(k, top) # nil then
3056+ restore(r);
3057+ if k = Scan.sProc then skipProc(); else skipDeclaration(); end;
3058+ end;
3059+ unguard(r);
3060+end;
3061+
3062+proc declarations(top: BOOL);
3063+var i: INT; o: PObj; k: Scan.Sym;
3064+begin
3065+ repeat
3066+ k := Scan.tok;
3067+ match k of
3068+ | sConst, sVar:
3069+ Scan.next;
3070+ while Scan.tok = Scan.sIdent do declaration(k, top); end;
3071+ | sType:
3072+ Scan.next;
3073+ numFwd := 0;
3074+ while Scan.tok = Scan.sIdent do declaration(Scan.sType, top); end;
3075+ inTypes := false;
3076+ for i := 0 to numFwd - 1 do
3077+ o := Sym.lookup(fwdTypes[i]^.fwd);
3078+ if (o = nil) or (o^.cls # Sym.oType) then
3079+ notDeclared(fwdPos[i], fwdTypes[i]^.fwd);
3080+ fwdTypes[i]^.base := Sym.tPoison;
3081+ else
3082+ fwdTypes[i]^.base := o^.typ;
3083+ named(o);
3084+ end;
3085+ fwdTypes[i]^.fwd := -1;
3086+ end;
3087+ | sProc, sExtern: declaration(k, top);
3088+ | else: return;
3089+ end;
3090+ until false;
3091+end;
3092+
3093+(* Modules *)
3094+
3095+(* Whether m is module n with these arguments. *)
3096+proc isModule(m: PModule; n: INT; args: Sym.Args): BOOL;
3097+var i: INT;
3098+begin
3099+ if (m^.name # n) or (m^.args.n # args.n) then return false; end;
3100+ for i := 0 to args.n - 1 do
3101+ if (m^.args.o[i] # args.o[i]) or not Sym.same(m^.args.t[i], args.t[i]) then return false; end;
3102+ end;
3103+ return true;
3104+end;
3105+
3106+proc findModule(n: INT; args: Sym.Args): PModule;
3107+var m: PModule;
3108+begin
3109+ m := firstModule;
3110+ while (m # nil) and not isModule(m, n, args) do m := m^.next; end;
3111+ return m;
3112+end;
3113+
3114+(* The arguments of an instance: types, or procedures named. *)
3115+proc parseArgs(var args: Sym.Args; mname: []U8): ERROR;
3116+var o: PObj; start: Diag.Pos;
3117+begin
3118+ Scan.next;
3119+ repeat
3120+ if args.n >= 8 then return Scan.mark(say1("too many type arguments for {}", mname)); end;
3121+ args.o[args.n] := nil;
3122+ start := Scan.tokPos();
3123+ if Scan.tok = Scan.sIdent then
3124+ o := try qualIdent();
3125+ if o^.cls = Sym.oProc then
3126+ args.o[args.n] := o;
3127+ elsif o^.cls # Sym.oType then
3128+ return Scan.markAt(Scan.spanFrom(start), say1("{} isn't a type or a procedure", nameOf(o^.name)));
3129+ end;
3130+ args.t[args.n] := o^.typ;
3131+ else
3132+ args.t[args.n] := try parseType();
3133+ end;
3134+ args.pos[args.n] := Scan.spanFrom(start);
3135+ INC(args.n);
3136+ if Scan.tok # Scan.sComma then break; end;
3137+ Scan.next;
3138+ until false;
3139+ return expect(Scan.sRparen);
3140+end;
3141+
3142+(* Past an instance's arguments, to be read when it is made *)
3143+proc skipArgs: ERROR;
3144+var p: INT;
3145+begin
3146+ p := 0;
3147+ repeat
3148+ if Scan.tok = Scan.sLparen then
3149+ INC(p);
3150+ elsif Scan.tok = Scan.sRparen then
3151+ DEC(p);
3152+ elsif (Scan.tok = Scan.sSemicolon) or (Scan.tok = Scan.sEof) then
3153+ return expected("\")\"");
3154+ end;
3155+ Scan.next;
3156+ until p = 0;
3157+ return nil;
3158+end;
3159+
3160+(* A generic module's parameters, bound to the instance's arguments: a
3161+ type parameter names its type, a procedure parameter its procedure.
3162+ The instance's name is the module's with its arguments, List(I64). *)
3163+proc moduleParams(m: PModule): ERROR;
3164+var i: INT; o, a: PObj; sig: PType; s: Buf.Buf; at: Diag.Pos; text: []U8;
3165+begin
3166+ Buf.init(ADR(s), Heap.heap);
3167+ i := 0;
3168+ Buf.str(ADR(s), nameOf(m^.name));
3169+ Buf.add(ADR(s), '(');
3170+ Scan.next;
3171+ repeat
3172+ if Scan.tok # Scan.sIdent then return expected("a name"); end;
3173+ if i >= m^.args.n then
3174+ return Scan.markAt(m^.args.at, say2("{} needs a type for {}", nameOf(m^.name), nameOf(Scan.id)));
3175+ end;
3176+ if m^.args.o[i] # nil then
3177+ return Scan.markAt(m^.args.pos[i], say2("{} needs a type for {}", nameOf(m^.name), nameOf(Scan.id)));
3178+ end;
3179+ o := Sym.newObj(Sym.oType, Scan.id, m^.args.t[i]);
3180+ o^.used := true; (* a parameter of the module, not a declaration *)
3181+ try declare(o);
3182+ Buf.str(ADR(s), Sym.typeName(m^.args.t[i]));
3183+ Buf.add(ADR(s), ',');
3184+ INC(i);
3185+ Scan.next;
3186+ if Scan.tok # Scan.sComma then break; end;
3187+ Scan.next;
3188+ until false;
3189+ while Scan.tok = Scan.sSemicolon do
3190+ Scan.next;
3191+ if Scan.tok # Scan.sIdent then return expected("a name"); end;
3192+ at := Scan.tokPos();
3193+ o := Sym.newObj(Sym.oProc, Scan.id, nil);
3194+ Scan.next;
3195+ try expect(Scan.sColon);
3196+ try expect(Scan.sProc);
3197+ sig := try signature();
3198+ if i >= m^.args.n then
3199+ return Scan.markAt(m^.args.at, say2("{} needs a procedure for {}", nameOf(m^.name), nameOf(o^.name)));
3200+ end;
3201+ a := m^.args.o[i];
3202+ if a = nil then
3203+ return Scan.markAt(m^.args.pos[i], say2("{} needs a procedure for {}", nameOf(m^.name), nameOf(o^.name)));
3204+ end;
3205+ if not Sym.same(a^.typ, sig) then
3206+ Diag.error(m^.args.pos[i], say2("{} doesn't have the signature of {}", nameOf(a^.name), nameOf(o^.name)));
3207+ Diag.note(at, "the signature is here");
3208+ Diag.finish();
3209+ end;
3210+ o^.typ := a^.typ; o^.chunk := a^.chunk; o^.isCode := a^.isCode; o^.ext := a^.ext;
3211+ o^.used := true;
3212+ try declare(o);
3213+ Buf.str(ADR(s), nameOf(a^.home^.name));
3214+ Buf.add(ADR(s), '.');
3215+ Buf.str(ADR(s), nameOf(a^.name));
3216+ Buf.add(ADR(s), ',');
3217+ INC(i);
3218+ end;
3219+ try expect(Scan.sRparen);
3220+ if i # m^.args.n then
3221+ return Scan.markAt(m^.args.at, say1("too many type arguments for {}", nameOf(m^.name)));
3222+ end;
3223+ text := Buf.bytes(ADR(s));
3224+ text[LEN(text) - 1] := ')';
3225+ m^.sname := internName(text);
3226+ Buf.done(ADR(s));
3227+ return nil;
3228+end;
3229+
3230+(* Warns of o if it is never used, or a variable only assigned. What
3231+ is exported may be used elsewhere, and a name that starts with _ says
3232+ it is meant to go unused. Writing a var parameter, a match's name for
3233+ a field or C's variable is what it is for. *)
3234+proc warn(o: PObj);
3235+var s, t: []U8;
3236+begin
3237+ s := nameOf(o^.name);
3238+ if (o^.cls = Sym.oProc) and o^.openEnd then
3239+ Diag.warning(o^.pos, say1("{} may reach its end without return, and then returns zero", s));
3240+ end;
3241+ if o^.exported or (s[0] = '_') then return; end;
3242+ if o^.used and (o^.read or (o^.cls # Sym.oVar) or o^.isVar or o^.ext) then return; end;
3243+ match o^.cls of
3244+ | oConst: t := say1("constant {}", s);
3245+ | oType: t := say1("type {}", s);
3246+ | oVar:
3247+ if o^.param then t := say1("parameter {}", s); else t := say1("variable {}", s); end;
3248+ | oProc: t := say1("procedure {}", s);
3249+ | oModule: t := say1("module {}", s);
3250+ | else: return;
3251+ end;
3252+ if o^.used then
3253+ Diag.warning(o^.pos, say1("{} is assigned but never read", t));
3254+ elsif o^.cls = Sym.oModule then
3255+ Diag.warning(o^.pos, say1("{} is imported but never used", t));
3256+ else
3257+ Diag.warning(o^.pos, say1("{} is never used", t));
3258+ end;
3259+ if not o^.used and (o^.param or o^.ind) then
3260+ Diag.help(say1("if it must be there, call it _{}", s));
3261+ end;
3262+end;
3263+
3264+(* Warns of the call at p, which drops its n results *)
3265+proc dropped(p: Diag.Pos; n: INT);
3266+var s, blanks: []U8; i: INT;
3267+begin
3268+ s := Diag.source(p);
3269+ i := 0;
3270+ while (i < LEN(s)) and (s[i] # '(') do INC(i); end;
3271+ if i < LEN(s) then s := s[0..i]; end;
3272+ blanks := "_";
3273+ for i := 2 to n do blanks := say1("{}, _", blanks); end;
3274+ if n = 1 then
3275+ Diag.warning(p, say1("the result of {} is dropped", s));
3276+ else
3277+ Diag.warning(p, say1("the results of {} are dropped", s));
3278+ end;
3279+ Diag.help(say2("if that is meant, write {} := {}(...)", blanks, s));
3280+end;
3281+
3282+(* The warnings of module m, by where each declaration is: its own
3283+ declarations and its procedures' are two lists, each in order, and
3284+ firstDrop on are the calls that drop results. The
3285+ instances of a generic module share its text, and so its warnings:
3286+ only the first is warned of. *)
3287+proc warnings(m: PModule; firstDrop: INT);
3288+var a, b: PObj; n: PModule; i: INT;
3289+begin
3290+ n := firstModule;
3291+ while (n # nil) and (n^.name # m^.name) do n := n^.next; end;
3292+ if n # nil then return; end;
3293+ a := m^.first; b := m^.locals;
3294+ i := firstDrop;
3295+ while (a # nil) or (b # nil) or (i < numDrops) do
3296+ if (i < numDrops) and ((a = nil) or (drops[i].at.a < a^.pos.a)) and ((b = nil) or (drops[i].at.a < b^.pos.a)) then
3297+ dropped(drops[i].at, drops[i].n);
3298+ INC(i);
3299+ elsif (b = nil) or ((a # nil) and (a^.pos.a < b^.pos.a)) then
3300+ warn(a);
3301+ a := a^.chain;
3302+ else
3303+ warn(b);
3304+ b := b^.chain;
3305+ end;
3306+ end;
3307+end;
3308+
3309+(* Modules being compiled, not yet finished: for finding a cycle. *)
3310+var
3311+ pending: [MaxPending]PModule;
3312+ numPending: INT;
3313+
3314+proc exists(path: []U8): BOOL;
3315+var info: Sys.Info; err: INT;
3316+begin
3317+ info, err := Sys.info(path);
3318+ return (err = 0) and info.file;
3319+end;
3320+
3321+(* Which file path is, as its device and inode: two names of one file
3322+ have the same. Zero for a file that can't be asked about. *)
3323+proc identity(path: []U8): (INT, INT);
3324+var a: [4096]U8; st: [18]INT; (* struct stat: st_dev, then st_ino *)
3325+begin
3326+ if LEN(path) >= 4096 then return 0, 0; end;
3327+ COPY(a[0..LEN(path)], path);
3328+ a[LEN(path)] := 0;
3329+ if SYSCALL(4, ADR(a[0]), ADR(st)) < 0 then return 0, 0; end;
3330+ return st[0], st[1];
3331+end;
3332+
3333+(* s, in memory that is never freed, for what must outlast the buffer it is in *)
3334+proc keep(s: []U8): []U8;
3335+var p: ^U8;
3336+begin
3337+ if LEN(s) = 0 then return ""; end;
3338+ p := Scan.grab(LEN(s));
3339+ COPY(p[0..LEN(s)], s);
3340+ return p[0..LEN(s)];
3341+end;
3342+
3343+proc importModule(name: INT; args: Sym.Args): (PModule, ERROR); forward;
3344+
3345+(* Compiles module n from path, an instance if args are given, or only
3346+ reads its interface if checkOnly; returns it. An import calls this in
3347+ the middle of reading another file, so it is re-entrant: it saves the
3348+ scanner's state, the open scopes, the current module and file and
3349+ whether checks are on, and puts them back at the end. *)
3350+proc compileFile(path: []U8; n: INT; args: Sym.Args; checkOnly: BOOL): (PModule, ERROR);
3351+var
3352+ st: Scan.State; saved: [Sym.MaxDepth]INT; d: INT;
3353+ oldMod: PModule; oldCheck, oldChecks: BOOL; m: PModule;
3354+ lib: ^Sym.Lib; start: Diag.Pos; alias, mname, line, oldPath: INT; o: PObj; bodyChunk: INT; iargs: Sym.Args;
3355+ generic: BOOL; argsAt: Scan.State; why: []U8; firstDrop: INT;
3356+begin
3357+ firstDrop := numDrops;
3358+ Scan.saveScan(st);
3359+ d := Sym.saveScopes(saved[0..Sym.MaxDepth]);
3360+ oldMod := Sym.curModule; oldCheck := checkMode; oldPath := Chunk.curFilePath(); oldChecks := Item.checks;
3361+ Item.setChecks(true);
3362+ Chunk.setCurFile(internName(path));
3363+ why := Scan.open(path);
3364+ if LEN(why) # 0 then Diag.fatal(say2("can't read {}: {}", path, why)); end;
3365+ NEW(m, Heap.heap);
3366+ m^.name := n;
3367+ m^.sname := n;
3368+ m^.args := args;
3369+ m^.scope := Sym.newScope();
3370+ m^.path := path;
3371+ m^.body := -1;
3372+ m^.checkOnly := checkOnly;
3373+ Sym.setCurModule(m);
3374+ checkMode := checkOnly;
3375+ if not checkOnly then
3376+ if numPending >= MaxPending then
3377+ return nil, Scan.mark(tooMany(MaxPending, "imports nested deep"));
3378+ end;
3379+ pending[numPending] := m;
3380+ INC(numPending);
3381+ end;
3382+ try Sym.openScope(m^.scope);
3383+ Scan.next;
3384+ try expect(Scan.sModule);
3385+ if (Scan.tok # Scan.sIdent) or (Scan.id # n) then
3386+ return nil, Scan.mark(say2("expected module {}, found {}", nameOf(n), Scan.found()));
3387+ end;
3388+ Scan.next;
3389+ (* the module first pending is the one named on the command line,
3390+ which nothing imports, so no arguments come with it *)
3391+ if (Scan.tok = Scan.sLparen) and not checkOnly and (numPending = 1) then
3392+ return nil, Scan.mark(say1("{} is generic: it is compiled where a module imports it", nameOf(n)));
3393+ elsif Scan.tok = Scan.sLparen then
3394+ try moduleParams(m);
3395+ elsif args.n > 0 then
3396+ return nil, Scan.markAt(args.at, say1("{} isn't generic", nameOf(n)));
3397+ end;
3398+ try expect(Scan.sSemicolon);
3399+ while Scan.tok = Scan.sImport do
3400+ Scan.next;
3401+ repeat
3402+ if Scan.tok # Scan.sIdent then return nil, expected("a module name"); end;
3403+ start := Scan.tokPos();
3404+ alias := Scan.id;
3405+ mname := Scan.id;
3406+ iargs.n := 0;
3407+ generic := false;
3408+ Scan.next;
3409+ if Scan.tok = Scan.sBecomes then
3410+ Scan.next;
3411+ if Scan.tok # Scan.sIdent then return nil, expected("a module name"); end;
3412+ mname := Scan.id;
3413+ Scan.next;
3414+ if Scan.tok = Scan.sLparen then
3415+ generic := true;
3416+ Scan.saveScan(argsAt);
3417+ try skipArgs();
3418+ end;
3419+ end;
3420+ iargs.at := Scan.spanFrom(start);
3421+ o := Sym.newObj(Sym.oModule, alias, nil);
3422+ o^.pos := start;
3423+ try declare(o);
3424+ if not generic then
3425+ o^.home := try importModule(mname, iargs);
3426+ addImport(m, o^.home);
3427+ else
3428+ o^.home := nil; (* until the instance is made, at its first use *)
3429+ if numDeferred >= MaxDeferred then
3430+ return nil, Scan.mark(tooMany(MaxDeferred, "generic imports"));
3431+ end;
3432+ deferred[numDeferred].o := o;
3433+ deferred[numDeferred].home := m;
3434+ deferred[numDeferred].mname := mname;
3435+ deferred[numDeferred].args := argsAt;
3436+ deferred[numDeferred].at := iargs.at;
3437+ INC(numDeferred);
3438+ end;
3439+ if Scan.tok # Scan.sComma then break; end;
3440+ Scan.next;
3441+ until false;
3442+ try expect(Scan.sSemicolon);
3443+ end;
3444+ while Scan.tok = Scan.sLink do
3445+ Scan.next;
3446+ if (Scan.tok = Scan.sIdent) and (Scan.id = nameStatic) then
3447+ m^.linkStatic := true;
3448+ elsif Scan.tok = Scan.sString then
3449+ NEW(lib, Heap.heap);
3450+ lib^.name := internName(Scan.strBytes());
3451+ lib^.next := m^.libs;
3452+ m^.libs := lib;
3453+ m^.usesC := true;
3454+ else
3455+ return nil, expected("a library or \"static\"");
3456+ end;
3457+ Scan.next;
3458+ try expect(Scan.sSemicolon);
3459+ end;
3460+ (* check off;: the module's index and slice checks left out; neither
3461+ word is reserved *)
3462+ if (Scan.tok = Scan.sIdent) and (Scan.id = nameCheck) then
3463+ Scan.next;
3464+ if (Scan.tok # Scan.sIdent) or (Scan.id # nameOff) then return nil, expected("\"off\""); end;
3465+ Scan.next;
3466+ try expect(Scan.sSemicolon);
3467+ Item.setChecks(false);
3468+ end;
3469+ declarations(true);
3470+ if Scan.tok = Scan.sBegin then
3471+ if checkMode then
3472+ try skipBody();
3473+ else
3474+ try instancesFor(true);
3475+ line := Scan.curLine();
3476+ Scan.next;
3477+ bodyChunk := Chunk.newChunk(Chunk.secText, m^.sname, nameBody);
3478+ m^.body := bodyChunk;
3479+ Item.beginProc(tBodySig, nil);
3480+ deferSlot := 0;
3481+ curResult := nil;
3482+ Gen.enterBody(bodyChunk, line);
3483+ stray := false; elseIf := false;
3484+ try statements();
3485+ Chunk.noteLine(Scan.curLine(), Scan.curCol());
3486+ try expect(Scan.sEnd);
3487+ try Gen.endProc(bodyChunk, false);
3488+ end;
3489+ else
3490+ try expect(Scan.sEnd);
3491+ end;
3492+ if (Scan.tok # Scan.sIdent) or (Scan.id # n) then
3493+ return nil, endMissing(Scan.missingPos(), say2("expected {}, found {}", nameOf(n), Scan.found()));
3494+ end;
3495+ Scan.next;
3496+ if Scan.tok # Scan.sPeriod then return nil, expected("\".\""); end;
3497+ o := m^.first;
3498+ while o # nil do
3499+ if (o^.cls = Sym.oProc) and o^.fwd then
3500+ Diag.error(Scan.tokPos(), say1("{} is declared forward but never defined", nameOf(o^.name)));
3501+ end;
3502+ o := o^.chain;
3503+ end;
3504+ if (Diag.errors = 0) and not checkOnly then warnings(m, firstDrop); end;
3505+ numDrops := firstDrop;
3506+ if Diag.errors > 0 then Diag.finish(); end; (* a module with errors stops the compiler after it *)
3507+ Sym.closeScope();
3508+ m^.done := true;
3509+ if not checkOnly then
3510+ DEC(numPending);
3511+ if lastModule = nil then firstModule := m; else lastModule^.next := m; end;
3512+ lastModule := m;
3513+ end;
3514+ Sym.setCurModule(oldMod); checkMode := oldCheck; Chunk.setCurFile(oldPath); Item.setChecks(oldChecks);
3515+ Sym.restoreScopes(d, saved[0..Sym.MaxDepth]);
3516+ Scan.restoreScan(st);
3517+ return m, nil;
3518+end;
3519+
3520+(* The interface check: b must export just what a does. *)
3521+proc compareIface(a, b: PModule);
3522+var o, q: PObj;
3523+begin
3524+ o := a^.first;
3525+ while o # nil do
3526+ if o^.exported then
3527+ q := Sym.find(b^.scope, o^.name);
3528+ if (q = nil) or not q^.exported or (Sym.fingerprint(o) # Sym.fingerprint(q)) then
3529+ Diag.fatal(Diag.say("{}: {} isn't exported as in {}", [Fmt.str(b^.path), Fmt.str(nameOf(o^.name)), Fmt.str(a^.path)]));
3530+ end;
3531+ end;
3532+ o := o^.chain;
3533+ end;
3534+ q := b^.first;
3535+ while q # nil do
3536+ o := Sym.find(a^.scope, q^.name);
3537+ if q^.exported and ((o = nil) or not o^.exported) then
3538+ Diag.fatal(Diag.say("{}: {} isn't exported by {}", [Fmt.str(b^.path), Fmt.str(nameOf(q^.name)), Fmt.str(a^.path)]));
3539+ end;
3540+ q := q^.chain;
3541+ end;
3542+end;
3543+
3544+(* Reads every other file of module n in dir, and checks its interface
3545+ against m, compiled from the file named chosen. *)
3546+proc checkSiblings(dir, chosen: []U8; n: INT; m: PModule; args: Sym.Args): ERROR;
3547+var
3548+ dp: Sys.Dir; e, prefix: []U8; i, numOthers: INT; more: BOOL; sib: PModule;
3549+ others: [32][]U8;
3550+begin
3551+ prefix := say1("{}.", nameOf(n));
3552+ numOthers := 0;
3553+ if Sys.openDir(ADR(dp), dir) # 0 then return nil; end;
3554+ repeat
3555+ e, more := Sys.nextEntry(ADR(dp));
3556+ if not more then break; end;
3557+ if (LEN(e) > 4) and Str.hasPrefix(e, prefix) and (e[LEN(e) - 4..LEN(e)] = ".raz")
3558+ and (e # chosen) and (numOthers < 32) then
3559+ others[numOthers] := keep(e);
3560+ INC(numOthers);
3561+ end;
3562+ until false;
3563+ Sys.closeDir(ADR(dp));
3564+ for i := 0 to numOthers - 1 do
3565+ sib := try compileFile(say2("{}/{}", dir, others[i]), n, args, true);
3566+ compareIface(m, sib);
3567+ end;
3568+ return nil;
3569+end;
3570+
3571+(* The directories searched for modules, in order, from -1 to numInc *)
3572+proc searchDir(i: INT): []U8;
3573+begin
3574+ if i = -1 then return mainDir; end;
3575+ if i = numInc then return libDir; end;
3576+ return incDirs[i];
3577+end;
3578+
3579+(* The file of module n in dir that suffix j says: Name.linux-x86_64.raz
3580+ for a file of this target alone, and so on to Name.raz *)
3581+proc fileName(n, j: INT): []U8;
3582+begin
3583+ return Diag.say("{}{}.raz", [Fmt.str(nameOf(n)), Fmt.str(Suffixes[j])]);
3584+end;
3585+
3586+proc moduleFile(n: INT): ([]U8, []U8, BOOL);
3587+var i, j: INT; dir, f: []U8;
3588+begin
3589+ for i := -1 to numInc do
3590+ dir := searchDir(i);
3591+ for j := 0 to 3 do
3592+ f := fileName(n, j);
3593+ if exists(say2("{}/{}", dir, f)) then return dir, f, true; end;
3594+ end;
3595+ end;
3596+ return "", "", false;
3597+end;
3598+
3599+(* A program has one module of each name: module n, found as dir/f,
3600+ must have no files in a later directory, unless dir/f is a link to
3601+ one of them, which chooses it (report, section 3) *)
3602+proc checkOneModule(n: INT; dir, f: []U8; at: Diag.Pos): ERROR;
3603+var
3604+ i, j, dev, ino, mineDev, mineIno: INT; past, chosen: BOOL; g, files, others: []U8;
3605+begin
3606+ mineDev, mineIno := identity(say2("{}/{}", dir, f));
3607+ others := "";
3608+ past := false;
3609+ for i := -1 to numInc do
3610+ if past then
3611+ files := "";
3612+ chosen := false;
3613+ for j := 0 to 3 do
3614+ g := say2("{}/{}", searchDir(i), fileName(n, j));
3615+ if exists(g) then
3616+ files := say2("{} and {}", files, Diag.shownPath(g));
3617+ dev, ino := identity(g);
3618+ chosen := chosen or ((dev = mineDev) and (ino = mineIno));
3619+ end;
3620+ end;
3621+ if not chosen then others := say2("{}{}", others, files); end;
3622+ end;
3623+ past := past or (searchDir(i) = dir);
3624+ end;
3625+ if LEN(others) = 0 then return nil; end;
3626+ Diag.error(at, say3("module {} is in {}{}", nameOf(n), Diag.shownPath(say2("{}/{}", dir, f)), others));
3627+ Diag.help("a program has one module of each name; a symbolic link to one of these files chooses it");
3628+ return Scan.Failed;
3629+end;
3630+
3631+proc importModule(name: INT; args: Sym.Args): (PModule, ERROR);
3632+var m: PModule; i: INT; dir, f, where: []U8; found: BOOL;
3633+begin
3634+ m := findModule(name, args);
3635+ if m # nil then return m, nil; end;
3636+ for i := 0 to numPending - 1 do
3637+ if isModule(pending[i], name, args) then
3638+ return nil, Scan.markAt(args.at, say1("{} imports itself", nameOf(name)));
3639+ end;
3640+ end;
3641+ dir, f, found := moduleFile(name);
3642+ if not found then
3643+ Diag.error(args.at, say1("can't find module {}", nameOf(name)));
3644+ where := Diag.shownPath(searchDir(-1));
3645+ for i := 0 to numInc do where := say2("{}, {}", where, Diag.shownPath(searchDir(i))); end;
3646+ Diag.help(say2("looked for {}.raz in {}", nameOf(name), where));
3647+ return nil, Scan.Failed;
3648+ end;
3649+ try checkOneModule(name, dir, f, args.at);
3650+ m := try compileFile(say2("{}/{}", dir, f), name, args, false);
3651+ try checkSiblings(dir, f, name, m, args);
3652+ return m, nil;
3653+end;
3654+
3655+proc addImport(m, im: PModule);
3656+var imp: ^Sym.Import;
3657+begin
3658+ NEW(imp, Heap.heap);
3659+ imp^.home := im;
3660+ imp^.next := m^.imports;
3661+ m^.imports := imp;
3662+end;
3663+
3664+(* Makes the instance that deferred[i] imports: its arguments are read
3665+ where the import wrote them, and must be declared by now. Compiling
3666+ the instance comes in the middle of a declaration, so what that
3667+ declaration has under way is kept aside meanwhile. *)
3668+proc makeInstance(i: INT; at: Diag.Pos): ERROR;
3669+var
3670+ d: Deferred; st: Scan.State; args: Sym.Args; types, exported, ext, wasQuiet: BOOL; nf, nd: INT;
3671+ ft: [MaxFwd]PType; fp: [MaxFwd]Diag.Pos; decl: [MaxNames]INT;
3672+begin
3673+ d := deferred[i];
3674+ DEC(numDeferred);
3675+ deferred[i] := deferred[numDeferred];
3676+ Scan.saveScan(st);
3677+ Scan.restoreScan(d.args);
3678+ args.n := 0;
3679+ making := true; useAt := at;
3680+ try parseArgs(args, nameOf(d.mname));
3681+ making := false;
3682+ Scan.restoreScan(st);
3683+ args.at := d.at;
3684+ types := inTypes; exported := declExported; ext := inExtern; wasQuiet := Diag.quiet;
3685+ nf := numFwd; ft := fwdTypes; fp := fwdPos; nd := numDeclaring; decl := declaring;
3686+ d.o^.home := try importModule(d.mname, args);
3687+ inTypes := types; declExported := exported; inExtern := ext; Diag.setQuiet(wasQuiet);
3688+ numFwd := nf; fwdTypes := ft; fwdPos := fp; numDeclaring := nd; declaring := decl;
3689+ addImport(Sym.curModule, d.o^.home);
3690+ return nil;
3691+end;
3692+
3693+proc firstUse(o: PObj; at: Diag.Pos): ERROR;
3694+var i: INT;
3695+begin
3696+ for i := 0 to numDeferred - 1 do
3697+ if deferred[i].o = o then return makeInstance(i, at); end;
3698+ end;
3699+ return Scan.Failed; (* its arguments had an error, already reported *)
3700+end;
3701+
3702+(* An instance can't be compiled in the middle of another procedure's
3703+ code, so before a procedure's code begins, from its "proc" on, or
3704+ the module body's, from its "begin" to the end of the file, this
3705+ reads ahead for the names of imports not yet made, and makes those. *)
3706+proc instancesFor(wholeRest: BOOL): ERROR;
3707+var st: Scan.State; d, i: INT; begun: BOOL;
3708+begin
3709+ if checkMode then return nil; end;
3710+ i := numDeferred - 1;
3711+ while (i >= 0) and (deferred[i].home # Sym.curModule) do DEC(i); end;
3712+ if i < 0 then return nil; end;
3713+ (* The procedure ends at the "end" that closes its first "begin": d
3714+ counts the words still open that "end" or "until" closes, and begun
3715+ says that begin was met, so that a record's end in its declarations
3716+ doesn't stop it. A forward or code procedure has no raz body to
3717+ read, so it stops at that word. The body reads to the end of the
3718+ file, as wholeRest says. *)
3719+ Scan.saveScan(st);
3720+ d := 0; begun := false;
3721+ repeat
3722+ match Scan.tok of
3723+ | sIdent:
3724+ for i := numDeferred - 1 to 0 by -1 do
3725+ if (deferred[i].home = Sym.curModule) and (deferred[i].o^.name = Scan.id) then
3726+ try makeInstance(i, Scan.tokPos());
3727+ end;
3728+ end;
3729+ | sBegin:
3730+ begun := begun or (d = 0);
3731+ INC(d);
3732+ | sIf, sWhile, sFor, sMatch, sRepeat, sRecord, sVariant: INC(d);
3733+ | sEnd, sUntil: DEC(d);
3734+ | else:
3735+ end;
3736+ if not wholeRest and (d = 0) and (begun or (Scan.tok = Scan.sForward) or (Scan.tok = Scan.sCode)) then break; end;
3737+ Scan.next;
3738+ until Scan.tok = Scan.sEof;
3739+ Scan.restoreScan(st);
3740+ return nil;
3741+end;
3742+
3743+(* The main module, from the file at path, and Rt, which every program
3744+ needs, first *)
3745+proc compileMain*(path: []U8): (PModule, ERROR);
3746+var base: []U8; i, n: INT; none: Sym.Args; m: PModule;
3747+begin
3748+ none.n := 0;
3749+ i := LEN(path);
3750+ while (i > 0) and (path[i - 1] # '/') do DEC(i); end;
3751+ if i = 0 then mainDir := "."; else mainDir := path[0..i - 1]; end;
3752+ base := path[i..LEN(path)];
3753+ i := 0;
3754+ while (i < LEN(base)) and (base[i] # '.') do INC(i); end;
3755+ base := base[0..i];
3756+ if LEN(base) = 0 then Diag.fatal(say1("no module in {}", path)); end;
3757+ n := internName(base);
3758+ none.at := Scan.tokPos();
3759+ if n # nameRt then _ := try importModule(nameRt, none); end;
3760+ m := findModule(n, none);
3761+ if m # nil then return m, nil; end;
3762+ return compileFile(path, n, none, false);
3763+end;
3764+
3765+begin
3766+ nameRt := internName("Rt");
3767+ nameFail := internName("fail");
3768+ nameAdr := internName("ADR");
3769+ nameBody := internName("body");
3770+ nameStatic := internName("static");
3771+ nameCheck := internName("check");
3772+ nameOff := internName("off");
3773+ tArgv := newPtr(newPtr(Sym.tU8, false), false);
3774+ tBodySig := Sym.newType(Sym.fProc, 8, 8);
3775+end Parse.

src/README.md (history) added +195 -0

@@ -0,0 +1,195 @@
1+# src: the compiler in raz
2+
3+The port of the Pascal compiler, the **seed** in `../seed/`, to raz.
4+`../PLAN.md`, "Self", says what it is for and the order of its units.
5+
6+One module to a seed unit, with the seed's name, written to the same
7+rules: plain code, each module opening with what it is, what it
8+depends on and what it leaves out. The seed is never edited from here.
9+
10+ make self # each unit against the seed's, on the same files
11+ make self-bench # the scanner's speed against the seed's
12+ make fixpoint # the seed builds self, that builds self, that builds it again
13+
14+`Chunk` and `Sym` have no input files to read, so each has a dumper
15+pair, `test/ChunkDump` and `test/SymDump`, that runs one fixed
16+pseudo-random script of calls on its side and prints all it made or
17+answered (`Sym` also ends, as an argument says, in the error of a name
18+declared twice or of too many scopes): the output, the messages and
19+the status must be the same. `Link` and `Elf` are tested by
20+`test/LinkDump`, which makes a program of chunks by a script and writes
21+it as a static, a dynamic and a stripped executable, which must be the
22+same file; `X64` by `test/X64Dump`, every encoder with operands from a
23+script, bytes, fixups and listing, and by `test/AsmDump` on the files
24+`test/genasm.py` makes: a long run of every instruction the assembler
25+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`.
42+
43+`Parse` and `Raz`, the last two units, are tested whole: the seed builds
44+`src/Raz.raz` into `build/self/raz.self`, and each compiler, run as
45+`build/cmp/raz` (a program holds the paths it was made from, and the
46+library is found beside the compiler), compiles the library, the
47+examples, the tools, `src/` itself, every test of `test/` and
48+`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.
51+`make self-bench` gives the speed of both.
52+
53+`make fixpoint` (`fixpoint.sh`) is the proof that the port is whole:
54+the seed builds `Raz.raz` (stage 1), stage 1 builds it (stage 2), and
55+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
58+`make bench` run on it. Each stage is built by the same command in the
59+same place, since a program holds the paths it was made from.
60+
61+`check.sh` builds a dumper for each side, `test/ScanDump.pas` over the
62+seed's units and `test/ScanDump.raz` over these, and has both read the
63+library, the examples, every test of the compiler and a file for each
64+message the scanner makes (`test/genlex.py`) and for hundreds of reals
65+that are hard to read exactly (`test/genreals.py`): the output, the
66+messages and the status must be the same.
67+
68+## What the port found
69+
70+Not the seed's to mend; for the owner to choose.
71+
72+- **Names.** An exported variable is read-only outside its module, so
73+ what the parser sets in the seed's `diag` and `scan` (`quiet`,
74+ `werror`, `recovery`, `skipping`) have setters. The `sbuf` array,
75+ which can't be sliced outside, is `strBytes`.
76+- **Going on after an error.** raz has no `setjmp`, and the seed's parser
77+ ends its errors in a jump back to the statement or declaration being
78+ read, which is how it reports up to 20 errors in a run. The language
79+ gained `try` (report 2026-10.20) for this: `Scan.mark` and the others
80+ show the error and return `Scan.Failed`, which the parser passes up
81+ with `try` to where it reads on. `test/Recover.raz` is the pattern.
82+- **`NO_COLOR` set to nothing.** `Sys.env` gives "" for a variable that
83+ is unset and for one that is empty, so the port reads the second as
84+ the first. no-color.org says a variable that is empty doesn't turn
85+ colour off, so the port is the one that follows it and the seed
86+ differs; no test depends on either.
87+- **Strings are slices.** A message is a `[]U8` made by `Diag.say`,
88+ which keeps what it makes: messages are made only to be shown. A name
89+ from `nameOf` stays valid, since names are kept in chunks that are
90+ never moved; the seed's was a copy.
91+- **Reserved words as names.** The seed's `code` (the text buffer of
92+ `Chunk`) is `text`; `module` (a record's, an import's) is `home`; an
93+ object's `link` is `chain`. A seed type `TName` is `Name`, and the
94+ procedures begin in lower case, as `Scan`'s do.
95+- **Errors in `Sym`.** `insert` (a name declared twice) and `openScope`
96+ (too many scopes) show the error and return `Scan.Failed`, as `mark`
97+ does, for the parser to pass up with `try`. `saveScopes` returns what
98+ the seed's `var d` gave.
99+- **Setters.** What other units set in `Chunk` has one each (`setLive`,
100+ `setAdr`, `setReals`, `setSaves`, `setCurFile`, and `rewindTo` for
101+ gen's `Redo` and `Rewind`), and `Sym` has `setCurModule`. `Scan.grab`
102+ is exported for the memory they all take.
103+- **No `continue`.** The seed's loops that skip to the next round
104+ (`MarkLive`, the line program, the assembler's statements) have the
105+ rest of the body in an `else`, or in a procedure of its own.
106+- **`X64`.** `code` of `Chunk` being reserved, its text is `Chunk.text`;
107+ `Say` and the rest of the encoder keep their names, in lower case.
108+ `ConstFn`, the parser's reader of a constant, returns an `ERROR` too,
109+ and `assemble` returns what it passes up. `mem` marks an offset beyond
110+ 32 bits and goes on, since an operand has nowhere to return an error
111+ to; the compile ends with the message shown. The listing's text is
112+ made by `Diag.say`, which keeps it, and only when `-S` asks for it.
113+- **`Link` and `Elf`.** What `raz.pas` set there has a setter each:
114+ `Link.setPlaces`, `Elf.needLib`, `noLibs`, `setMainPath`,
115+ `setStripped` and `X64.setListing`. The file is written by
116+ `Files.write` and made executable by `Sys.chmod`, in place of one
117+ `open` with mode 755 (which the umask would trim).
118+- **`Gen`.** The seed's `Mark` in the middle of a push or a check
119+ can't give an error back: `newEntry` (the stack's 256 places) and
120+ `check` (4,096 checks a procedure) show it and go on without doing
121+ what they couldn't, and the parser's `resetStack` makes the stack
122+ right again; `endProc` returns its error ("frame too big") and
123+ `codeProc` the assembler's. A `var` out of the seed became a result
124+ (`topConst`, `operands`, `deferBegin`); the labels, which are chains
125+ that a call extends, stay `var`. `inPlace` has a setter. The seed's
126+ `Call` record is `CallInfo` (the procedure is `call`) and `TLink` is
127+ `Link`. A `match` on an enumeration takes one name to an arm, and a
128+ set holds at most 64 names, so `Scan.Sym` (over 64) has none: the
129+ seed's sets of its names are chains of `=`.
130+- **`Item`.** The seed's `Mark` ended in a jump, so here every
131+ routine that can find an error returns an `ERROR` as its last result
132+ and the ones that call it pass it up with `try`; `Item` shows the
133+ message and returns what the seed jumped out of, so a script that
134+ goes on after an error sees the same state. The seed's `Mismatch` of
135+ two operands is `mismatchOps`, `demoted` and `checks` have setters,
136+ and `matchBegin`, `toSlot` and `errorChunk` return their value and
137+ the error. `op2` has a parameter it never read, now `_L`. A message
138+ is made by `Diag.say` from strings, with no `shortstring` to add up.
139+ A `Mark` with no place is at the scanner's, as in the seed.
140+- **No `const` parameter.** The seed's `const x: TItem` is a value
141+ parameter here, so an item of about 130 bytes is copied at each call
142+ of `what`, `adrOf`, `notValue` and the others. The result is the
143+ same; whether the compiler built from this is slower for it is for
144+ the speed test of step 4 to say. A `const` parameter (a hint that
145+ the callee won't change it, so that the caller may pass its address)
146+ would be a language change: it goes on the wish list.
147+- **`Parse` and the seed's jumps.** The seed's `Guard`, `setjmp` and
148+ `longjmp` are `guard`, a record of what to put back, and the `ERROR`
149+ that comes up through `try` to the statement or declaration that is
150+ the recovery point (`statement`, `declaration`), which looks at it,
151+ puts the state back (`restore`) and skips ahead, as the seed does.
152+ `giveUp`, the seed's `GiveUp`, returns the error on to the next one,
153+ or ends the compile if there is none (`guards` counts them). A routine
154+ that can't fail has no `ERROR` (`declarations`, `declaration`). The
155+ seed's nested procedures (`ChooseRegs`'s three) are procedures of the
156+ module with its candidates in variables. `defer` and `module` being
157+ words, the seed's `Defer` is `deferStatement`. A message is made
158+ from strings with `Diag.say`, which has no shortstring to add up to.
159+ `Scan.skipping` is exported to be read, and `Scan.strWithZero` gives
160+ `Item.makeStr` a pointer to a string that may be empty: the seed's
161+ `@sbuf` indexed nothing, and `ADR(Scan.strBytes()[0])`, which the
162+ port of `Item` had, stopped on `""`.
163+- **`Raz`.** The program is `proc main*: INT`. Where it is, for the
164+ library beside it, it reads from `/proc/self/exe` as FPC's `ParamStr(0)`
165+ does: `Files.arg(0)` is what the shell was typed, and `./raz` made the
166+ library `./lib`, so the same program held other paths in its file.
167+ `raz run` writes the memfd with `Elf.writeElf` and executes it with
168+ the system call, `execve`, which `Sys` has no procedure for. The
169+ version is the module `Version`, which `check.sh` makes in
170+ `build/self/` from `build/version.inc`, as the seed's `{$I}` is.
171+ Two names of a file, for a module found in two places, are told by
172+ the device and inode `SYSCALL` `stat` gives, which `Sys.info` lacks.
173+- **Sets of `Scan.Sym`.** It has 76 names and a set holds 64, so the
174+ operators a rule names are chains of `=` or the helpers `oneOf` and
175+ `isRel`. (A `match` arm with several names, which the seed's `case`
176+ has, was added to the report for this: 2026-10.21.)
177+- **Strings made by the compiler.** A joined string (`"a" + "b"`) and
178+ an error's text are built in memory from `Scan.grab`, which is never
179+ freed, in place of `GetMem` and `FreeMem`; the compiler runs once.
180+- **No bit cast.** A real's bits and back go through a pointer.
181+- **Speed.** On the 348,025 lines of `test/genbench.py`, 7.6 MB, the
182+ seed's scanner takes 75 ms and this one 74. It took 121 at first.
183+ What closed the gap, in the source: a byte loop in place of the slice
184+ comparison `a[0..n] = b[0..n]` (97 ms), a 256-entry table for the
185+ bytes of a name (84), and one for the symbols that are a byte each
186+ (75). What is left for the code generator, which would help every
187+ module: the slice comparison is slower than the loop it stands for.
188+ On the whole compiler, the same 348,025 lines take 427 ms with the
189+ seed's and 770 with this one (452,000 lines a second, over the 400,000
190+ the budget wants): `Scan.tokPos`, a record of three words returned
191+ through a pointer, is 9% of it, and the rest is spread thin; the
192+ `const` parameter of `Item` isn't what stands out.
193+ (The seed's `match` on an integer was a chain of compares, each
194+ loading the selector from the frame and jumping over a `jmp`, where
195+ FPC makes a jump table; now it makes one too.)

src/Raz.raz (history) added +273 -0

@@ -0,0 +1,273 @@
1+(* Raz: the command line.
2+
3+ raz [-I dir]... [-o file] [-Werror] [-S] Main.raz
4+ raz run [-I dir]... Main.raz [arg]...
5+ raz --version
6+
7+ Compiles the main module and every module it imports, writes the
8+ entry point, links what it reaches, and writes the executable: by
9+ default the main module's file without its .raz; with -S, it lists
10+ the main module's code instead. raz run writes it to a memfd
11+ instead, a file that lives only in memory, and executes it in raz's
12+ place with the arguments after Main.raz, so its status is the
13+ program's; its argv[0] is Main.raz.
14+
15+ The program starts by saving argc and argv, runs every module's body
16+ (those of the modules the program imports, imported modules first),
17+ then the main module's main, and ends with Rt.exit and main's
18+ status. A static program does this from its entry point. One that
19+ uses C starts through the C library, __libc_start_main, which sets
20+ C up and calls this as C's main; first it gives Rt C's exit, which
21+ Rt.exit then ends the program with.
22+
23+ Depends on: everything else, and Version, a module the build makes
24+ (build/self/Version.raz) from what git describe says, as the seed's
25+ build/version.inc is.
26+ Leaves out: the work itself; the other units compile, link and
27+ write, and this only reads the command line and runs them in order. *)
28+module Raz;
29+import Sys, Out, Version, Files, Fmt, Diag, Scan, Sym, Chunk, X64, Gen, Parse, Link, Elf;
30+
31+const
32+ Report = "2026-10.21"; (* the version of doc/raz.md it follows *)
33+ MemfdCreate = 319; (* the system call *)
34+ MfdCloexec = 1; (* an ELF still executes: the kernel opens it first *)
35+ Execve = 59;
36+
37+var
38+ links: [4]Gen.Link;
39+ numLinks: INT;
40+
41+proc say1(f, a: []U8): []U8;
42+begin
43+ return Diag.say(f, [Fmt.str(a)]);
44+end;
45+
46+(* The number of the name s *)
47+proc internStr(s: []U8): INT;
48+begin
49+ return Scan.intern(ADR(s[0]), LEN(s));
50+end;
51+
52+(* The modules the program uses: the main module, Rt, and every module
53+ they import. A module read only for the interface check is not. *)
54+proc use(m: ^Sym.Module);
55+var i: ^Sym.Import;
56+begin
57+ if m^.used then return; end;
58+ m^.used := true;
59+ i := m^.imports;
60+ while i # nil do
61+ use(i^.home);
62+ i := i^.next;
63+ end;
64+end;
65+
66+(* Whether the program uses C: if so, the libraries it needs go to
67+ Elf, the C library first. *)
68+proc usesC: BOOL;
69+var m, st, c: ^Sym.Module; l: ^Sym.Lib;
70+begin
71+ st := nil; c := nil;
72+ Elf.noLibs();
73+ _ := Elf.needLib(internStr("libc.so.6"));
74+ m := Parse.firstModule;
75+ while m # nil do
76+ if m^.used and m^.linkStatic then st := m; end;
77+ if m^.used and m^.usesC then c := m; end;
78+ l := m^.libs;
79+ while m^.used and (l # nil) do
80+ if not Elf.needLib(l^.name) then Diag.fatal("more than 32 libraries"); end;
81+ l := l^.next;
82+ end;
83+ m := m^.next;
84+ end;
85+ if (st # nil) and (c # nil) then
86+ Diag.fatal(Diag.say("{} says link static, but {} uses C", [Fmt.str(Scan.nameOf(st^.name)), Fmt.str(Scan.nameOf(c^.name))]));
87+ end;
88+ if c = nil then Elf.noLibs(); end;
89+ return c # nil;
90+end;
91+
92+(* What raz -h says *)
93+proc usage;
94+begin
95+ Out.str("usage: raz [option]... Main.raz compiles Main.raz and the modules it imports\n");
96+ Out.str(" raz run [option]... Main.raz [arg]... compiles it and runs it, with the args\n");
97+ Out.str("options:\n");
98+ Out.str(" -o file the program's file, Main without .raz if left out\n");
99+ Out.str(" -I dir looks for imported modules in dir too, after Main.raz's own\n");
100+ Out.str(" -Werror a warning counts as an error\n");
101+ Out.str(" -S lists the main module's code, under each line of source\n");
102+ Out.str(" -s strips symbols, line numbers, the places a failure is told\n");
103+ Out.str(" by and the profiler: a failure says only its address\n");
104+ Out.str(" -noprofile leaves out the profiler, which RAZ_PROFILE turns on\n");
105+ Out.str(" -h, --help says this\n");
106+ Out.str(" --version says the version, and the report it follows\n");
107+ Out.str("see raz(1), and the report, doc/raz.md\n");
108+ Out.flush();
109+end;
110+
111+proc rtObj(rt: ^Sym.Module; n: []U8): ^Sym.Obj;
112+var o: ^Sym.Obj;
113+begin
114+ o := Sym.find(rt^.scope, internStr(n));
115+ if o = nil then Diag.fatal(say1("Rt has no {}", n)); end;
116+ return o;
117+end;
118+
119+(* Rt is given the address of chunk, in its variable v *)
120+proc addLink(chunk: INT; v: ^Sym.Obj);
121+begin
122+ links[numLinks].chunk := chunk;
123+ links[numLinks].into := v^.chunk;
124+ INC(numLinks);
125+end;
126+
127+(* s as a C string, in memory that is never freed *)
128+proc cstr(s: []U8): ^U8;
129+var p: ^U8;
130+begin
131+ p := Scan.grab(LEN(s) + 1);
132+ if LEN(s) > 0 then COPY(p[0..LEN(s)], s); end;
133+ p[LEN(s)] := 0;
134+ return p;
135+end;
136+
137+proc main*: INT;
138+var
139+ path, outPath, s: []U8; dir: []U8;
140+ i, first, entry, fd, last, errno: INT;
141+ m, rt: ^Sym.Module; mainObj: ^Sym.Obj;
142+ run, noProfile, listing: BOOL; err: ERROR;
143+begin
144+ path := "";
145+ outPath := "";
146+ noProfile := false;
147+ listing := false;
148+ run := (ARGC() >= 2) and (Files.arg(1) = "run");
149+ if run then i := 2; else i := 1; end;
150+ while i < ARGC() do
151+ s := Files.arg(i);
152+ if s = "-I" then
153+ INC(i);
154+ if Parse.numInc > 15 then Diag.fatal("more than 16 -I directories"); end;
155+ Parse.addIncDir(Files.arg(i));
156+ elsif s = "-o" then
157+ INC(i);
158+ outPath := Files.arg(i);
159+ elsif s = "-Werror" then
160+ Diag.setWerror(true);
161+ elsif s = "-S" then
162+ listing := true;
163+ X64.setListing(true);
164+ elsif s = "-s" then
165+ Elf.setStripped(true);
166+ elsif s = "-noprofile" then
167+ noProfile := true;
168+ elsif (s = "-h") or (s = "--help") then
169+ usage();
170+ return 0;
171+ elsif s = "--version" then
172+ Out.str(Diag.say("raz {}, report {}\n", [Fmt.str(Version.Text), Fmt.str(Report)]));
173+ Out.flush();
174+ return 0;
175+ elsif (LEN(s) > 0) and (s[0] = '-') then
176+ Diag.fatal(say1("unknown option {}", s));
177+ else
178+ path := s;
179+ first := i;
180+ if run then break; end; (* the rest are the program's *)
181+ end;
182+ INC(i);
183+ end;
184+ if LEN(path) = 0 then
185+ usage();
186+ return 1;
187+ end;
188+ if run and (LEN(outPath) > 0) then Diag.fatal("raz run takes no -o"); end;
189+ (* where raz is, as the system says, for the library beside it *)
190+ dir, errno := Sys.readLink("/proc/self/exe");
191+ if errno # 0 then dir := Files.arg(0); end;
192+ i := LEN(dir);
193+ while (i > 0) and (dir[i - 1] # '/') do DEC(i); end;
194+ if i = 0 then Parse.setLibDir("lib"); else Parse.setLibDir(say1("{}lib", dir[0..i])); end;
195+ if LEN(outPath) = 0 then
196+ outPath := path;
197+ last := LEN(outPath);
198+ if (last >= 4) and (outPath[last - 4..last] = ".raz") then
199+ outPath := outPath[0..last - 4];
200+ else
201+ outPath := say1("{}.out", outPath);
202+ end;
203+ end;
204+
205+ m, err := Parse.compileMain(path);
206+ if err # nil then
207+ Diag.finish();
208+ return 1;
209+ end;
210+ if Diag.errors > 0 then Diag.finish(); end;
211+
212+ use(m);
213+ rt := Parse.firstModule;
214+ while (rt # nil) and (Scan.nameOf(rt^.name) # "Rt") do rt := rt^.next; end;
215+ if rt # nil then use(rt); end;
216+
217+ mainObj := Sym.find(m^.scope, internStr("main"));
218+ if mainObj # nil then
219+ if (mainObj^.cls # Sym.oProc) or not mainObj^.exported then
220+ Diag.error(mainObj^.pos, "main must be an exported procedure");
221+ elsif (mainObj^.typ^.len # 0) or ((mainObj^.typ^.base # nil) and (mainObj^.typ^.base # Sym.tInt)) then
222+ Diag.error(mainObj^.pos, "main must be proc main* or proc main*: INT");
223+ end;
224+ if Diag.errors > 0 then Diag.finish(); end;
225+ end;
226+ Diag.finish();
227+
228+ if rt = nil then Diag.fatal("can't find module Rt"); end;
229+ (* what Rt is given: the places, which the linker makes, for Rt to say
230+ where a failed check or a signal was (place), and the calls under
231+ way then (calls); and the profiler, which needs them too. raz -s
232+ gives none, -noprofile no profiler. *)
233+ numLinks := 0;
234+ if not Elf.stripped then
235+ Link.setPlaces(Chunk.newChunk(Chunk.secRodata, -1, -1));
236+ Chunk.setData(Link.placesChunk, nil, 0, 8);
237+ addLink(Link.placesChunk, rtObj(rt, "places"));
238+ addLink(rtObj(rt, "calls")^.chunk, rtObj(rt, "teller"));
239+ addLink(rtObj(rt, "place")^.chunk, rtObj(rt, "placer"));
240+ if not noProfile then addLink(rtObj(rt, "startProfile")^.chunk, rtObj(rt, "profiler")); end;
241+ end;
242+ entry := Gen.entryPoint(usesC(), Parse.firstModule, mainObj, rtObj(rt, "cExit")^.chunk,
243+ rtObj(rt, "exit")^.chunk, links[0..numLinks], numLinks);
244+
245+ Link.markLive(entry);
246+ if not Parse.HasReals then
247+ for i := 0 to Chunk.numChunks - 1 do
248+ if Chunk.chunks[i].live and Chunk.chunks[i].reals then
249+ Diag.error(Chunk.chunks[i].realsAt, "this target has no reals");
250+ end;
251+ end;
252+ end;
253+ if Diag.errors > 0 then Diag.finish(); end;
254+ if listing then
255+ X64.list(m^.sname);
256+ return 0;
257+ end;
258+
259+ Elf.setMainPath(path);
260+ if run then
261+ (* argv from Main.raz on is the program's, ending in nil as it must *)
262+ fd := SYSCALL(MemfdCreate, cstr("raz"), MfdCloexec);
263+ if fd < 0 then Diag.fatal("can't create a memfd"); end;
264+ outPath := Diag.say("/proc/self/fd/{}", [Fmt.int(fd)]);
265+ Elf.writeElf(outPath, entry);
266+ _ := SYSCALL(Execve, cstr(outPath), ARGV() + first, ARGV() + (ARGC() + 1));
267+ Diag.fatal(say1("can't run {}", path));
268+ end;
269+ Elf.writeElf(outPath, entry);
270+ return 0;
271+end;
272+
273+end Raz.

src/Scan.raz (history) added +1002 -0

@@ -0,0 +1,1002 @@
1+(* Scan: the scanner.
2+
3+ Reads a raz source file and hands the parser one symbol at a time:
4+ reserved words, identifiers, numbers, characters, strings and
5+ operators. Identifiers are interned, so that the rest of the compiler
6+ compares names as small integers. The scanner also says where the
7+ current symbol is, for messages.
8+
9+ Depends on: Sys, to read files; Diag, to report errors.
10+ Leaves out: recovery from errors in the text itself, such as a string
11+ not closed: the first such error stops the compiler. The parser goes
12+ on after its own errors: mark and the others report one and give
13+ back Failed, which it passes up with try to where it can read on. *)
14+module Scan;
15+import Sys, Heap, Mem, Fmt, Str, Diag;
16+
17+type
18+ NamePtr = ^U8;
19+
20+ Sym* = (sNull, sIdent, sInt, sReal, sChar, sString,
21+ sPlus, sMinus, sTimes, sSlash, sEql, sNeq, sLss, sLeq, sGtr, sGeq,
22+ sBecomes, sColon, sSemicolon, sComma, sPeriod, sUpto, sEllipsis,
23+ sLparen, sRparen, sLbrak, sRbrak, sLbrace, sRbrace, sArrow, sAmp, sTilde, sBar,
24+ sBlank,
25+ (* the reserved words, in the order of words below *)
26+ sAnd, sBegin, sBreak, sBy, sCode, sConst, sDefer, sDiv, sDo, sElse,
27+ sElsif, sEnd, sExtern, sFor, sForward, sIf, sImport, sIn, sLink,
28+ sMatch, sMod, sModule, sNot, sOf, sOr, sPacked, sProc, sRecord,
29+ sRepeat, sReturn, sSet, sShl, sShr, sThen, sTo, sTry, sType, sUntil, sVar,
30+ sVariant, sVolatile, sWhile, sXor,
31+ sEof);
32+
33+ (* Where the scanner is. Importing a module compiles it in the middle
34+ of another, so the parser saves this and restores it afterwards. *)
35+ State* = record
36+ buf: ^U8;
37+ len, pos, line, lineStart: INT;
38+ tokPos, tokLine, tokLineStart: INT;
39+ prevEnd: INT; (* where the symbol before this one ends *)
40+ tok: Sym;
41+ ival: I64;
42+ rval: F64;
43+ id: INT;
44+ f: INT; (* the file, as Diag knows it *)
45+ end;
46+
47+const
48+ Failed*: ERROR = "reported"; (* an error has been shown: the parser returns it *)
49+ MaxIdent* = 63;
50+ MaxStr* = 65536;
51+ NumWords = 43;
52+ NumOps = 28;
53+ words: [NumWords][]U8 = [
54+ "and", "begin", "break", "by", "code", "const", "defer", "div", "do",
55+ "else", "elsif", "end", "extern", "for", "forward", "if", "import",
56+ "in", "link", "match", "mod", "module", "not", "of", "or", "packed",
57+ "proc", "record", "repeat", "return", "set", "shl", "shr", "then",
58+ "to", "try", "type", "until", "var", "variant", "VOLATILE", "while",
59+ "xor"];
60+ (* sPlus to sBlank *)
61+ ops: [NumOps][]U8 = [
62+ "+", "-", "*", "/", "=", "#", "<", "<=", ">", ">=",
63+ ":=", ":", ";", ",", ".", "..", "...",
64+ "(", ")", "[", "]", "{", "}", "^", "&", "~", "|", "_"];
65+ (* the operators that no longer one starts, so that one byte is the symbol *)
66+ alone = "+-*/#;,()[]{}^~";
67+ PoolChunk = 65536;
68+
69+var
70+ tok*: Sym; (* the current symbol *)
71+ ival*: I64; (* sInt, sChar: its value *)
72+ rval*: F64; (* sReal: its value *)
73+ id*: INT; (* sIdent: its name *)
74+ slen*: INT; (* sString: how many bytes *)
75+ sbuf: [MaxStr + 1]U8; (* sString: its bytes, then a zero *)
76+
77+ (* The parser is skipping what it has read once already, after an
78+ error, so slips in it aren't reported again. *)
79+ skipping*: BOOL;
80+
81+ (* Whether a byte may be in a name: a letter, a digit or _. A table,
82+ since the loop that reads a name asks it of every byte. *)
83+ nameChar: [256]BOOL;
84+
85+ (* The symbol a byte is by itself, as + is, or sNull: a table, since
86+ most symbols are of this kind and a match would test them one by one. *)
87+ single: [256]Sym;
88+
89+ cur: State; (* buf .. f; tok, ival, rval and id live above *)
90+
91+ (* The name table: every distinct identifier once, found through an
92+ open-addressed hash table. A name's bytes are in a chunk of memory
93+ that is never moved, so that nameOf can hand out a slice of them. *)
94+ chunk: ^U8; (* where names are put; chunkLeft bytes are left *)
95+ chunkLeft: INT;
96+ namePtr: ^NamePtr;
97+ nameLen, nameHash: ^INT;
98+ numNames, nameCap: INT;
99+ table: ^INT; (* name + 1, or 0 for an empty slot *)
100+ tableMask: INT;
101+
102+(* Exported variables can't be set from outside, so these do it. *)
103+proc setSkipping*(yes: BOOL);
104+begin
105+ skipping := yes;
106+end;
107+
108+(* The bytes of the string just read, without the zero after them *)
109+proc strBytes*: []U8;
110+begin
111+ return sbuf[0..slen];
112+end;
113+
114+(* The string just read and the zero after it, for the code that makes a
115+ chunk of it: an empty string has bytes to point at, though none to index *)
116+proc strWithZero*: ^U8;
117+begin
118+ return ADR(sbuf[0]);
119+end;
120+
121+(* Memory, or the end of the compile when there is none *)
122+proc grab*(size: INT): ^U8;
123+var p: ^U8;
124+begin
125+ p := Mem.alloc(Heap.heap, size, 8);
126+ if p = nil then Diag.fatal("out of memory"); end;
127+ return p;
128+end;
129+
130+(* p, which holds used bytes, moved to a block of size bytes *)
131+proc regrab*(p: ^U8; used, size: INT): ^U8;
132+var q: ^U8;
133+begin
134+ q := grab(size);
135+ COPY(q[0..used], p[0..used]);
136+ Mem.free(Heap.heap, p);
137+ return q;
138+end;
139+
140+(* n zeroed words *)
141+proc words64(n: INT): ^INT;
142+var p: ^INT; i: INT;
143+begin
144+ p := ^INT(grab(n * SIZE(INT)));
145+ for i := 0 to n - 1 do p[i] := 0; end;
146+ return p;
147+end;
148+
149+(* Names *)
150+
151+proc hash(p: ^U8; n: INT): INT;
152+var h: U32; i: INT;
153+begin
154+ h := 2166136261;
155+ for i := 0 to n - 1 do h := (h xor U32(p[i])) * 16777619; end;
156+ return INT(h & 7FFFFFFFH);
157+end;
158+
159+(* A table twice the size, and room for twice the names *)
160+proc grow;
161+var i, n, j: INT; ptrs: ^NamePtr; lens, hashes: ^INT;
162+begin
163+ Mem.free(Heap.heap, ^U8(table));
164+ tableMask := tableMask * 2 + 1;
165+ table := words64(tableMask + 1);
166+ for n := 0 to numNames - 1 do
167+ i := nameHash[n] & tableMask;
168+ while table[i] # 0 do i := (i + 1) & tableMask; end;
169+ table[i] := n + 1;
170+ end;
171+ j := nameCap * 2;
172+ ptrs := ^NamePtr(grab(j * SIZE(NamePtr)));
173+ lens := ^INT(grab(j * SIZE(INT)));
174+ hashes := ^INT(grab(j * SIZE(INT)));
175+ for n := 0 to numNames - 1 do
176+ ptrs[n] := namePtr[n];
177+ lens[n] := nameLen[n];
178+ hashes[n] := nameHash[n];
179+ end;
180+ Mem.free(Heap.heap, ^U8(namePtr));
181+ Mem.free(Heap.heap, ^U8(nameLen));
182+ Mem.free(Heap.heap, ^U8(nameHash));
183+ namePtr := ptrs;
184+ nameLen := lens;
185+ nameHash := hashes;
186+ nameCap := j;
187+end;
188+
189+(* Whether the n bytes at p and at q are the same *)
190+proc same(p, q: ^U8; n: INT): BOOL;
191+var i: INT;
192+begin
193+ for i := 0 to n - 1 do
194+ if p[i] # q[i] then return false; end;
195+ end;
196+ return true;
197+end;
198+
199+(* The number of the name of the n bytes at p; a new name gets the next *)
200+proc intern*(p: ^U8; n: INT): INT;
201+var h, i, k: INT;
202+begin
203+ h := hash(p, n);
204+ i := h & tableMask;
205+ while table[i] # 0 do
206+ k := table[i] - 1;
207+ if (nameHash[k] = h) and (nameLen[k] = n) and same(namePtr[k], p, n) then
208+ return k;
209+ end;
210+ i := (i + 1) & tableMask;
211+ end;
212+ if n > chunkLeft then
213+ chunk := grab(PoolChunk);
214+ chunkLeft := PoolChunk;
215+ end;
216+ COPY(chunk[0..n], p[0..n]);
217+ k := numNames;
218+ namePtr[k] := chunk;
219+ nameLen[k] := n;
220+ nameHash[k] := h;
221+ chunk := chunk + n;
222+ chunkLeft := chunkLeft - n;
223+ INC(numNames);
224+ table[i] := k + 1;
225+ if numNames * 2 > tableMask then grow; end;
226+ return k;
227+end;
228+
229+(* The name n, which stays as it is *)
230+proc nameOf*(n: INT): []U8;
231+begin
232+ return namePtr[n][0..nameLen[n]];
233+end;
234+
235+(* Errors *)
236+
237+(* The current symbol *)
238+proc tokPos*: Diag.Pos;
239+begin
240+ return {f: cur.f, a: cur.tokPos, b: cur.pos};
241+end;
242+
243+(* The place just after the symbol before the current one, where a
244+ missing symbol belongs *)
245+proc afterPrev*: Diag.Pos;
246+begin
247+ return {f: cur.f, a: cur.prevEnd, b: cur.prevEnd};
248+end;
249+
250+(* Where to say a symbol is missing: at the current symbol, unless it
251+ starts a later line than the symbol before it, which is more likely
252+ where the missing one belongs *)
253+proc missingPos*: Diag.Pos;
254+var i: INT; p: Diag.Pos;
255+begin
256+ p := tokPos();
257+ for i := cur.prevEnd to cur.tokPos - 1 do
258+ if cur.buf[i] = '\n' then p := afterPrev(); end;
259+ end;
260+ return p;
261+end;
262+
263+(* From the start of p to the end of the symbol before the current one:
264+ the whole of a construct that has just been read *)
265+proc spanFrom*(p: Diag.Pos): Diag.Pos;
266+begin
267+ p.b := cur.prevEnd;
268+ return p;
269+end;
270+
271+proc curLine*: INT;
272+begin
273+ return cur.tokLine;
274+end;
275+
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
278+ the distance. A column counts characters, as Diag's do. *)
279+proc lineCol*(a: INT): (INT, INT);
280+var i, line, start, col: INT;
281+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;
288+ end;
289+ col := 1;
290+ for i := start to a - 1 do
291+ if (cur.buf[i] & 0C0H) # 80H then INC(col); end;
292+ end;
293+ return line, col;
294+end;
295+
296+proc curCol*: INT;
297+var col: INT;
298+begin
299+ _, col := lineCol(cur.tokPos);
300+ return col;
301+end;
302+
303+(* An error at p, shown: the parser returns Failed, which try passes up
304+ to where it goes on. *)
305+proc markAt*(p: Diag.Pos; msg: []U8): ERROR;
306+begin
307+ Diag.error(p, msg);
308+ return Failed;
309+end;
310+
311+proc mark*(msg: []U8): ERROR;
312+begin
313+ return markAt(tokPos(), msg);
314+end;
315+
316+(* markAt, with a line of help after the message. *)
317+proc markHelp*(p: Diag.Pos; msg, hint: []U8): ERROR;
318+begin
319+ Diag.error(p, msg);
320+ Diag.help(hint);
321+ return Failed;
322+end;
323+
324+(* An error in the text at bytes a to b of the file being read, which
325+ stops the compiler: past it, the symbols can't be trusted. *)
326+proc markBytes(a, b: INT; msg: []U8);
327+begin
328+ Diag.setQuiet(false);
329+ Diag.error({f: cur.f, a: a, b: b}, msg);
330+ Diag.finish;
331+end;
332+
333+proc lexError(msg: []U8);
334+begin
335+ markBytes(cur.tokPos, cur.pos, msg);
336+end;
337+
338+(* The n characters at the scanner are how another language writes t:
339+ an error, but reading goes on as if t were written. *)
340+proc slip(n: INT; t: Sym; msg: []U8);
341+begin
342+ if not skipping then Diag.error({f: cur.f, a: cur.pos, b: cur.pos + n}, msg); end;
343+ INC(cur.pos, n);
344+ tok := t;
345+end;
346+
347+(* How an operator or reserved word is written, quoted, for messages. *)
348+proc symText*(s: Sym): []U8;
349+begin
350+ if (s >= sPlus) and (s <= sBlank) then
351+ return Diag.say("\"{}\"", [Fmt.str(ops[INT(s) - INT(sPlus)])]);
352+ end;
353+ return Diag.say("\"{}\"", [Fmt.str(words[INT(s) - INT(sAnd)])]);
354+end;
355+
356+(* The current symbol, for "expected ..., found ...": a name as it is,
357+ a literal by its kind, an operator or reserved word quoted. *)
358+proc found*: []U8;
359+begin
360+ match tok of
361+ | sIdent: return nameOf(id);
362+ | sInt: return "a number";
363+ | sReal: return "a number";
364+ | sChar: return "a character";
365+ | sString: return "a string";
366+ | sEof: return "the end of the file";
367+ | else: return symText(tok);
368+ end;
369+end;
370+
371+(* The current symbol is the first on its line: at the top level of a
372+ module, by the usual layout, so where reading can start again. *)
373+proc atLineStart*: BOOL;
374+begin
375+ return cur.tokPos = cur.tokLineStart;
376+end;
377+
378+(* The column the current symbol's line is indented to *)
379+proc indent*: INT;
380+var i: INT;
381+begin
382+ i := cur.tokLineStart;
383+ while (cur.buf[i] = ' ') or (cur.buf[i] = '\t') do INC(i); end;
384+ return i - cur.tokLineStart + 1;
385+end;
386+
387+(* Files *)
388+
389+(* Name n is a reserved word *)
390+proc reserved*(n: INT): BOOL;
391+begin
392+ return n < NumWords;
393+end;
394+
395+(* Reads the file at path to scan it; "" if it can, else why not *)
396+proc open*(path: []U8): []U8;
397+var fd, n, got, r, err: INT; info: Sys.Info;
398+begin
399+ info, err := Sys.info(path);
400+ if err = -2 then return "there is no such file"; end;
401+ if err = -13 then return "permission denied"; end;
402+ if err < 0 then return "it can't be opened"; end;
403+ if not info.file then return "it isn't a file"; end;
404+ fd := Sys.openRead(path);
405+ if fd = -2 then return "there is no such file"; end;
406+ if fd = -13 then return "permission denied"; end;
407+ if fd < 0 then return "it can't be opened"; end;
408+ n := INT(info.size);
409+ cur.buf := grab(n + 1);
410+ got := 0;
411+ while got < n do
412+ r := Sys.read(fd, cur.buf[got..n]);
413+ if r <= 0 then Diag.fatal(Diag.say("can't read {}", [Fmt.str(path)])); end;
414+ got := got + r;
415+ end;
416+ Sys.close(fd);
417+ cur.buf[n] := 0; (* the sentinel that ends every scan *)
418+ cur.len := n;
419+ cur.pos := 0;
420+ cur.line := 1;
421+ cur.lineStart := 0;
422+ cur.tokPos := 0;
423+ cur.tokLine := 1;
424+ cur.tokLineStart := 0;
425+ cur.f := Diag.addFile(path, cur.buf, n);
426+ return "";
427+end;
428+
429+proc saveScan*(var st: State);
430+begin
431+ st := cur;
432+ st.tok := tok;
433+ st.ival := ival;
434+ st.rval := rval;
435+ st.id := id;
436+end;
437+
438+proc restoreScan*(st: State);
439+begin
440+ cur := st;
441+ tok := st.tok;
442+ ival := st.ival;
443+ rval := st.rval;
444+ id := st.id;
445+end;
446+
447+(* UTF-8 *)
448+
449+(* Decodes the character at buf[pos], which is not ASCII, checking that
450+ it is well formed; returns its code point and moves pos past it. *)
451+proc utf8(var pos: INT): INT;
452+var b0, b1, n, i, cp: INT; lo, hi: INT;
453+begin
454+ b0 := INT(cur.buf[pos]);
455+ lo := 80H;
456+ hi := 0BFH;
457+ n := 0;
458+ cp := 0;
459+ match b0 of
460+ | 0C2H..0DFH: n := 1; cp := b0 & 1FH;
461+ | 0E0H: n := 2; lo := 0A0H;
462+ | 0E1H..0ECH, 0EEH, 0EFH: n := 2; cp := b0 & 0FH;
463+ | 0EDH: n := 2; cp := 0DH; hi := 9FH; (* no surrogates *)
464+ | 0F0H: n := 3; lo := 90H;
465+ | 0F1H..0F3H: n := 3; cp := b0 & 7;
466+ | 0F4H: n := 3; cp := 4; hi := 8FH; (* up to 10FFFFH *)
467+ | else:
468+ cur.tokPos := pos;
469+ lexError("invalid UTF-8");
470+ end;
471+ for i := 1 to n do
472+ b1 := INT(cur.buf[pos + i]);
473+ if (b1 < lo) or (b1 > hi) or (pos + i >= cur.len) then
474+ cur.tokPos := pos;
475+ lexError("bad UTF-8");
476+ end;
477+ cp := cp shl 6 | (b1 & 3FH);
478+ lo := 80H;
479+ hi := 0BFH;
480+ end;
481+ pos := pos + n + 1;
482+ return cp;
483+end;
484+
485+proc put(b: INT);
486+begin
487+ if slen >= MaxStr then
488+ lexError(Diag.say("a string holds at most {} bytes", [Fmt.int(MaxStr)]));
489+ end;
490+ sbuf[slen] := U8(b);
491+ INC(slen);
492+end;
493+
494+proc putUtf8(cp: INT);
495+begin
496+ if cp < 80H then
497+ put(cp);
498+ elsif cp < 800H then
499+ put(0C0H | cp shr 6); put(80H | cp & 3FH);
500+ elsif cp < 10000H then
501+ put(0E0H | cp shr 12); put(80H | cp shr 6 & 3FH); put(80H | cp & 3FH);
502+ else
503+ put(0F0H | cp shr 18); put(80H | cp shr 12 & 3FH);
504+ put(80H | cp shr 6 & 3FH); put(80H | cp & 3FH);
505+ end;
506+end;
507+
508+proc isDigit(c: U8): BOOL;
509+begin
510+ return (c >= '0') and (c <= '9');
511+end;
512+
513+proc isLetter(c: U8): BOOL;
514+begin
515+ return (c >= 'a') and (c <= 'z') or (c >= 'A') and (c <= 'Z') or (c = '_');
516+end;
517+
518+proc hexVal(c: U8): INT;
519+begin
520+ if isDigit(c) then return INT(c) - '0';
521+ elsif (c >= 'A') and (c <= 'F') then return INT(c) - 'A' + 10;
522+ elsif (c >= 'a') and (c <= 'f') then return INT(c) - 'a' + 10;
523+ end;
524+ return -1;
525+end;
526+
527+(* The text of the file from byte a up to but not including b *)
528+proc text(a, b: INT): []U8;
529+begin
530+ return Diag.source({f: cur.f, a: a, b: b});
531+end;
532+
533+(* One character of a character or string literal, at buf[pos]: its code
534+ point, or for \xHH, minus one minus the byte. *)
535+proc litChar(inString: BOOL): INT;
536+var c: U8; v, d, n, esc, digits: INT;
537+begin
538+ c := cur.buf[cur.pos];
539+ esc := cur.pos;
540+ v := 0;
541+ if c = '\\' then
542+ INC(cur.pos);
543+ c := cur.buf[cur.pos];
544+ INC(cur.pos);
545+ match c of
546+ | 'n': v := 10;
547+ | 't': v := 9;
548+ | 'r': v := 13;
549+ | '0': v := 0;
550+ | '\\', '\'', '"': v := INT(c);
551+ | 'x':
552+ if not inString then markBytes(esc, cur.pos, "\\x is only for strings"); end;
553+ d := hexVal(cur.buf[cur.pos]);
554+ n := hexVal(cur.buf[cur.pos + 1]);
555+ if (d < 0) or (n < 0) then markBytes(esc, cur.pos + 2, "\\x needs two hex digits"); end;
556+ INC(cur.pos, 2);
557+ v := -1 - (d * 16 + n);
558+ | 'u':
559+ if cur.buf[cur.pos] # '{' then markBytes(esc, cur.pos, "expected \"{\" after \\u"); end;
560+ INC(cur.pos);
561+ digits := cur.pos;
562+ v := 0;
563+ n := 0;
564+ while hexVal(cur.buf[cur.pos]) >= 0 do
565+ v := v * 16 + hexVal(cur.buf[cur.pos]);
566+ INC(n);
567+ INC(cur.pos);
568+ if n > 6 then markBytes(esc, cur.pos, "a code point has at most 6 hex digits"); end;
569+ end;
570+ if (n = 0) or (cur.buf[cur.pos] # '}') then
571+ markBytes(esc, cur.pos, "expected hex digits and \"}\" after \\u{");
572+ end;
573+ INC(cur.pos);
574+ if (v > 10FFFFH) or (v >= 0D800H) and (v <= 0DFFFH) then
575+ markBytes(esc, cur.pos, Diag.say("{} isn't a code point", [Fmt.str(text(digits, cur.pos - 1))]));
576+ end;
577+ | else:
578+ markBytes(esc, cur.pos, Diag.say("unknown escape \\{}", [Fmt.char(c)]));
579+ end;
580+ elsif c >= 80H then
581+ v := utf8(cur.pos);
582+ elsif (c < ' ') or (c = 127) then
583+ if inString then lexError("string not closed"); else lexError("character not closed"); end;
584+ else
585+ v := INT(c);
586+ INC(cur.pos);
587+ end;
588+ return v;
589+end;
590+
591+(* Symbols *)
592+
593+proc comment;
594+var depth, open: INT; c: U8;
595+begin
596+ depth := 1;
597+ open := cur.pos;
598+ INC(cur.pos, 2);
599+ repeat
600+ c := cur.buf[cur.pos];
601+ if c = 0 then
602+ if cur.pos >= cur.len then markBytes(open, open + 2, "comment not closed"); end;
603+ INC(cur.pos);
604+ elsif (c = '(') and (cur.buf[cur.pos + 1] = '*') then
605+ INC(depth);
606+ INC(cur.pos, 2);
607+ elsif (c = '*') and (cur.buf[cur.pos + 1] = ')') then
608+ DEC(depth);
609+ INC(cur.pos, 2);
610+ elsif c = '\n' then
611+ INC(cur.pos);
612+ INC(cur.line);
613+ cur.lineStart := cur.pos;
614+ elsif c >= 80H then
615+ _ := utf8(cur.pos);
616+ else
617+ INC(cur.pos);
618+ end;
619+ until depth = 0;
620+end;
621+
622+(* Reading a decimal real exactly: the F64 nearest to digits times 10 to
623+ an exponent, ties to the even one, which a library's reader doesn't
624+ promise. The number is a fraction of two big integers, num / den,
625+ scaled by 2^e until its whole part has 53 or 54 bits; that part and
626+ the remainder give the bits and the rounding. *)
627+type
628+ Big = record
629+ n: INT; (* words in use; 0 is zero *)
630+ w: [96]U32; (* least significant first *)
631+ end;
632+(* 96 words, 3072 bits, are plenty: a string holds at most 255
633+ digits, so readReal's den is at most 10^(330 + 255), about 2^1944,
634+ and num below 10^310; the shift that follows makes the larger one at
635+ most 54 bits longer than den, about 2000 bits in all. *)
636+
637+(* a := a * m + add *)
638+proc bigMul(var a: Big; m, add: U32);
639+var i: INT; c: U64;
640+begin
641+ c := U64(add);
642+ for i := 0 to a.n - 1 do
643+ c := U64(a.w[i]) * U64(m) + c;
644+ a.w[i] := U32(c);
645+ c := c shr 32;
646+ end;
647+ if c # 0 then
648+ a.w[a.n] := U32(c);
649+ INC(a.n);
650+ end;
651+end;
652+
653+proc bigShl(var a: Big; k: INT);
654+var i, ws, bits: INT;
655+begin
656+ if a.n = 0 then return; end;
657+ ws := k div 32;
658+ bits := k mod 32;
659+ a.w[a.n + ws] := 0;
660+ for i := a.n - 1 to 0 by -1 do
661+ if bits > 0 then a.w[i + ws + 1] := a.w[i + ws + 1] | (a.w[i] shr (32 - bits)); end;
662+ a.w[i + ws] := a.w[i] shl bits;
663+ end;
664+ for i := 0 to ws - 1 do a.w[i] := 0; end;
665+ INC(a.n, ws + 1);
666+ while (a.n > 0) and (a.w[a.n - 1] = 0) do DEC(a.n); end;
667+end;
668+
669+proc bigShr1(var a: Big);
670+var i: INT;
671+begin
672+ for i := 0 to a.n - 1 do
673+ a.w[i] := a.w[i] shr 1;
674+ if i + 1 < a.n then a.w[i] := a.w[i] | (a.w[i + 1] shl 31); end;
675+ end;
676+ while (a.n > 0) and (a.w[a.n - 1] = 0) do DEC(a.n); end;
677+end;
678+
679+(* -1, 0 or 1 as a is below, equal to or above b *)
680+proc bigCmp(a, b: Big): INT;
681+var i: INT;
682+begin
683+ if a.n # b.n then
684+ if a.n > b.n then return 1; end;
685+ return -1;
686+ end;
687+ for i := a.n - 1 to 0 by -1 do
688+ if a.w[i] # b.w[i] then
689+ if a.w[i] > b.w[i] then return 1; end;
690+ return -1;
691+ end;
692+ end;
693+ return 0;
694+end;
695+
696+(* a := a - b, b not above a *)
697+proc bigSub(var a: Big; b: Big);
698+var i: INT; d: I64;
699+begin
700+ d := 0;
701+ for i := 0 to a.n - 1 do
702+ d := d + I64(a.w[i]);
703+ if i < b.n then d := d - I64(b.w[i]); end;
704+ a.w[i] := U32(d);
705+ if d < 0 then d := -1; else d := 0; end; (* a borrow *)
706+ end;
707+ while (a.n > 0) and (a.w[a.n - 1] = 0) do DEC(a.n); end;
708+end;
709+
710+proc bigBits(a: Big): INT;
711+var t: U32; bits: INT;
712+begin
713+ if a.n = 0 then return 0; end;
714+ bits := (a.n - 1) * 32;
715+ t := a.w[a.n - 1];
716+ while t # 0 do
717+ INC(bits);
718+ t := t shr 1;
719+ end;
720+ return bits;
721+end;
722+
723+(* s is digits, a point, digits, and maybe E, a sign and digits. False if
724+ the value is past the largest F64; one below the smallest is 0. *)
725+proc readReal(s: []U8): (F64, BOOL);
726+var
727+ num, den, d: Big; i, digits, e, ex: INT; neg, half, sticky: BOOL;
728+ q, b: U64; x: F64; bits: ^F64;
729+begin
730+ num.n := 0;
731+ den.n := 1;
732+ den.w[0] := 1;
733+ digits := 0;
734+ e := 0;
735+ i := 0;
736+ while (i < LEN(s)) and (s[i] # 'E') do
737+ if s[i] = '.' then
738+ e := 1;
739+ else
740+ bigMul(num, 10, U32(INT(s[i]) - '0'));
741+ if num.n > 0 then INC(digits); end; (* counted from the first that isn't 0 *)
742+ if e > 0 then INC(e); end;
743+ end;
744+ INC(i);
745+ end;
746+ if e > 0 then e := 1 - e; end; (* minus the digits after the point *)
747+ ex := 0;
748+ neg := false;
749+ if i < LEN(s) then
750+ INC(i);
751+ neg := s[i] = '-';
752+ if (s[i] = '+') or (s[i] = '-') then INC(i); end;
753+ while i < LEN(s) do
754+ if ex < 100000 then ex := ex * 10 + INT(s[i]) - '0'; end;
755+ INC(i);
756+ end;
757+ end;
758+ if neg then ex := -ex; end;
759+ INC(e, ex);
760+ x := 0.0;
761+ if num.n = 0 then return x, true; end;
762+ if digits + e > 310 then return x, false; end; (* 10^310 is past every F64 *)
763+ if digits + e < -330 then return x, true; end; (* and 10^-330 below half the least *)
764+ for i := 1 to e do bigMul(num, 10, 0); end;
765+ for i := 1 to -e do bigMul(den, 10, 0); end;
766+ (* num / den 2^-e from 2^52 to 2^54, but not past the least exponent *)
767+ e := bigBits(num) - bigBits(den) - 53;
768+ if e < -1074 then e := -1074; end;
769+ if e < 0 then bigShl(num, -e); else bigShl(den, e); end;
770+ (* q, its whole part, by long division; num is left the remainder *)
771+ d := den;
772+ bigShl(d, 53);
773+ q := 0;
774+ for i := 53 to 0 by -1 do
775+ if bigCmp(num, d) >= 0 then
776+ bigSub(num, d);
777+ q := q | (U64(1) shl i);
778+ end;
779+ bigShr1(d);
780+ end;
781+ if q >= U64(1) shl 53 then (* a bit too many: it rounds *)
782+ half := (q & 1) # 0;
783+ sticky := num.n > 0;
784+ q := q shr 1;
785+ INC(e);
786+ else (* the remainder against half of den *)
787+ bigShl(num, 1);
788+ i := bigCmp(num, den);
789+ half := i >= 0;
790+ sticky := i > 0;
791+ end;
792+ if half and (sticky or ((q & 1) # 0)) then
793+ INC(q);
794+ if q = U64(1) shl 53 then
795+ q := q shr 1;
796+ INC(e);
797+ end;
798+ end;
799+ if e > 971 then return x, false; end;
800+ if q >= U64(1) shl 52 then
801+ b := U64(e + 1075) shl 52 | (q & (U64(1) shl 52 - 1));
802+ else
803+ b := q; (* below the least normal, e is -1074 *)
804+ end;
805+ bits := ^F64(ADR(b));
806+ return bits^, true;
807+end;
808+
809+proc number;
810+var start, i, d: INT; allDec, ok: BOOL; v: U64;
811+begin
812+ start := cur.pos;
813+ allDec := true;
814+ while isDigit(cur.buf[cur.pos]) or (cur.buf[cur.pos] >= 'A') and (cur.buf[cur.pos] <= 'F') do
815+ if cur.buf[cur.pos] > '9' then allDec := false; end;
816+ INC(cur.pos);
817+ end;
818+ if cur.buf[cur.pos] = 'H' then
819+ v := 0;
820+ for i := start to cur.pos - 1 do
821+ if v shr 60 # 0 then lexError(Diag.say("{} is too big for U64", [Fmt.str(text(start, cur.pos))])); end;
822+ v := v * 16 + U64(hexVal(cur.buf[i]));
823+ end;
824+ INC(cur.pos);
825+ tok := sInt;
826+ ival := I64(v); (* 16 digits are the bits of a 64-bit word *)
827+ elsif (cur.buf[cur.pos] = '.') and isDigit(cur.buf[cur.pos + 1]) then
828+ if not allDec then lexError("a decimal number has only the digits 0 to 9"); end;
829+ INC(cur.pos);
830+ while isDigit(cur.buf[cur.pos]) do INC(cur.pos); end;
831+ if cur.buf[cur.pos] = 'E' then
832+ INC(cur.pos);
833+ if (cur.buf[cur.pos] = '+') or (cur.buf[cur.pos] = '-') then INC(cur.pos); end;
834+ if not isDigit(cur.buf[cur.pos]) then lexError("expected a digit in the exponent"); end;
835+ while isDigit(cur.buf[cur.pos]) do INC(cur.pos); end;
836+ end;
837+ if cur.pos - start > 255 then lexError("a number has at most 255 characters"); end;
838+ rval, ok := readReal(cur.buf[start..cur.pos]);
839+ if not ok then lexError(Diag.say("{} is out of the range of F64", [Fmt.str(text(start, cur.pos))])); end;
840+ tok := sReal;
841+ else
842+ if not allDec then lexError("a hex number ends with H"); end;
843+ v := 0;
844+ for i := start to cur.pos - 1 do
845+ d := INT(cur.buf[i]) - '0';
846+ if v > (U64(9223372036854775807) - U64(d)) div 10 then
847+ lexError(Diag.say("{} is too big for I64", [Fmt.str(text(start, cur.pos))]));
848+ end;
849+ v := v * 10 + U64(d);
850+ end;
851+ tok := sInt;
852+ ival := I64(v);
853+ end;
854+ if nameChar[cur.buf[cur.pos]] then
855+ lexError("a name can't start with a digit");
856+ end;
857+end;
858+
859+(* Reads the next symbol *)
860+proc next*;
861+var c: U8; start, h, v, i: INT;
862+begin
863+ cur.prevEnd := cur.pos;
864+ repeat
865+ c := cur.buf[cur.pos];
866+ while (c = ' ') or (c = '\t') or (c = '\r') or (c = '\n') do
867+ if c = '\n' then
868+ INC(cur.line);
869+ cur.lineStart := cur.pos + 1;
870+ end;
871+ INC(cur.pos);
872+ c := cur.buf[cur.pos];
873+ end;
874+ if (c = '(') and (cur.buf[cur.pos + 1] = '*') then
875+ comment;
876+ c := ' ';
877+ end;
878+ until c # ' ';
879+ cur.tokPos := cur.pos;
880+ cur.tokLine := cur.line;
881+ cur.tokLineStart := cur.lineStart;
882+ if single[c] # sNull then
883+ INC(cur.pos);
884+ tok := single[c];
885+ return;
886+ end;
887+ match c of
888+ | '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
892+ lexError(Diag.say("a name has at most {} characters", [Fmt.int(MaxIdent)]));
893+ end;
894+ h := intern(cur.buf + start, cur.pos - start);
895+ if (cur.pos - start = 1) and (c = '_') then
896+ tok := sBlank;
897+ elsif h < NumWords then
898+ tok := Sym(INT(sAnd) + h);
899+ else
900+ tok := sIdent;
901+ id := h;
902+ end;
903+ | '0'..'9': number;
904+ | '\'':
905+ INC(cur.pos);
906+ if cur.buf[cur.pos] = '\'' then lexError("empty character"); end;
907+ v := litChar(false);
908+ if cur.buf[cur.pos] # '\'' then
909+ (* 'ab': several characters, as some languages write a string *)
910+ i := cur.pos;
911+ while (cur.buf[i] # '\'') and (cur.buf[i] # '\n') and (cur.buf[i] # 0) do INC(i); end;
912+ if cur.buf[i] = '\'' then
913+ markBytes(cur.tokPos, i + 1,
914+ Diag.say("a character is one character: the string is \"{}\"", [Fmt.str(text(cur.tokPos + 1, i))]));
915+ else
916+ lexError("character not closed");
917+ end;
918+ end;
919+ INC(cur.pos);
920+ tok := sChar;
921+ ival := I64(v);
922+ | '"':
923+ INC(cur.pos);
924+ slen := 0;
925+ while cur.buf[cur.pos] # '"' do
926+ v := litChar(true);
927+ if v < 0 then put(-1 - v); else putUtf8(v); end;
928+ end;
929+ INC(cur.pos);
930+ sbuf[slen] := 0;
931+ tok := sString;
932+ | '=':
933+ if cur.buf[cur.pos + 1] = '=' then
934+ slip(2, sEql, "comparing is written =, not ==");
935+ else
936+ INC(cur.pos);
937+ tok := sEql;
938+ end;
939+ | '&':
940+ if cur.buf[cur.pos + 1] = '&' then
941+ slip(2, sAnd, "\"and\" is written and, not &&");
942+ else
943+ INC(cur.pos);
944+ tok := sAmp;
945+ end;
946+ | '<':
947+ INC(cur.pos);
948+ if cur.buf[cur.pos] = '=' then INC(cur.pos); tok := sLeq; else tok := sLss; end;
949+ | '>':
950+ INC(cur.pos);
951+ if cur.buf[cur.pos] = '=' then INC(cur.pos); tok := sGeq; else tok := sGtr; end;
952+ | ':':
953+ INC(cur.pos);
954+ if cur.buf[cur.pos] = '=' then INC(cur.pos); tok := sBecomes; else tok := sColon; end;
955+ | '.':
956+ INC(cur.pos);
957+ if cur.buf[cur.pos] = '.' then
958+ INC(cur.pos);
959+ if cur.buf[cur.pos] = '.' then INC(cur.pos); tok := sEllipsis; else tok := sUpto; end;
960+ else
961+ tok := sPeriod;
962+ end;
963+ | '|':
964+ if cur.buf[cur.pos + 1] = '|' then
965+ slip(2, sOr, "\"or\" is written or, not ||");
966+ else
967+ INC(cur.pos);
968+ tok := sBar;
969+ end;
970+ | '!':
971+ if cur.buf[cur.pos + 1] = '=' then
972+ slip(2, sNeq, "\"not equal\" is written #, not !=");
973+ else
974+ slip(1, sNot, "\"not\" is written not, not !");
975+ end;
976+ | 0:
977+ if cur.pos < cur.len then markBytes(cur.pos, cur.pos + 1, "NUL byte in the text"); end;
978+ tok := sEof;
979+ | else:
980+ if c >= 80H then lexError("only ASCII outside strings, characters and comments"); end;
981+ markBytes(cur.pos, cur.pos + 1, Diag.say("unexpected character \"{}\"", [Fmt.char(c)]));
982+ end;
983+end;
984+
985+var i: INT;
986+
987+begin
988+ for i := 0 to 255 do nameChar[i] := isLetter(U8(i)) or isDigit(U8(i)); end;
989+ for i := 0 to NumOps - 1 do
990+ if (LEN(ops[i]) = 1) and (Str.find(alone, ops[i]) >= 0) then
991+ single[ops[i][0]] := Sym(INT(sPlus) + i);
992+ end;
993+ end;
994+ chunkLeft := 0;
995+ nameCap := 1 shl 12;
996+ namePtr := ^NamePtr(grab(nameCap * SIZE(NamePtr)));
997+ nameLen := ^INT(grab(nameCap * SIZE(INT)));
998+ nameHash := ^INT(grab(nameCap * SIZE(INT)));
999+ tableMask := 2 * nameCap - 1;
1000+ table := words64(tableMask + 1);
1001+ for i := 0 to NumWords - 1 do _ := intern(ADR(words[i][0]), LEN(words[i])); end;
1002+end Scan.

src/Sym.raz (history) added +684 -0

@@ -0,0 +1,684 @@
1+(* Sym: types, objects and scopes.
2+
3+ Every name the program declares becomes an object (Obj): a constant,
4+ type, variable, procedure, module, record field, variant case or
5+ built-in. Every type is a Type. Objects are found through one hash
6+ table keyed by scope and name, so a lookup costs the same however
7+ big a module grows. A scope is just a number: the universe is 0,
8+ and each module, procedure, record and match arm gets a fresh one.
9+
10+ Depends on: Scan, for names and errors; Diag, for positions.
11+ Leaves out: code. Where a variable lives is decided here (frame
12+ offsets, chunk numbers), but nothing is emitted.
13+
14+ Exported variables can't be set from outside, so setCurModule is
15+ how the parser says which module it is in. A name that holds a
16+ reserved word of raz is spelled otherwise: a record's `module` is
17+ its `home`, an object's `link` its `chain`. *)
18+module Sym;
19+import Mem, Heap, Buf, Fmt, Diag, Scan;
20+
21+type
22+ Form* = (fNone, fBool, fInt, fReal, fConst, fNil, fStr, fPtr, fArray,
23+ fSlice, fRecord, fVariant, fProc, fEnum, fSet, fError);
24+ (* fConst is the type of an untyped integer constant; fStr of a string
25+ literal, whose length the literal carries. F32 and F64 are fReal,
26+ told apart by size, and so is tRConst, an untyped real constant. *)
27+
28+ Class* = (oConst, oType, oVar, oProc, oModule, oField, oCase, oBuiltin);
29+
30+ Type* = record
31+ form*: Form;
32+ size*, align*: I64;
33+ signed*: BOOL; (* fInt *)
34+ vol*: BOOL; (* fPtr: ^VOLATILE *)
35+ packd*: BOOL; (* fRecord *)
36+ variadic*: BOOL; (* fProc: ends in ... *)
37+ tuple*: BOOL; (* fRecord: the results of a procedure that has several *)
38+ base*: ^Type; (* fPtr, fArray, fSlice: what it holds; fProc: result *)
39+ len*: I64; (* fArray: elements; fProc: parameters; fVariant: cases; a tuple: results *)
40+ fields*: ^Obj; (* fRecord: fields; fVariant: cases; fProc: parameters *)
41+ scope*: INT; (* fRecord: the scope of its fields *)
42+ fwd*: INT; (* fPtr whose base isn't declared yet: its name, else -1 *)
43+ obj*: ^Obj; (* the declaration that names it, or nil *)
44+ home*: ^Module; (* the module that built it *)
45+ end;
46+
47+ Obj* = record
48+ cls*: Class;
49+ name*: INT;
50+ exported*: BOOL;
51+ typ*: ^Type;
52+ next*: ^Obj; (* the next in its list: scope, fields, parameters *)
53+ scope*: INT; (* where it is declared *)
54+ pos*: Diag.Pos; (* where its name is declared, for messages *)
55+ val*: I64; (* oConst: value; oBuiltin: which; oCase: tag;
56+ oField: offset; oVar: frame offset *)
57+ chunk*: INT; (* global oVar, oProc, string oConst: its chunk *)
58+ lev*: INT; (* oVar: 0 for a module variable, 1 for a local *)
59+ ind*: BOOL; (* oVar: the frame slot holds the variable's address *)
60+ off*: I64; (* oVar with ind: added to that address *)
61+ isVar*: BOOL; (* a var parameter *)
62+ param*: BOOL; (* oVar: a parameter *)
63+ used*: BOOL; (* named somewhere but in its own body *)
64+ read*: BOOL; (* oVar: named other than as what := assigns *)
65+ fwd*: BOOL; (* oProc: declared forward, no body yet *)
66+ isCode*: BOOL; (* oProc: a code procedure *)
67+ openEnd*: BOOL; (* oProc: has results, and may reach its end *)
68+ reg*: INT; (* oVar: the register it lives in, or 0 if in memory;
69+ for a slice, the one its pointer is in *)
70+ reg2*: INT; (* oVar: a slice in registers: the one its length is in *)
71+ ext*: BOOL; (* oProc, oVar: C's, reached through its chunk, which
72+ holds its address *)
73+ fields*: ^Obj; (* oCase: its fields *)
74+ home*: ^Module; (* oModule: the module; others: where declared *)
75+ chain*: ^Obj; (* the next declaration of its module, top-level or
76+ local *)
77+ end;
78+
79+ (* The arguments of a generic module's instance: a type, or a
80+ procedure (o) and its type. *)
81+ Args* = record
82+ n*: INT;
83+ t*: [8]^Type;
84+ o*: [8]^Obj;
85+ pos*: [8]Diag.Pos; (* where each argument is, for messages *)
86+ at*: Diag.Pos; (* where the import is *)
87+ end;
88+
89+ Import* = record
90+ home*: ^Module;
91+ next*: ^Import;
92+ end;
93+
94+ (* A library a module links, by its name, as interned *)
95+ Lib* = record
96+ name*: INT;
97+ next*: ^Lib;
98+ end;
99+
100+ Module* = record
101+ name*: INT;
102+ sname*: INT; (* the name of its symbols: List(I64) for an instance *)
103+ args*: Args;
104+ scope*: INT;
105+ path*: []U8;
106+ first*, last*: ^Obj; (* its top-level declarations, in order *)
107+ locals*, lastLocal*: ^Obj; (* its procedures' declarations, in order *)
108+ imports*: ^Import;
109+ body*: INT; (* the chunk of its body, or -1 *)
110+ done*: BOOL; (* compiled to the end *)
111+ checkOnly*: BOOL; (* read only to check another file's interface *)
112+ used*: BOOL; (* imported, through others, by the main module *)
113+ usesC*: BOOL; (* has an extern, or links a library *)
114+ linkStatic*: BOOL; (* says link static *)
115+ libs*: ^Lib; (* the libraries it links *)
116+ next*: ^Module; (* modules in the order they were finished *)
117+ end;
118+
119+const
120+ (* built-in procedures *)
121+ bSize* = 0; bAdr* = 1; bLen* = 2; bNew* = 3; bMsg* = 4; bSyscall* = 5;
122+ bFence* = 6; bCas* = 7; bXchg* = 8; bXadd* = 9; bArgc* = 10; bArgv* = 11;
123+ bInc* = 12; bDec* = 13; bCopy* = 14;
124+
125+ MaxDepth* = 64; (* scopes open at once *)
126+
127+var
128+ tI8*, tI16*, tI32*, tI64*, tU8*, tU16*, tU32*, tU64*: ^Type;
129+ tInt*, tUInt*: ^Type; (* INT and UINT, as big as an address: 8 bytes here *)
130+ tBool*, tF32*, tReal*, tRConst*, tError*, tConst*, tNil*, tStr*, tNone*, tPtrU8*, tBytes*: ^Type;
131+ tPoison*: ^Type; (* of a name reported as not declared *)
132+ curModule*: ^Module;
133+
134+ scopes: [MaxDepth]INT;
135+ depth: INT;
136+ nextScope: INT;
137+ hashTab: ^^Obj;
138+ hashMask, hashCount: INT;
139+
140+proc setCurModule*(m: ^Module);
141+begin
142+ curModule := m;
143+end;
144+
145+proc newType*(form: Form; size, align: I64): ^Type;
146+var t: ^Type;
147+begin
148+ NEW(t, Heap.heap);
149+ if t = nil then Diag.fatal("out of memory"); end;
150+ t^.form := form;
151+ t^.size := size;
152+ t^.align := align;
153+ t^.fwd := -1;
154+ t^.home := curModule;
155+ return t;
156+end;
157+
158+proc newObj*(cls: Class; name: INT; typ: ^Type): ^Obj;
159+var o: ^Obj;
160+begin
161+ NEW(o, Heap.heap);
162+ if o = nil then Diag.fatal("out of memory"); end;
163+ o^.cls := cls;
164+ o^.name := name;
165+ o^.typ := typ;
166+ o^.chunk := -1;
167+ o^.home := curModule;
168+ o^.pos := Scan.tokPos();
169+ return o;
170+end;
171+
172+(* Scopes *)
173+
174+proc newScope*: INT;
175+begin
176+ INC(nextScope);
177+ return nextScope;
178+end;
179+
180+proc openScope*(s: INT): ERROR;
181+begin
182+ if depth = MaxDepth then
183+ return Scan.mark(Diag.say("scopes nested more than {} deep", [Fmt.int(MaxDepth)]));
184+ end;
185+ scopes[depth] := s;
186+ INC(depth);
187+ return nil;
188+end;
189+
190+proc closeScope*;
191+begin
192+ DEC(depth);
193+end;
194+
195+(* An imported module is compiled in the middle of another, and must
196+ see only the universe and itself. The scopes open are kept in saved,
197+ and their number is the result. *)
198+proc saveScopes*(saved: []INT): INT;
199+var i, d: INT;
200+begin
201+ d := depth;
202+ for i := 0 to depth - 1 do saved[i] := scopes[i]; end;
203+ depth := 1;
204+ return d;
205+end;
206+
207+proc restoreScopes*(d: INT; saved: []INT);
208+var i: INT;
209+begin
210+ depth := d;
211+ for i := 0 to depth - 1 do scopes[i] := saved[i]; end;
212+end;
213+
214+proc scopeDepth*: INT;
215+begin
216+ return depth;
217+end;
218+
219+(* Closes the scopes opened since there were d, after an error *)
220+proc cutScopes*(d: INT);
221+begin
222+ depth := d;
223+end;
224+
225+proc topScope*: INT;
226+begin
227+ return scopes[depth - 1];
228+end;
229+
230+(* Where the search for name in scope s starts in the hash table: each
231+ number is multiplied by an odd constant near 2^32 or 2^16 over the
232+ golden ratio (Knuth's multiplicative hashing), which spreads the low
233+ bits the mask keeps. *)
234+proc slot(s, name: INT): INT;
235+begin
236+ return INT(((U32(s & 0FFFFFFFFH) * 2654435761) xor (U32(name & 0FFFFFFFFH) * 40503)) & U32(hashMask));
237+end;
238+
239+(* A table of n slots, all empty *)
240+proc emptyTable(n: INT): ^^Obj;
241+var t: ^^Obj; i: INT;
242+begin
243+ t := ^^Obj(Scan.grab(n * SIZE(^Obj)));
244+ for i := 0 to n - 1 do t[i] := nil; end;
245+ return t;
246+end;
247+
248+(* Doubles the table, which insert keeps at most half full so that the
249+ linear probing stays short, and puts every entry in its new slot. *)
250+proc rehash;
251+var old: ^^Obj; n, i, j: INT;
252+begin
253+ old := hashTab;
254+ n := hashMask + 1;
255+ hashMask := n * 2 - 1;
256+ hashTab := emptyTable(n * 2);
257+ for i := 0 to n - 1 do
258+ if old[i] # nil then
259+ j := slot(old[i]^.scope, old[i]^.name);
260+ while hashTab[j] # nil do j := (j + 1) & hashMask; end;
261+ hashTab[j] := old[i];
262+ end;
263+ end;
264+ Mem.free(Heap.heap, ^U8(old));
265+end;
266+
267+proc insert*(obj: ^Obj; s: INT): ERROR;
268+var i: INT; o: ^Obj;
269+begin
270+ i := slot(s, obj^.name);
271+ o := hashTab[i];
272+ while o # nil do
273+ if (o^.scope = s) and (o^.name = obj^.name) then
274+ Diag.error(obj^.pos, Diag.say("{} is declared twice", [Fmt.str(Scan.nameOf(obj^.name))]));
275+ Diag.note(o^.pos, "the first one is here");
276+ return Scan.Failed;
277+ end;
278+ i := (i + 1) & hashMask;
279+ o := hashTab[i];
280+ end;
281+ obj^.scope := s;
282+ hashTab[i] := obj;
283+ INC(hashCount);
284+ if hashCount * 2 > hashMask then rehash; end;
285+ return nil;
286+end;
287+
288+proc find*(s, name: INT): ^Obj;
289+var i: INT; o: ^Obj;
290+begin
291+ i := slot(s, name);
292+ o := hashTab[i];
293+ while o # nil do
294+ if (o^.scope = s) and (o^.name = name) then return o; end;
295+ i := (i + 1) & hashMask;
296+ o := hashTab[i];
297+ end;
298+ return nil;
299+end;
300+
301+proc lookup*(name: INT): ^Obj;
302+var i: INT; o: ^Obj;
303+begin
304+ for i := depth - 1 to 0 by -1 do
305+ o := find(scopes[i], name);
306+ if o # nil then return o; end;
307+ end;
308+ return nil;
309+end;
310+
311+proc min(a, b: INT): INT;
312+begin
313+ if a < b then return a; end;
314+ return b;
315+end;
316+
317+(* c, in capitals if it is a letter *)
318+proc up(c: U8): U8;
319+begin
320+ if (c >= 97) and (c <= 122) then return c - 32; end;
321+ return c;
322+end;
323+
324+(* How far apart two names are: the edits, a character put in, taken out,
325+ changed or swapped with the next, that make one the other, ignoring
326+ case. *)
327+proc distance(a, b: []U8): INT;
328+var d: [Scan.MaxIdent + 2][Scan.MaxIdent + 2]INT; i, j, c: INT;
329+begin
330+ for i := 0 to LEN(a) do d[i][0] := i; end;
331+ for j := 0 to LEN(b) do d[0][j] := j; end;
332+ for i := 1 to LEN(a) do
333+ for j := 1 to LEN(b) do
334+ c := 1;
335+ if up(a[i - 1]) = up(b[j - 1]) then c := 0; end;
336+ d[i][j] := min(min(d[i - 1][j] + 1, d[i][j - 1] + 1), d[i - 1][j - 1] + c);
337+ if (i > 1) and (j > 1) and (up(a[i - 1]) = up(b[j - 2]))
338+ and (up(a[i - 2]) = up(b[j - 1])) then
339+ d[i][j] := min(d[i][j], d[i - 2][j - 2] + 1);
340+ end;
341+ end;
342+ end;
343+ return d[LEN(a)][LEN(b)];
344+end;
345+
346+(* The name spelled most like name, for "did you mean": in scope s, if
347+ it can be reached from here, or in the scopes in reach if s < 0; nil
348+ if none is within an edit for every three characters. Only after an
349+ error, so it looks at every object. *)
350+proc closest*(name, s: INT): ^Obj;
351+var i, j, d, best: INT; o, found: ^Obj; n: []U8; reach: BOOL;
352+begin
353+ n := Scan.nameOf(name);
354+ best := LEN(n) div 3 + 1;
355+ found := nil;
356+ for i := 0 to hashMask do
357+ o := hashTab[i];
358+ if (o = nil) or (o^.name = name) or (o^.name < 0) or (o^.typ = tPoison) then
359+ reach := false;
360+ elsif s >= 0 then
361+ reach := (o^.scope = s) and (o^.exported or (o^.home = curModule));
362+ else
363+ reach := false;
364+ for j := 0 to depth - 1 do reach := reach or (o^.scope = scopes[j]); end;
365+ end;
366+ if reach then
367+ d := distance(n, Scan.nameOf(o^.name));
368+ if d < best then best := d; found := o; end;
369+ end;
370+ end;
371+ return found;
372+end;
373+
374+(* Types *)
375+
376+proc alignUp*(x, a: I64): I64;
377+begin
378+ return (x + a - 1) div a * a;
379+end;
380+
381+proc isInt*(t: ^Type): BOOL;
382+begin
383+ return t^.form in {fInt, fConst};
384+end;
385+
386+proc isScalar*(t: ^Type): BOOL;
387+begin
388+ return t^.form in {fBool, fInt, fReal, fConst, fNil, fPtr, fProc, fEnum, fSet, fError};
389+end;
390+
391+proc isAggregate*(t: ^Type): BOOL;
392+begin
393+ return t^.form in {fArray, fSlice, fRecord, fVariant};
394+end;
395+
396+(* Whether a result field f is a single value of at most a word, not a real *)
397+proc oneWord(f: ^Obj): BOOL;
398+begin
399+ return isScalar(f^.typ) and (f^.typ^.form # fReal) and (f^.typ^.size <= 8);
400+end;
401+
402+(* Whether a procedure's result t is two words, which come back in rax
403+ and rdx, as System V returns a struct of two integers: a slice (its
404+ pointer, then its length), or two results that are each a single
405+ value of 8 bytes at most and not a real. *)
406+proc inTwoRegs*(t: ^Type): BOOL;
407+begin
408+ if t^.form = fSlice then return true; end;
409+ return t^.tuple and (t^.len = 2) and oneWord(t^.fields) and oneWord(t^.fields^.next);
410+end;
411+
412+(* Whether a procedure's result t comes back in memory the caller
413+ provides, whose address the caller passes as a hidden first argument,
414+ in rdi: any result that is neither one value, in rax or xmm0, nor two
415+ words, in rax and rdx. *)
416+proc behindPointer*(t: ^Type): BOOL;
417+begin
418+ return isAggregate(t) and not inTwoRegs(t);
419+end;
420+
421+proc fits*(v: I64; t: ^Type): BOOL;
422+begin
423+ if t^.form # fInt then return t^.form = fConst; end;
424+ match t^.size of
425+ | 1:
426+ if t^.signed then return (v >= -128) and (v <= 127); end;
427+ return (v >= 0) and (v <= 255);
428+ | 2:
429+ if t^.signed then return (v >= -32768) and (v <= 32767); end;
430+ return (v >= 0) and (v <= 65535);
431+ | 4:
432+ if t^.signed then return (v >= -2147483648) and (v <= 2147483647); end;
433+ return (v >= 0) and (v <= 4294967295);
434+ | else: return t^.signed or (v >= 0);
435+ end;
436+end;
437+
438+proc same*(a, b: ^Type): BOOL; forward;
439+
440+(* Whether two procedure types, or two tuples, are alike: the same
441+ results and parameters, in the same modes *)
442+proc alikeShape(a, b: ^Type): BOOL;
443+var p, q: ^Obj;
444+begin
445+ (* a record is the same only as itself, but for several results *)
446+ if (a^.form = fRecord) and not (a^.tuple and b^.tuple) then return false; end;
447+ if (a^.len # b^.len) or (a^.variadic # b^.variadic) then return false; end;
448+ if (a^.base = nil) # (b^.base = nil) then return false; end;
449+ if (a^.base # nil) and not same(a^.base, b^.base) then return false; end;
450+ p := a^.fields; q := b^.fields;
451+ while p # nil do
452+ if (p^.isVar # q^.isVar) or not same(p^.typ, q^.typ) then return false; end;
453+ p := p^.next; q := q^.next;
454+ end;
455+ return true;
456+end;
457+
458+(* Structural sameness of two types. Named types are the same only if
459+ they are one declaration; a type with no name is the same as another
460+ built alike. *)
461+proc alike(a, b: ^Type): BOOL;
462+begin
463+ if a = b then return true; end;
464+ if a^.form # b^.form then return false; end;
465+ match a^.form of
466+ | fPtr: return (a^.vol = b^.vol) and same(a^.base, b^.base);
467+ | fArray: return (a^.len = b^.len) and same(a^.base, b^.base);
468+ | fSlice: return same(a^.base, b^.base);
469+ | fSet: return same(a^.base, b^.base);
470+ | fProc: return alikeShape(a, b);
471+ | fRecord: return alikeShape(a, b);
472+ | else: return false;
473+ end;
474+end;
475+
476+proc same*(a, b: ^Type): BOOL;
477+begin
478+ if a = b then return true; end;
479+ if (a = nil) or (b = nil) then return false; end;
480+ if (a^.obj # nil) and (b^.obj # nil) then return false; end;
481+ return alike(a, b);
482+end;
483+
484+(* What a type is called, added to b: the names a program gives it, else
485+ what it is made of *)
486+proc typeText(b: ^Buf.Buf; t: ^Type);
487+var f: ^Obj;
488+begin
489+ if t = nil then Buf.str(b, "nothing"); return; end;
490+ if t^.obj # nil then
491+ if (t^.obj^.home # nil) and (t^.obj^.home # curModule) then
492+ Buf.str(b, Scan.nameOf(t^.obj^.home^.sname));
493+ Buf.str(b, ".");
494+ end;
495+ Buf.str(b, Scan.nameOf(t^.obj^.name));
496+ return;
497+ end;
498+ match t^.form of
499+ | fConst: Buf.str(b, "an integer constant");
500+ | fReal: Buf.str(b, "a real constant");
501+ | fNil: Buf.str(b, "nil");
502+ | fStr: Buf.str(b, "a string");
503+ | fPtr:
504+ if t^.vol then Buf.str(b, "^VOLATILE "); else Buf.str(b, "^"); end;
505+ typeText(b, t^.base);
506+ | fArray:
507+ Fmt.write(b, "[{}]", [Fmt.int(t^.len)]);
508+ typeText(b, t^.base);
509+ | fSlice:
510+ Buf.str(b, "[]");
511+ typeText(b, t^.base);
512+ | fRecord:
513+ if not t^.tuple then
514+ Buf.str(b, "record");
515+ else
516+ Buf.str(b, "(");
517+ f := t^.fields;
518+ while f # nil do
519+ typeText(b, f^.typ);
520+ f := f^.next;
521+ if f # nil then Buf.str(b, ", "); end;
522+ end;
523+ Buf.str(b, ")");
524+ end;
525+ | fVariant: Buf.str(b, "variant");
526+ | fProc:
527+ Buf.str(b, "proc(");
528+ f := t^.fields;
529+ while f # nil do
530+ if f^.isVar then Buf.str(b, "var "); end;
531+ typeText(b, f^.typ);
532+ f := f^.next;
533+ if f # nil then Buf.str(b, ", "); end;
534+ end;
535+ Buf.str(b, ")");
536+ if t^.base # nil then
537+ Buf.str(b, ": ");
538+ typeText(b, t^.base);
539+ end;
540+ | else: Buf.str(b, "?");
541+ end;
542+end;
543+
544+(* A name for t, kept for good, as every message is *)
545+proc typeName*(t: ^Type): []U8;
546+var b: ^Buf.Buf;
547+begin
548+ b := ^Buf.Buf(Scan.grab(SIZE(Buf.Buf)));
549+ Buf.init(b, Heap.heap);
550+ typeText(b, t);
551+ return Buf.bytes(b);
552+end;
553+
554+(* A fingerprint of what a declaration exports, for the interface
555+ check: two files of one module export the same thing when their
556+ fingerprints agree. A named type counts by its name, so that a type
557+ declared in each file stands for the other's. *)
558+proc mix(var h: U64; v: I64);
559+begin
560+ h := (h xor U64(v)) * 1099511628211; (* FNV-1a's 64-bit prime *)
561+end;
562+
563+proc bit(f: BOOL): INT;
564+begin
565+ if f then return 1; end;
566+ return 0;
567+end;
568+
569+proc shape(var h: U64; t: ^Type; top: BOOL);
570+var f, g: ^Obj;
571+begin
572+ if t = nil then mix(h, -1); return; end;
573+ if (t^.obj # nil) and not top then
574+ mix(h, t^.obj^.name);
575+ if t^.obj^.home # nil then mix(h, t^.obj^.home^.sname); end;
576+ return;
577+ end;
578+ mix(h, INT(t^.form));
579+ mix(h, bit(t^.vol) + 2 * bit(t^.variadic));
580+ mix(h, t^.len);
581+ if t^.form in {fPtr, fArray, fSlice, fProc, fSet} then shape(h, t^.base, false); end;
582+ f := t^.fields;
583+ while f # nil do
584+ if (t^.form # fRecord) or f^.exported then
585+ mix(h, f^.name);
586+ mix(h, bit(f^.isVar));
587+ shape(h, f^.typ, false);
588+ g := f^.fields;
589+ while g # nil do shape(h, g^.typ, false); g := g^.next; end;
590+ end;
591+ f := f^.next;
592+ end;
593+end;
594+
595+proc fingerprint*(o: ^Obj): U64;
596+var h: U64; f: ^Obj;
597+begin
598+ h := 0CBF29CE484222325H; (* FNV-1a's 64-bit offset basis *)
599+ mix(h, INT(o^.cls));
600+ if o^.cls = oCase then
601+ mix(h, o^.val);
602+ f := o^.fields;
603+ while f # nil do shape(h, f^.typ, false); f := f^.next; end;
604+ else
605+ shape(h, o^.typ, o^.cls = oType);
606+ end;
607+ return h;
608+end;
609+
610+(* The universe *)
611+
612+proc basic(name: []U8; form: Form; size: I64; signed: BOOL): ^Type;
613+var t: ^Type; o: ^Obj;
614+begin
615+ t := newType(form, size, size);
616+ t^.signed := signed;
617+ o := newObj(oType, Scan.intern(ADR(name[0]), LEN(name)), t);
618+ o^.exported := true;
619+ t^.obj := o;
620+ _ := insert(o, 0);
621+ return t;
622+end;
623+
624+proc enter(name: []U8; cls: Class; t: ^Type; v: I64);
625+var o: ^Obj;
626+begin
627+ o := newObj(cls, Scan.intern(ADR(name[0]), LEN(name)), t);
628+ o^.val := v;
629+ o^.exported := true;
630+ _ := insert(o, 0);
631+end;
632+
633+begin
634+ hashMask := (1 shl 14) - 1;
635+ hashTab := emptyTable(hashMask + 1);
636+ depth := 1;
637+ scopes[0] := 0;
638+ nextScope := 0;
639+ curModule := nil;
640+ tI8 := basic("I8", fInt, 1, true);
641+ tI16 := basic("I16", fInt, 2, true);
642+ tI32 := basic("I32", fInt, 4, true);
643+ tI64 := basic("I64", fInt, 8, true);
644+ tU8 := basic("U8", fInt, 1, false);
645+ tU16 := basic("U16", fInt, 2, false);
646+ tU32 := basic("U32", fInt, 4, false);
647+ tU64 := basic("U64", fInt, 8, false);
648+ tInt := basic("INT", fInt, 8, true);
649+ tUInt := basic("UINT", fInt, 8, false);
650+ tBool := basic("BOOL", fBool, 1, false);
651+ tF32 := basic("F32", fReal, 4, false);
652+ tReal := basic("F64", fReal, 8, false);
653+ tRConst := newType(fReal, 8, 8);
654+ tError := basic("ERROR", fError, 8, false);
655+ tConst := newType(fConst, 8, 8);
656+ tConst^.signed := true;
657+ tNil := newType(fNil, 8, 8);
658+ tStr := newType(fStr, 0, 1);
659+ tNone := newType(fNone, 0, 1);
660+ tPtrU8 := newType(fPtr, 8, 8);
661+ tPtrU8^.base := tU8;
662+ tBytes := newType(fSlice, 16, 8);
663+ tBytes^.base := tU8;
664+ tPoison := newType(fInt, 8, 8);
665+ tPoison^.signed := true;
666+ enter("true", oConst, tBool, 1);
667+ enter("false", oConst, tBool, 0);
668+ enter("nil", oConst, tNil, 0);
669+ enter("SIZE", oBuiltin, nil, bSize);
670+ enter("ADR", oBuiltin, nil, bAdr);
671+ enter("LEN", oBuiltin, nil, bLen);
672+ enter("NEW", oBuiltin, nil, bNew);
673+ enter("MSG", oBuiltin, nil, bMsg);
674+ enter("SYSCALL", oBuiltin, nil, bSyscall);
675+ enter("FENCE", oBuiltin, nil, bFence);
676+ enter("CAS", oBuiltin, nil, bCas);
677+ enter("XCHG", oBuiltin, nil, bXchg);
678+ enter("XADD", oBuiltin, nil, bXadd);
679+ enter("ARGC", oBuiltin, nil, bArgc);
680+ enter("ARGV", oBuiltin, nil, bArgv);
681+ enter("INC", oBuiltin, nil, bInc);
682+ enter("DEC", oBuiltin, nil, bDec);
683+ enter("COPY", oBuiltin, nil, bCopy);
684+end Sym.

src/X64.raz (history) added +1472 -0

@@ -0,0 +1,1472 @@
1+(* X64: machine code for x86-64.
2+
3+ The encoder writes the instructions the code generator needs, and
4+ no others, into the text of Chunk. Registers are numbered as the
5+ hardware numbers them. Jumps within a procedure are patched here, as
6+ soon as their target is known.
7+
8+ Depends on: Scan, for errors and the assembler's symbols; Diag, for
9+ positions; Chunk for the code buffer and fixups.
10+ Leaves out: choosing instructions; that is Gen.
11+
12+ The seed's `Mem` that is too large an offset is marked and the code
13+ goes on, since a function that makes an operand has no place to give
14+ an error back from; the compile ends with the error shown. *)
15+module X64;
16+import Out, Fmt, Heap, Buf, Str, Diag, Scan, Chunk;
17+
18+const
19+ RAX* = 0; RCX* = 1; RDX* = 2; RBX* = 3; RSP* = 4; RBP* = 5; RSI* = 6; RDI* = 7;
20+ R8* = 8; R9* = 9; R10* = 10; R11* = 11; R12* = 12; R13* = 13; R14* = 14; R15* = 15;
21+ RIP* = -1; (* a base meaning rip-relative, to a chunk *)
22+ NoIndex* = -1;
23+
24+ (* condition codes *)
25+ ccB* = 2; ccAE* = 3; ccE* = 4; ccNE* = 5; ccBE* = 6; ccA* = 7; ccS* = 8;
26+ ccP* = 10; ccNP* = 11; ccL* = 12; ccGE* = 13; ccLE* = 14; ccG* = 15;
27+
28+ (* group 1 operations, the /digit of 81 and 83 *)
29+ aluAdd* = 0; aluOr* = 1; aluAnd* = 4; aluSub* = 5; aluXor* = 6; aluCmp* = 7;
30+
31+ (* the /digit of D3 and C1 *)
32+ shShl* = 4; shShr* = 5; shSar* = 7;
33+
34+ NoLabel* = -1;
35+
36+type
37+ Mem* = record
38+ base*: INT; (* a register, or RIP *)
39+ index*: INT; (* a register, or NoIndex *)
40+ scale*: INT; (* 1, 2, 4 or 8 *)
41+ disp*: INT;
42+ chunk*: INT; (* with RIP: the chunk addressed *)
43+ end;
44+
45+ (* The parser's reader of an integer constant in a code procedure: a
46+ whole expression, or, when whole is false, a single factor *)
47+ ConstFn* = proc(whole: BOOL): (I64, ERROR);
48+
49+ (* The text of the instruction that starts at at, for the listing *)
50+ Said = record
51+ at: INT;
52+ text: []U8;
53+ end;
54+
55+var
56+ listing*: BOOL; (* -S: each instruction's text is kept, for list *)
57+ said: ^Said;
58+ numSaid, saidCap: INT;
59+
60+proc setListing*(yes: BOOL);
61+begin
62+ listing := yes;
63+end;
64+
65+(* Operands *)
66+
67+proc mem*(base: INT; disp: I64): Mem;
68+var m: Mem;
69+begin
70+ if (disp < -2147483648) or (disp > 2147483647) then
71+ _ := Scan.mark("an offset beyond 32 bits");
72+ end;
73+ m.base := base; m.index := NoIndex; m.scale := 1;
74+ m.disp := INT(disp); m.chunk := -1;
75+ return m;
76+end;
77+
78+proc memRip*(chunk: INT; disp: INT): Mem;
79+var m: Mem;
80+begin
81+ m.base := RIP; m.index := NoIndex; m.scale := 1;
82+ m.disp := disp; m.chunk := chunk;
83+ return m;
84+end;
85+
86+proc memIdx*(base, index, scale: INT; disp: I64): Mem;
87+var m: Mem;
88+begin
89+ m := mem(base, disp);
90+ m.index := index;
91+ m.scale := scale;
92+ return m;
93+end;
94+
95+(* The address of the code about to be written, as an operand *)
96+proc here*: Mem;
97+begin
98+ return memRip(Chunk.curChunk, Chunk.pc - Chunk.chunks[Chunk.curChunk].start);
99+end;
100+
101+(* Encoding. An instruction is: a legacy prefix, REX, the opcode, ModRM,
102+ SIB and displacement. Opcodes of more than one byte are given with
103+ their first byte in the low eight bits. *)
104+
105+proc opcode(op: INT);
106+begin
107+ repeat
108+ Chunk.put1(op & 0FFH);
109+ op := op shr 8;
110+ until op = 0;
111+end;
112+
113+(* The legacy prefix pfx, if any, and REX: wide is REX.W; byte4 says
114+ a byte register of 4 to 7 is used, spl to dil, which exist only with
115+ a REX prefix. *)
116+proc prefix(pfx: INT; w: BOOL; reg, index, base: INT; byte4: BOOL);
117+var rex: INT;
118+begin
119+ if pfx # 0 then Chunk.put1(pfx); end;
120+ rex := 0;
121+ if w then rex := rex | 8; end;
122+ if reg >= 8 then rex := rex | 4; end;
123+ if index >= 8 then rex := rex | 2; end;
124+ if base >= 8 then rex := rex | 1; end;
125+ if (rex # 0) or byte4 then Chunk.put1(40H | rex); end;
126+end;
127+
128+(* op reg, [mem] *)
129+proc opM(pfx: INT; w: BOOL; op, reg: INT; m: Mem; byteReg: BOOL);
130+var md, b, sc: INT;
131+begin
132+ byteReg := byteReg and (reg >= 4) and (reg <= 7);
133+ if m.base = RIP then
134+ prefix(pfx, w, reg, NoIndex, 0, byteReg);
135+ else
136+ prefix(pfx, w, reg, m.index, m.base, byteReg);
137+ end;
138+ opcode(op);
139+ reg := reg & 7;
140+ if m.base = RIP then
141+ Chunk.put1((reg shl 3) | 5);
142+ (* mod 00 with r/m 101 is rip + disp32. The displacement counts
143+ from the end of the instruction, and the fixup takes it to end
144+ with these four bytes: an instruction with an immediate after
145+ them, aluMI's or storeI's, takes the immediate's size off disp
146+ first (the assembler can't name a chunk). *)
147+ Chunk.addFixup(Chunk.pc, m.chunk, m.disp);
148+ Chunk.put4(0);
149+ return;
150+ end;
151+ b := m.base & 7;
152+ (* mod 00 takes no displacement, but with r/m 101 (RBP or R13) it means
153+ rip-relative, or disp32 under a SIB byte, so those bases take a
154+ zero disp8 *)
155+ if (m.disp = 0) and (b # RBP) then
156+ md := 0;
157+ elsif (m.disp >= -128) and (m.disp <= 127) then
158+ md := 1;
159+ else
160+ md := 2;
161+ end;
162+ (* r/m 100 (RSP or R12) means a SIB byte follows, so those bases need
163+ one, with index 100 meaning none *)
164+ if (m.index # NoIndex) or (b = RSP) then
165+ Chunk.put1((md shl 6) | (reg shl 3) | 4);
166+ if m.scale = 1 then sc := 0; elsif m.scale = 2 then sc := 1; elsif m.scale = 4 then sc := 2; else sc := 3; end;
167+ if m.index = NoIndex then
168+ Chunk.put1((sc shl 6) | (4 shl 3) | b);
169+ else
170+ Chunk.put1((sc shl 6) | ((m.index & 7) shl 3) | b);
171+ end;
172+ else
173+ Chunk.put1((md shl 6) | (reg shl 3) | b);
174+ end;
175+ if md = 1 then
176+ Chunk.put1(m.disp);
177+ elsif md = 2 then
178+ Chunk.put4(m.disp);
179+ end;
180+end;
181+
182+(* op reg, rm (both registers) *)
183+proc opR(pfx: INT; w: BOOL; op, reg, rm: INT; byteReg: BOOL);
184+begin
185+ prefix(pfx, w, reg, NoIndex, rm, byteReg and (((reg >= 4) and (reg <= 7)) or ((rm >= 4) and (rm <= 7))));
186+ opcode(op);
187+ Chunk.put1(0C0H | ((reg & 7) shl 3) | (rm & 7));
188+end;
189+
190+(* The listing: the text of each instruction, as it is made *)
191+
192+(* How many instructions the listing has, and back to n of them, for
193+ code made again *)
194+proc saidCount*: INT;
195+begin
196+ return numSaid;
197+end;
198+
199+proc unsay*(n: INT);
200+begin
201+ numSaid := n;
202+end;
203+
204+proc sayAt*(at: INT; s: []U8);
205+begin
206+ if not listing then return; end;
207+ if numSaid = saidCap then
208+ said := ^Said(Scan.regrab(^U8(said), numSaid * SIZE(Said), (saidCap * 2 + 1024) * SIZE(Said)));
209+ saidCap := saidCap * 2 + 1024;
210+ end;
211+ said[numSaid].at := at;
212+ said[numSaid].text := s;
213+ INC(numSaid);
214+end;
215+
216+(* The text of the instruction about to be written *)
217+proc say*(s: []U8);
218+begin
219+ sayAt(Chunk.pc, s);
220+end;
221+
222+(* The text of the instruction at at, said again, as when its operand is
223+ patched *)
224+proc restate*(at: INT; s: []U8);
225+var i: INT;
226+begin
227+ i := numSaid - 1;
228+ while (i >= 0) and (said[i].at # at) do DEC(i); end;
229+ if i >= 0 then said[i].text := s; end;
230+end;
231+
232+const
233+ RegNames: [4][16][]U8 = [
234+ ["rax", "rcx", "rdx", "rbx", "rsp", "rbp", "rsi", "rdi",
235+ "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15"],
236+ ["eax", "ecx", "edx", "ebx", "esp", "ebp", "esi", "edi",
237+ "r8d", "r9d", "r10d", "r11d", "r12d", "r13d", "r14d", "r15d"],
238+ ["ax", "cx", "dx", "bx", "sp", "bp", "si", "di",
239+ "r8w", "r9w", "r10w", "r11w", "r12w", "r13w", "r14w", "r15w"],
240+ ["al", "cl", "dl", "bl", "spl", "bpl", "sil", "dil",
241+ "r8b", "r9b", "r10b", "r11b", "r12b", "r13b", "r14b", "r15b"]];
242+ CondNames*: [16][]U8 = ["o", "no", "b", "ae", "e", "ne", "be", "a", "s", "ns", "p", "np", "l", "ge", "le", "g"];
243+ AluNames: [8][]U8 = ["add", "or", "adc", "sbb", "and", "sub", "xor", "cmp"];
244+ ShiftNames: [8][]U8 = ["rol", "ror", "rcl", "rcr", "shl", "shr", "sal", "sar"];
245+ UnaryNames: [8][]U8 = ["", "", "not", "neg", "mul", "imul", "div", "idiv"]; (* from 2 *)
246+
247+(* The name of register r, of size bytes *)
248+proc rnSized(r, size: INT): []U8;
249+begin
250+ if size = 1 then return RegNames[3][r]; end;
251+ if size = 2 then return RegNames[2][r]; end;
252+ if size = 4 then return RegNames[1][r]; end;
253+ return RegNames[0][r];
254+end;
255+
256+proc rn(r: INT): []U8;
257+begin
258+ return RegNames[0][r];
259+end;
260+
261+proc xn(x: INT): []U8;
262+begin
263+ return Diag.say("xmm{}", [Fmt.int(x)]);
264+end;
265+
266+(* A memory operand, with the size of what it holds, as the assembler
267+ reads it *)
268+proc mnSized(m: Mem; size: INT): []U8;
269+var b: ^Buf.Buf;
270+begin
271+ b := ^Buf.Buf(Scan.grab(SIZE(Buf.Buf)));
272+ Buf.init(b, Heap.heap);
273+ if size = 1 then Buf.str(b, "byte ");
274+ elsif size = 2 then Buf.str(b, "word ");
275+ elsif size = 4 then Buf.str(b, "dword ");
276+ elsif size = 8 then Buf.str(b, "qword ");
277+ end;
278+ Buf.str(b, "[");
279+ if m.base = RIP then Buf.str(b, Chunk.chunkName(m.chunk)); else Buf.str(b, rn(m.base)); end;
280+ if m.index # NoIndex then Fmt.write(b, " + {} * {}", [Fmt.str(rn(m.index)), Fmt.int(m.scale)]); end;
281+ if m.disp > 0 then
282+ Fmt.write(b, " + {}", [Fmt.int(m.disp)]);
283+ elsif m.disp < 0 then
284+ Fmt.write(b, " - {}", [Fmt.int(-m.disp)]);
285+ end;
286+ Buf.str(b, "]");
287+ return Buf.bytes(b);
288+end;
289+
290+proc mn(m: Mem): []U8;
291+begin
292+ return mnSized(m, 0);
293+end;
294+
295+(* "op a, b" and "op a" *)
296+proc text2(op, a, b: []U8): []U8;
297+begin
298+ return Diag.say("{} {}, {}", [Fmt.str(op), Fmt.str(a), Fmt.str(b)]);
299+end;
300+
301+proc text1(op, a: []U8): []U8;
302+begin
303+ return Diag.say("{} {}", [Fmt.str(op), Fmt.str(a)]);
304+end;
305+
306+(* v in decimal *)
307+proc num(v: INT): []U8;
308+begin
309+ return Diag.say("{}", [Fmt.int(v)]);
310+end;
311+
312+proc movRR*(dst, src: INT);
313+begin
314+ if listing then say(text2("mov", rn(dst), rn(src))); end;
315+ opR(0, true, 89H, src, dst, false);
316+end;
317+
318+(* The operand-size prefix a size of 2 bytes takes *)
319+proc pfx16(size: INT): INT;
320+begin
321+ if size = 2 then return 66H; end;
322+ return 0;
323+end;
324+
325+(* The immediate of n bytes that ends an instruction *)
326+proc putImm(v, n: INT);
327+begin
328+ if n = 4 then
329+ Chunk.put4(v);
330+ else
331+ Chunk.put1(v & 0FFH);
332+ if n = 2 then Chunk.put1((v shr 8) & 0FFH); end;
333+ end;
334+end;
335+
336+(* op [m], v, on size bytes; v fits in them, or in 32 bits for 8 *)
337+proc aluMI*(op: INT; m: Mem; v, size: INT);
338+var n: INT;
339+begin
340+ if listing then say(text2(AluNames[op], mnSized(m, size), num(v))); end;
341+ if (size = 1) or ((v >= -128) and (v <= 127)) then
342+ n := 1;
343+ elsif size = 2 then
344+ n := 2;
345+ else
346+ n := 4;
347+ end;
348+ if m.base = RIP then m.disp := m.disp - n; end;
349+ if size = 1 then
350+ opM(0, false, 80H, op, m, false);
351+ elsif n = 1 then
352+ opM(pfx16(size), size = 8, 83H, op, m, false);
353+ else
354+ opM(pfx16(size), size = 8, 81H, op, m, false);
355+ end;
356+ putImm(v, n);
357+end;
358+
359+(* mov [m], v, of size bytes; v fits in them, or in 32 bits for 8 *)
360+proc storeI*(m: Mem; v, size: INT);
361+var n: INT;
362+begin
363+ if listing then say(text2("mov", mnSized(m, size), num(v))); end;
364+ n := size;
365+ if n > 4 then n := 4; end;
366+ if m.base = RIP then m.disp := m.disp - n; end;
367+ if size = 1 then
368+ opM(0, false, 0C6H, 0, m, false);
369+ else
370+ opM(pfx16(size), size = 8, 0C7H, 0, m, false);
371+ end;
372+ putImm(v, n);
373+end;
374+
375+proc movRI*(r: INT; v: I64);
376+begin
377+ if listing then
378+ if v = 0 then
379+ say(text2("xor", rnSized(r, 4), rnSized(r, 4)));
380+ else
381+ say(text2("mov", rn(r), Diag.say("{}", [Fmt.int(v)])));
382+ end;
383+ end;
384+ if (v >= -2147483648) and (v <= 2147483647) then
385+ if v = 0 then
386+ opR(0, false, 31H, r, r, false); (* xor r32, r32 *)
387+ elsif v > 0 then (* mov r32, imm32 *)
388+ prefix(0, false, 0, NoIndex, r, false); Chunk.put1(0B8H + (r & 7)); Chunk.put4(INT(v));
389+ else
390+ opR(0, true, 0C7H, 0, r, false); Chunk.put4(INT(v)); (* sign-extended imm32 *)
391+ end;
392+ elsif (v > 0) and (v <= 0FFFFFFFFH) then
393+ prefix(0, false, 0, NoIndex, r, false); Chunk.put1(0B8H + (r & 7)); Chunk.put4(INT(v));
394+ else
395+ prefix(0, true, 0, NoIndex, r, false); Chunk.put1(0B8H + (r & 7)); Chunk.put8(v);
396+ end;
397+end;
398+
399+proc load*(r: INT; m: Mem; size: INT; signed: BOOL);
400+begin
401+ if listing then
402+ if size = 8 then
403+ say(text2("mov", rn(r), mn(m)));
404+ elsif (size = 4) and not signed then
405+ say(text2("mov", rnSized(r, 4), mn(m)));
406+ elsif size = 4 then
407+ say(text2("movsxd", rn(r), mnSized(m, 4)));
408+ elsif signed then
409+ say(text2("movsx", rn(r), mnSized(m, size)));
410+ else
411+ say(text2("movzx", rnSized(r, 4), mnSized(m, size)));
412+ end;
413+ end;
414+ if size = 1 then
415+ if signed then opM(0, true, 0BE0FH, r, m, false); else opM(0, false, 0B60FH, r, m, false); end;
416+ elsif size = 2 then
417+ if signed then opM(0, true, 0BF0FH, r, m, false); else opM(0, false, 0B70FH, r, m, false); end;
418+ elsif size = 4 then
419+ if signed then opM(0, true, 63H, r, m, false); else opM(0, false, 8BH, r, m, false); end;
420+ else
421+ opM(0, true, 8BH, r, m, false);
422+ end;
423+end;
424+
425+proc store*(m: Mem; r: INT; size: INT);
426+begin
427+ if listing then say(text2("mov", mn(m), rnSized(r, size))); end;
428+ if size = 1 then
429+ opM(0, false, 88H, r, m, true);
430+ elsif size = 2 then
431+ opM(66H, false, 89H, r, m, false);
432+ elsif size = 4 then
433+ opM(0, false, 89H, r, m, false);
434+ else
435+ opM(0, true, 89H, r, m, false);
436+ end;
437+end;
438+
439+proc lea*(r: INT; m: Mem);
440+begin
441+ if listing then say(text2("lea", rn(r), mn(m))); end;
442+ opM(0, true, 8DH, r, m, false);
443+end;
444+
445+proc alu*(op, dst, src: INT);
446+begin
447+ if listing then say(text2(AluNames[op], rn(dst), rn(src))); end;
448+ opR(0, true, (op shl 3) | 1, src, dst, false);
449+end;
450+
451+proc aluI*(op, r: INT; v: INT);
452+begin
453+ if listing then say(text2(AluNames[op], rn(r), num(v))); end;
454+ if (v >= -128) and (v <= 127) then
455+ opR(0, true, 83H, op, r, false); Chunk.put1(v);
456+ else
457+ opR(0, true, 81H, op, r, false); Chunk.put4(v);
458+ end;
459+end;
460+
461+(* op r, [m] *)
462+proc aluM*(op, r: INT; m: Mem);
463+begin
464+ if listing then say(text2(AluNames[op], rn(r), mn(m))); end;
465+ opM(0, true, (op shl 3) | 3, r, m, false);
466+end;
467+
468+proc imul*(dst, src: INT);
469+begin
470+ if listing then say(text2("imul", rn(dst), rn(src))); end;
471+ opR(0, true, 0AF0FH, dst, src, false);
472+end;
473+
474+proc imulI*(r: INT; v: INT);
475+begin
476+ if listing then say(Diag.say("imul {}, {}, {}", [Fmt.str(rn(r)), Fmt.str(rn(r)), Fmt.int(v)])); end;
477+ opR(0, true, 69H, r, r, false);
478+ Chunk.put4(v);
479+end;
480+
481+proc shift*(op, r: INT);
482+begin
483+ if listing then say(text2(ShiftNames[op], rn(r), "cl")); end;
484+ opR(0, true, 0D3H, op, r, false);
485+end;
486+
487+proc shiftI*(op, r, n: INT);
488+begin
489+ if listing then say(text2(ShiftNames[op], rn(r), num(n))); end;
490+ opR(0, true, 0C1H, op, r, false);
491+ Chunk.put1(n);
492+end;
493+
494+(* F7 /ext: 2 not, 3 neg, 6 div, 7 idiv *)
495+proc unary*(ext, r: INT);
496+begin
497+ if listing then say(text1(UnaryNames[ext], rn(r))); end;
498+ opR(0, true, 0F7H, ext, r, false);
499+end;
500+
501+proc cqo*;
502+begin
503+ if listing then say("cqo"); end;
504+ Chunk.put1(48H); Chunk.put1(99H);
505+end;
506+
507+(* Brings a value of size bytes in r to 64 bits, by its sign or zeros. *)
508+proc extend*(r, size: INT; signed: BOOL);
509+begin
510+ if listing then
511+ if size = 4 then
512+ if signed then
513+ say(text2("movsxd", rn(r), rnSized(r, 4)));
514+ else
515+ say(text2("mov", rnSized(r, 4), rnSized(r, 4)));
516+ end;
517+ elsif signed then
518+ say(text2("movsx", rn(r), rnSized(r, size)));
519+ else
520+ say(text2("movzx", rnSized(r, 4), rnSized(r, size)));
521+ end;
522+ end;
523+ if size = 1 then
524+ if signed then opR(0, true, 0BE0FH, r, r, true); else opR(0, false, 0B60FH, r, r, true); end;
525+ elsif size = 2 then
526+ if signed then opR(0, true, 0BF0FH, r, r, false); else opR(0, false, 0B70FH, r, r, false); end;
527+ elsif size = 4 then
528+ if signed then opR(0, true, 63H, r, r, false); else opR(0, false, 89H, r, r, false); end;
529+ end;
530+end;
531+
532+(* r := 1 if the condition holds, else 0 *)
533+proc setCC*(cc, r: INT);
534+begin
535+ if listing then say(text1(Diag.say("set{}", [Fmt.str(CondNames[cc])]), rnSized(r, 1))); end;
536+ opR(0, false, 900FH + (cc shl 8), 0, r, true);
537+ if listing then say(text2("movzx", rnSized(r, 4), rnSized(r, 1))); end;
538+ opR(0, false, 0B60FH, r, r, true);
539+end;
540+
541+proc testRR*(a, b: INT);
542+begin
543+ if listing then say(text2("test", rn(a), rn(b))); end;
544+ opR(0, true, 85H, b, a, false);
545+end;
546+
547+proc push*(r: INT);
548+begin
549+ if listing then say(text1("push", rn(r))); end;
550+ if r >= 8 then Chunk.put1(41H); end;
551+ Chunk.put1(50H + (r & 7));
552+end;
553+
554+proc pop*(r: INT);
555+begin
556+ if listing then say(text1("pop", rn(r))); end;
557+ if r >= 8 then Chunk.put1(41H); end;
558+ Chunk.put1(58H + (r & 7));
559+end;
560+
561+proc callChunk*(c: INT);
562+begin
563+ if listing then say(text1("call", Chunk.chunkName(c))); end;
564+ Chunk.put1(0E8H);
565+ Chunk.addFixup(Chunk.pc, c, 0);
566+ Chunk.put4(0);
567+end;
568+
569+proc callBack*(target: INT);
570+begin
571+ if listing then say("call"); end;
572+ Chunk.put1(0E8H);
573+ Chunk.put4(target - (Chunk.pc + 4));
574+end;
575+
576+proc callR*(r: INT);
577+begin
578+ if listing then say(text1("call", rn(r))); end;
579+ opR(0, false, 0FFH, 2, r, false);
580+end;
581+
582+proc jmpR*(r: INT);
583+begin
584+ if listing then say(text1("jmp", rn(r))); end;
585+ opR(0, false, 0FFH, 4, r, false);
586+end;
587+
588+proc callM*(m: Mem);
589+begin
590+ if listing then say(text1("call", mn(m))); end;
591+ opM(0, false, 0FFH, 2, m, false);
592+end;
593+
594+proc ret*;
595+begin
596+ if listing then say("ret"); end;
597+ Chunk.put1(0C3H);
598+end;
599+
600+proc leave*;
601+begin
602+ say("leave"); Chunk.put1(0C9H);
603+end;
604+
605+proc syscall*;
606+begin
607+ say("syscall"); Chunk.put1(0FH); Chunk.put1(05H);
608+end;
609+
610+proc mfence*;
611+begin
612+ say("mfence"); Chunk.put1(0FH); Chunk.put1(0AEH); Chunk.put1(0F0H);
613+end;
614+
615+proc ud2*;
616+begin
617+ say("ud2"); Chunk.put1(0FH); Chunk.put1(0BH);
618+end;
619+
620+(* Code made up to a multiple of n bytes with no-ops, the fewest: the
621+ long forms of nop, of up to 8 bytes, that x86 decodes as one *)
622+proc align*(n: INT);
623+const
624+ Nops: [8][]U8 = ["\x90", "\x66\x90", "\x0F\x1F\x00", "\x0F\x1F\x40\x00",
625+ "\x0F\x1F\x44\x00\x00", "\x66\x0F\x1F\x44\x00\x00", "\x0F\x1F\x80\x00\x00\x00\x00",
626+ "\x0F\x1F\x84\x00\x00\x00\x00\x00"];
627+var k, i: INT;
628+begin
629+ while Chunk.pc mod n # 0 do
630+ k := n - Chunk.pc mod n;
631+ if k > 8 then k := 8; end;
632+ say("nop");
633+ for i := 0 to k - 1 do Chunk.put1(INT(Nops[k - 1][i])); end;
634+ end;
635+end;
636+
637+proc repMovsb*;
638+begin
639+ say("rep movsb"); Chunk.put1(0F3H); Chunk.put1(0A4H);
640+end;
641+
642+(* the direction flag, which has rep movsb go down, and back up *)
643+proc std*;
644+begin
645+ say("std"); Chunk.put1(0FDH);
646+end;
647+
648+proc cld*;
649+begin
650+ say("cld"); Chunk.put1(0FCH);
651+end;
652+
653+proc repStosb*;
654+begin
655+ say("rep stosb"); Chunk.put1(0F3H); Chunk.put1(0AAH);
656+end;
657+
658+proc repeCmpsb*;
659+begin
660+ say("repe cmpsb"); Chunk.put1(0F3H); Chunk.put1(0A6H);
661+end;
662+
663+proc lockCmpxchg*(m: Mem; r: INT);
664+begin
665+ if listing then say(text2("lock cmpxchg", mn(m), rn(r))); end;
666+ Chunk.put1(0F0H);
667+ opM(0, true, 0B10FH, r, m, false);
668+end;
669+
670+proc xchg*(m: Mem; r: INT);
671+begin
672+ if listing then say(text2("xchg", mn(m), rn(r))); end;
673+ opM(0, true, 87H, r, m, false);
674+end;
675+
676+proc lockXadd*(m: Mem; r: INT);
677+begin
678+ if listing then say(text2("lock xadd", mn(m), rn(r))); end;
679+ Chunk.put1(0F0H);
680+ opM(0, true, 0C10FH, r, m, false);
681+end;
682+
683+proc movqXR*(x, r: INT);
684+begin
685+ if listing then say(text2("movq", xn(x), rn(r))); end;
686+ opR(66H, true, 6E0FH, x, r, false);
687+end;
688+
689+proc movqRX*(r, x: INT);
690+begin
691+ if listing then say(text2("movq", rn(r), xn(x))); end;
692+ opR(66H, true, 7E0FH, x, r, false);
693+end;
694+
695+(* movaps: all of xmm y to xmm x, the shortest move between two *)
696+proc movX*(x, y: INT);
697+begin
698+ if listing then say(text2("movaps", xn(x), xn(y))); end;
699+ opR(0, false, 280FH, x, y, false);
700+end;
701+
702+(* The prefix of a real instruction, and the end of its name: sd, or ss for single *)
703+proc realPfx(single: BOOL): INT;
704+begin
705+ if single then return 0F3H; end;
706+ return 0F2H;
707+end;
708+
709+proc realEnd(single: BOOL): []U8;
710+begin
711+ if single then return "ss"; end;
712+ return "sd";
713+end;
714+
715+(* The real instructions take single: F32 (ss) rather than F64 (sd) *)
716+proc movsXM*(x: INT; m: Mem; single: BOOL);
717+begin
718+ if listing then say(text2(Diag.say("movs{}", [Fmt.str(realEnd(single)[1..2])]), xn(x), mn(m))); end;
719+ opM(realPfx(single), false, 100FH, x, m, false);
720+end;
721+
722+proc movsMX*(m: Mem; x: INT; single: BOOL);
723+begin
724+ if listing then say(text2(Diag.say("movs{}", [Fmt.str(realEnd(single)[1..2])]), mn(m), xn(x))); end;
725+ opM(realPfx(single), false, 110FH, x, m, false);
726+end;
727+
728+proc sseName(op: INT; single: BOOL): []U8;
729+begin
730+ if op = 58H then return Diag.say("add{}", [Fmt.str(realEnd(single))]); end;
731+ if op = 59H then return Diag.say("mul{}", [Fmt.str(realEnd(single))]); end;
732+ if op = 5CH then return Diag.say("sub{}", [Fmt.str(realEnd(single))]); end;
733+ if op = 5EH then return Diag.say("div{}", [Fmt.str(realEnd(single))]); end;
734+ return Diag.say("cvt{}2{}", [Fmt.str(realEnd(single)), Fmt.str(realEnd(not single))]);
735+end;
736+
737+(* 58 add, 59 mul, 5C sub, 5E div, 5A convert *)
738+proc sse*(op, x, y: INT; single: BOOL);
739+begin
740+ if listing then say(text2(sseName(op, single), xn(x), xn(y))); end;
741+ opR(realPfx(single), false, 0FH | (op shl 8), x, y, false);
742+end;
743+
744+(* The same, its right operand in memory: addsd x, [m] *)
745+proc sseM*(op, x: INT; m: Mem; single: BOOL);
746+begin
747+ if listing then say(text2(sseName(op, single), xn(x), mn(m))); end;
748+ opM(realPfx(single), false, 0FH | (op shl 8), x, m, false);
749+end;
750+
751+proc ucomis*(x, y: INT; single: BOOL);
752+begin
753+ if listing then say(text2(Diag.say("ucomi{}", [Fmt.str(realEnd(single))]), xn(x), xn(y))); end;
754+ if single then opR(0, false, 2E0FH, x, y, false); else opR(66H, false, 2E0FH, x, y, false); end;
755+end;
756+
757+proc cvtsi2s*(x, r: INT; single: BOOL);
758+begin
759+ if listing then say(text2(Diag.say("cvtsi2{}", [Fmt.str(realEnd(single))]), xn(x), rn(r))); end;
760+ opR(realPfx(single), true, 2A0FH, x, r, false);
761+end;
762+
763+proc cvtts2si*(r, x: INT; single: BOOL);
764+begin
765+ if listing then say(text2(Diag.say("cvtt{}2si", [Fmt.str(realEnd(single))]), rn(r), xn(x))); end;
766+ opR(realPfx(single), true, 2C0FH, r, x, false);
767+end;
768+
769+proc btc*(r, bit: INT);
770+begin
771+ if listing then say(text2("btc", rn(r), num(bit))); end;
772+ opR(0, true, 0BA0FH, 7, r, false);
773+ Chunk.put1(bit);
774+end;
775+
776+(* Jumps. A label not yet placed is the chain of the jumps to it, each
777+ rel32 field holding the position of the one before, NoLabel ending
778+ it. Placing the label walks the chain and patches each. *)
779+
780+proc jmp*(var L: INT);
781+begin
782+ if listing then say("jmp"); end;
783+ Chunk.put1(0E9H);
784+ Chunk.put4(L);
785+ L := Chunk.pc - 4;
786+end;
787+
788+proc jcc*(cc: INT; var L: INT);
789+begin
790+ if listing then say(Diag.say("j{}", [Fmt.str(CondNames[cc])])); end;
791+ Chunk.put1(0FH); Chunk.put1(80H + cc);
792+ Chunk.put4(L);
793+ L := Chunk.pc - 4;
794+end;
795+
796+proc jmpBack*(target: INT);
797+begin
798+ if listing then say("jmp"); end;
799+ Chunk.put1(0E9H);
800+ Chunk.put4(target - (Chunk.pc + 4));
801+end;
802+
803+proc jccBack*(cc, target: INT);
804+begin
805+ if listing then say(Diag.say("j{}", [Fmt.str(CondNames[cc])])); end;
806+ Chunk.put1(0FH); Chunk.put1(80H + cc);
807+ Chunk.put4(target - (Chunk.pc + 4));
808+end;
809+
810+proc fixLinkTo*(L, target: INT);
811+var next: INT;
812+begin
813+ while L # NoLabel do
814+ next := Chunk.get4At(L);
815+ Chunk.put4At(L, target - (L + 4));
816+ L := next;
817+ end;
818+end;
819+
820+proc fixLink*(L: INT);
821+begin
822+ fixLinkTo(L, Chunk.pc);
823+end;
824+
825+(* If the last instruction made is a jmp to L, it is taken back, since L
826+ is to be placed just after it: a return at the end of a procedure
827+ needn't jump to the code that returns. L is the place of the latest
828+ jump's 4-byte field, so the last instruction is that jump when L is
829+ 4 bytes back and an E9 byte (jmp) is before it; a jcc's field follows
830+ the bytes 0F 8x, never E9. L then becomes the next jump on the chain,
831+ which the field held. The caller must place L next, before anything
832+ can have noted where the jmp ended. *)
833+proc dropJumpTo*(var L: INT);
834+begin
835+ if (L = NoLabel) or (L # Chunk.pc - 4) or (Chunk.text[L - 1] # 0E9H) then return; end;
836+ L := Chunk.get4At(L);
837+ Chunk.takeBack(5);
838+ if listing and (numSaid > 0) and (said[numSaid - 1].at = Chunk.pc) then DEC(numSaid); end;
839+end;
840+
841+(* The jumps of chains L1 and L2, as one chain: each jump's field holds
842+ the next one's place until it is fixed, the last NoLabel *)
843+proc joinLinks*(L1, L2: INT): INT;
844+var L: INT;
845+begin
846+ if L2 = NoLabel then return L1; end;
847+ if L1 # NoLabel then
848+ L := L2;
849+ while Chunk.get4At(L) # NoLabel do L := Chunk.get4At(L); end;
850+ Chunk.put4At(L, L1);
851+ end;
852+ return L2;
853+end;
854+
855+(* The assembler, for code procedures: x86-64 in Intel's syntax as NASM
856+ writes it (report, appendix A). It reads instructions with the
857+ scanner up to end, and encodes them with opM and opR; constants are
858+ read by the parser's constExpr. *)
859+
860+const
861+ NoBase = -3; (* a memory operand's base, not yet read *)
862+
863+type
864+ OpKind = (oReg, oXmm, oMem, oImm);
865+ Operand = record
866+ kind: OpKind;
867+ r, size: INT; (* oReg, oXmm: the register and its size; oMem: its size, or 0 *)
868+ m: Mem;
869+ v: I64; (* oImm *)
870+ end;
871+
872+(* The current symbol as a word: an identifier, or a reserved word that
873+ is also an instruction *)
874+proc asmWord: []U8;
875+begin
876+ match Scan.tok of
877+ | sIdent: return Scan.nameOf(Scan.id);
878+ | sAnd: return "and";
879+ | sOr: return "or";
880+ | sXor: return "xor";
881+ | sNot: return "not";
882+ | sDiv: return "div";
883+ | sShl: return "shl";
884+ | sShr: return "shr";
885+ | else: return "";
886+ end;
887+end;
888+
889+(* Whether w names a register: rax, eax, ax, al and so on, or xmm0 to
890+ xmm15 (size 16); r and size are set if so *)
891+proc isReg(w: []U8; r, size: ^INT): BOOL;
892+const Sizes: [4]INT = [8, 4, 2, 1];
893+var i, j, n, d: INT;
894+begin
895+ for i := 0 to 3 do
896+ for j := 0 to 15 do
897+ if RegNames[i][j] = w then r^ := j; size^ := Sizes[i]; return true; end;
898+ end;
899+ end;
900+ size^ := 16;
901+ if not Str.hasPrefix(w, "xmm") or (LEN(w) <= 3) then return false; end;
902+ (* the seed read the two bytes after xmm as a number, whatever follows *)
903+ n := LEN(w) - 3;
904+ if n > 2 then n := 2; end;
905+ r^ := 0;
906+ for i := 0 to n - 1 do
907+ d := INT(w[3 + i]) - 48;
908+ if (d < 0) or (d > 9) then return false; end;
909+ r^ := r^ * 10 + d;
910+ end;
911+ return r^ <= 15;
912+end;
913+
914+(* Which word of list, a list of words each with a space either side,
915+ w is, from 0; -1 if none *)
916+proc wordIndex(w: []U8; list: []U8): INT;
917+var i, n, start: INT;
918+begin
919+ n := 0;
920+ start := 1;
921+ for i := 1 to LEN(list) - 1 do
922+ if list[i] = ' ' then
923+ if (i - start = LEN(w)) and (list[start..i] = w) then return n; end;
924+ INC(n);
925+ start := i + 1;
926+ end;
927+ end;
928+ return -1;
929+end;
930+
931+(* w from byte from on, at most n bytes of it, as copy does *)
932+proc part(w: []U8; from, n: INT): []U8;
933+var e: INT;
934+begin
935+ e := from + n;
936+ if e > LEN(w) then e := LEN(w); end;
937+ if from >= e then return ""; end;
938+ return w[from..e];
939+end;
940+
941+(* The condition a name ends in: e of je, nz of jnz *)
942+proc cond(w: []U8): INT;
943+const
944+ Alias: [12][]U8 = ["c", "nae", "nc", "nb", "z", "nz", "na", "nbe", "nge", "nl", "ng", "nle"];
945+ AliasCc: [12]INT = [2, 2, 3, 3, 4, 5, 6, 7, 12, 13, 14, 15];
946+var i: INT;
947+begin
948+ for i := 0 to 15 do
949+ if CondNames[i] = w then return i; end;
950+ end;
951+ for i := 0 to 11 do
952+ if Alias[i] = w then return AliasCc[i]; end;
953+ end;
954+ return -1;
955+end;
956+
957+proc operand(o: ^Operand; constExpr: ConstFn): ERROR;
958+var w: []U8; r, size, sz: INT; st: Scan.State; v: I64; isR, wasMinus: BOOL;
959+begin
960+ o^ := {};
961+ w := asmWord();
962+ sz := 0;
963+ if w = "byte" then sz := 1;
964+ elsif w = "word" then sz := 2;
965+ elsif w = "dword" then sz := 4;
966+ elsif w = "qword" then sz := 8;
967+ end;
968+ if sz # 0 then Scan.next; w := asmWord(); end;
969+ if Scan.tok = Scan.sLbrak then
970+ (* [base + index * scale + disp], the displacement last *)
971+ Scan.next;
972+ o^.kind := oMem; o^.size := sz;
973+ o^.m := mem(NoBase, 0);
974+ repeat
975+ if isReg(asmWord(), ADR(r), ADR(size)) and (size = 8) then
976+ Scan.next;
977+ (* the scale is a single number or constant: a whole expression
978+ would take in the displacement after it, as 4 + 16 in
979+ [rdi + rsi * 4 + 16] *)
980+ if Scan.tok = Scan.sTimes then
981+ Scan.next;
982+ o^.m.index := r;
983+ v := try constExpr(false);
984+ o^.m.scale := INT(v);
985+ elsif o^.m.base = NoBase then
986+ o^.m.base := r;
987+ else
988+ o^.m.index := r; o^.m.scale := 1;
989+ end;
990+ else
991+ v := try constExpr(true);
992+ o^.m.disp := o^.m.disp + INT(v);
993+ end;
994+ if (Scan.tok # Scan.sPlus) and (Scan.tok # Scan.sMinus) then break; end;
995+ wasMinus := Scan.tok = Scan.sMinus;
996+ Scan.saveScan(st);
997+ Scan.next;
998+ isR := isReg(asmWord(), ADR(r), ADR(size));
999+ if not isR and wasMinus then Scan.restoreScan(st); end;
1000+ until false;
1001+ if (Scan.tok # Scan.sRbrak) or (o^.m.base = NoBase)
1002+ or not ((o^.m.scale = 1) or (o^.m.scale = 2) or (o^.m.scale = 4) or (o^.m.scale = 8)) then
1003+ return Scan.mark("expected a memory operand, [base + index * scale + disp]");
1004+ end;
1005+ Scan.next;
1006+ elsif isReg(w, ADR(o^.r), ADR(o^.size)) then
1007+ if o^.size = 16 then o^.kind := oXmm; else o^.kind := oReg; end;
1008+ Scan.next;
1009+ else
1010+ o^.kind := oImm;
1011+ o^.v := try constExpr(true);
1012+ end;
1013+ return nil;
1014+end;
1015+
1016+(* op with register reg and the register or memory operand o *)
1017+proc rm(pfx: INT; w: BOOL; op, reg: INT; o: Operand; byteReg: BOOL);
1018+begin
1019+ if o.kind = oMem then opM(pfx, w, op, reg, o.m, byteReg); else opR(pfx, w, op, reg, o.r, byteReg); end;
1020+end;
1021+
1022+proc putImmV(v: I64; size: INT);
1023+begin
1024+ if size = 1 then
1025+ Chunk.put1(INT(v & 0FFH));
1026+ elsif size = 2 then
1027+ Chunk.put1(INT(v & 0FFH)); Chunk.put1(INT((v shr 8) & 0FFH));
1028+ else
1029+ Chunk.put4(INT(v & 0FFFFFFFFH));
1030+ end;
1031+end;
1032+
1033+const
1034+ Alus = " add or adc sbb and sub xor cmp ";
1035+ Unaries = " not neg mul imul div idiv ";
1036+ Shifts = " rol ror rcl rcr shl shr sal sar ";
1037+ SseOps = " sqrt add mul sub min div max ";
1038+ SseCodes: [7]INT = [51H, 58H, 59H, 5CH, 5DH, 5EH, 5FH];
1039+ (* SSE2 integer instructions that work on 16 bytes at a time: 66 0F code,
1040+ xmm and xmm or memory (pshufd also takes a byte) *)
1041+ PackedOps = " punpcklbw punpcklwd pcmpeqb pshufd pand pandn por pxor paddb psubb ";
1042+ PackedCodes: [10]INT = [60H, 61H, 74H, 70H, 0DBH, 0DFH, 0EBH, 0EFH, 0FCH, 0F8H];
1043+ (* bit scans and counts: reg, reg or memory, with the prefix and code that tell them *)
1044+ BitOps = " bsf bsr tzcnt lzcnt popcnt ";
1045+ BitPfx: [5]INT = [0, 0, 0F3H, 0F3H, 0F3H];
1046+ BitCodes: [5]INT = [0BC0FH, 0BD0FH, 0BC0FH, 0BD0FH, 0B80FH];
1047+ Plain: [15][]U8 = ["ret", "leave", "syscall", "cpuid", "rdtsc",
1048+ "pause", "nop", "ud2", "int3", "hlt", "cqo", "cdq", "mfence", "lfence", "sfence"];
1049+ PlainOp: [15]INT = [0C3H, 0C9H, 050FH, 0A20FH, 310FH,
1050+ 90F3H, 90H, 0B0FH, 0CCH, 0F4H, 9948H, 99H, 0F0AE0FH, 0E8AE0FH, 0F8AE0FH];
1051+
1052+var
1053+ (* the instruction being assembled *)
1054+ aw: []U8; (* its word *)
1055+ ao: [3]Operand; (* its operands *)
1056+ an: INT; (* how many *)
1057+ asize, apfx: INT;
1058+ awide, abyte: BOOL;
1059+ aat: Diag.Pos; (* where it starts *)
1060+ (* the labels of the procedure *)
1061+ lnames, lplaces, lchains: [64]INT;
1062+ lusedAt: [64]Diag.Pos;
1063+ numLabels: INT;
1064+
1065+(* The label called n, entered if new *)
1066+proc lab(n: INT): (INT, ERROR);
1067+var i: INT;
1068+begin
1069+ for i := 0 to numLabels - 1 do
1070+ if lnames[i] = n then return i, nil; end;
1071+ end;
1072+ if numLabels > 63 then return 0, Scan.mark("more than 64 labels"); end;
1073+ lnames[numLabels] := n; lplaces[numLabels] := -1; lchains[numLabels] := NoLabel;
1074+ lusedAt[numLabels] := Scan.tokPos();
1075+ numLabels := numLabels + 1;
1076+ return numLabels - 1, nil;
1077+end;
1078+
1079+proc bad: ERROR;
1080+begin
1081+ return Scan.markAt(aat, Diag.say("can't assemble {} with these operands", [Fmt.str(aw)]));
1082+end;
1083+
1084+(* an instruction of two operands: a register or memory, and a
1085+ register (opcode toRM), the other way (fromRM), or an immediate
1086+ (opImm /digit, or none if opImm < 0) *)
1087+proc two(toRM, fromRM, opImm, digit: INT): ERROR;
1088+var b: INT;
1089+begin
1090+ b := 0;
1091+ if abyte then b := 1; end;
1092+ if an # 2 then return bad(); end;
1093+ if ao[1].kind = oImm then
1094+ if (ao[0].kind = oImm) or (opImm < 0) then return bad(); end;
1095+ if (opImm = 81H) and not abyte and (ao[1].v >= -128) and (ao[1].v <= 127) then
1096+ rm(apfx, awide, 83H, digit, ao[0], false); (* a byte, sign-extended *)
1097+ Chunk.put1(INT(ao[1].v & 0FFH));
1098+ else
1099+ rm(apfx, awide, opImm - b, digit, ao[0], false);
1100+ putImmV(ao[1].v, asize);
1101+ end;
1102+ elsif (ao[1].kind = oReg) and ((ao[0].kind = oReg) or (ao[0].kind = oMem)) then
1103+ rm(apfx, awide, toRM - b, ao[1].r, ao[0], abyte);
1104+ elsif (ao[0].kind = oReg) and (ao[1].kind = oMem) then
1105+ rm(apfx, awide, fromRM - b, ao[0].r, ao[1], abyte);
1106+ else
1107+ return bad();
1108+ end;
1109+ return nil;
1110+end;
1111+
1112+(* whether operand i is an xmm register or a memory operand *)
1113+proc isXM(i: INT): BOOL;
1114+begin
1115+ return (ao[i].kind = oXmm) or (ao[i].kind = oMem);
1116+end;
1117+
1118+(* whether operand i is a general register or a memory operand, for an
1119+ xmm register's partner *)
1120+proc isRMem(i: INT): BOOL;
1121+begin
1122+ return (ao[i].kind = oReg) or (ao[i].kind = oMem);
1123+end;
1124+
1125+(* b as 1 for true *)
1126+proc bit(f: BOOL): INT;
1127+begin
1128+ if f then return 1; end;
1129+ return 0;
1130+end;
1131+
1132+(* The instruction w with its operands, in ao and an, apart from the
1133+ jumps to labels and db, which assemble does *)
1134+proc instruction(): ERROR;
1135+var k: INT;
1136+begin
1137+ if wordIndex(aw, Alus) >= 0 then
1138+ k := wordIndex(aw, Alus);
1139+ return two(k * 8 + 1, k * 8 + 3, 81H, k);
1140+ elsif aw = "mov" then
1141+ if (an = 2) and (ao[0].kind = oReg) and (ao[1].kind = oImm) and (asize >= 4) then
1142+ if awide then
1143+ movRI(ao[0].r, ao[1].v);
1144+ else
1145+ prefix(0, false, 0, NoIndex, ao[0].r, false); Chunk.put1(0B8H + (ao[0].r & 7)); Chunk.put4(INT(ao[1].v & 0FFFFFFFFH));
1146+ end;
1147+ return nil;
1148+ end;
1149+ return two(89H, 8BH, 0C7H, 0);
1150+ elsif aw = "test" then
1151+ return two(85H, 85H, 0F7H, 0);
1152+ elsif aw = "xchg" then
1153+ return two(87H, 87H, -1, 0);
1154+ elsif (aw = "cmpxchg") or (aw = "xadd") then
1155+ if (an # 2) or (ao[1].kind # oReg) then return bad(); end;
1156+ if aw = "xadd" then k := 0C10FH; else k := 0B10FH; end;
1157+ rm(apfx, awide, k - (bit(abyte) shl 8), ao[1].r, ao[0], abyte);
1158+ elsif aw = "lea" then
1159+ if (an # 2) or (ao[0].kind # oReg) or (ao[1].kind # oMem) then return bad(); end;
1160+ rm(apfx, awide, 8DH, ao[0].r, ao[1], false);
1161+ elsif (aw = "movzx") or (aw = "movsx") or (aw = "movsxd") then
1162+ if (an # 2) or (ao[0].kind # oReg) or (ao[1].kind = oImm) then return bad(); end;
1163+ if aw = "movsxd" then
1164+ k := 63H;
1165+ elsif ao[1].size = 1 then
1166+ k := 0B60FH;
1167+ elsif ao[1].size = 2 then
1168+ k := 0B70FH;
1169+ else
1170+ return bad();
1171+ end;
1172+ if aw = "movsx" then k := k + 0800H; end;
1173+ rm(apfx, awide, k, ao[0].r, ao[1], ao[1].size = 1);
1174+ elsif ((wordIndex(aw, Unaries) >= 0) and (an = 1)) or (aw = "inc") or (aw = "dec") then
1175+ if ao[0].kind = oImm then return bad(); end;
1176+ if aw = "inc" then
1177+ rm(apfx, awide, 0FFH - bit(abyte), 0, ao[0], abyte);
1178+ elsif aw = "dec" then
1179+ rm(apfx, awide, 0FFH - bit(abyte), 1, ao[0], abyte);
1180+ else
1181+ rm(apfx, awide, 0F7H - bit(abyte), wordIndex(aw, Unaries) + 2, ao[0], abyte);
1182+ end;
1183+ elsif aw = "imul" then
1184+ if (an < 2) or (ao[0].kind # oReg) or (ao[1].kind = oImm) then return bad(); end;
1185+ if an = 2 then
1186+ rm(apfx, awide, 0AF0FH, ao[0].r, ao[1], false);
1187+ else
1188+ rm(apfx, awide, 69H, ao[0].r, ao[1], false);
1189+ putImmV(ao[2].v, asize);
1190+ end;
1191+ elsif wordIndex(aw, Shifts) >= 0 then
1192+ k := wordIndex(aw, Shifts);
1193+ if k = 6 then k := 4; end; (* sal is shl *)
1194+ if (an # 2) or (ao[0].kind = oImm) then return bad(); end;
1195+ if ao[1].kind = oImm then
1196+ rm(apfx, awide, 0C1H - bit(abyte), k, ao[0], abyte);
1197+ Chunk.put1(INT(ao[1].v & 0FFH));
1198+ elsif (ao[1].kind = oReg) and (ao[1].r = RCX) and (ao[1].size = 1) then
1199+ rm(apfx, awide, 0D3H - bit(abyte), k, ao[0], abyte);
1200+ else
1201+ return bad();
1202+ end;
1203+ elsif (aw = "push") or (aw = "pop") then
1204+ if (an # 1) or (ao[0].kind # oReg) or not awide then return bad(); end;
1205+ if aw = "push" then push(ao[0].r); else pop(ao[0].r); end;
1206+ elsif (aw = "call") or (aw = "jmp") then
1207+ if (an # 1) or (ao[0].kind = oImm) then return bad(); end;
1208+ if aw = "call" then rm(0, false, 0FFH, 2, ao[0], false); else rm(0, false, 0FFH, 4, ao[0], false); end;
1209+ elsif Str.hasPrefix(aw, "set") and (cond(part(aw, 3, 3)) >= 0) then
1210+ if (an # 1) or (ao[0].kind = oImm) or (asize # 1) then return bad(); end;
1211+ rm(0, false, 900FH + (cond(part(aw, 3, 3)) shl 8), 0, ao[0], true);
1212+ elsif Str.hasPrefix(aw, "cmov") and (cond(part(aw, 4, 3)) >= 0) then
1213+ if (an # 2) or (ao[0].kind # oReg) or (ao[1].kind = oImm) then return bad(); end;
1214+ rm(apfx, awide, 400FH + (cond(part(aw, 4, 3)) shl 8), ao[0].r, ao[1], false);
1215+ elsif (LEN(aw) > 2) and (wordIndex(aw[0..LEN(aw) - 2], SseOps) >= 0)
1216+ and ((aw[LEN(aw) - 2..LEN(aw)] = "sd") or (aw[LEN(aw) - 2..LEN(aw)] = "ss")) then
1217+ (* sqrtsd, addss and the like: xmm, xmm or memory *)
1218+ if (an # 2) or (ao[0].kind # oXmm) or not isXM(1) then return bad(); end;
1219+ k := 0FH | (SseCodes[wordIndex(aw[0..LEN(aw) - 2], SseOps)] shl 8);
1220+ rm(realPfx(aw[LEN(aw) - 1] = 's'), false, k, ao[0].r, ao[1], false);
1221+ elsif wordIndex(aw, PackedOps) >= 0 then
1222+ if (an < 2) or (ao[0].kind # oXmm) or not isXM(1) then return bad(); end;
1223+ k := wordIndex(aw, PackedOps);
1224+ rm(66H, false, 0FH | (PackedCodes[k] shl 8), ao[0].r, ao[1], false);
1225+ if aw = "pshufd" then
1226+ if (an # 3) or (ao[2].kind # oImm) then return bad(); end;
1227+ Chunk.put1(INT(ao[2].v & 0FFH));
1228+ elsif an # 2 then
1229+ return bad();
1230+ end;
1231+ elsif (aw = "movdqu") or (aw = "movdqa") then
1232+ (* the load is 6F and the store 7F; movdqu is F3, movdqa 66 *)
1233+ if aw = "movdqu" then k := 0F3H; else k := 66H; end;
1234+ if (an = 2) and (ao[0].kind = oXmm) and isXM(1) then
1235+ rm(k, false, 6F0FH, ao[0].r, ao[1], false);
1236+ elsif (an = 2) and (ao[0].kind = oMem) and (ao[1].kind = oXmm) then
1237+ rm(k, false, 7F0FH, ao[1].r, ao[0], false);
1238+ else
1239+ return bad();
1240+ end;
1241+ elsif aw = "pmovmskb" then
1242+ if (an # 2) or (ao[0].kind # oReg) or (ao[1].kind # oXmm) then return bad(); end;
1243+ rm(66H, false, 0D70FH, ao[0].r, ao[1], false);
1244+ elsif wordIndex(aw, BitOps) >= 0 then
1245+ if (an # 2) or (ao[0].kind # oReg) or (ao[1].kind = oImm) or (asize < 4) then return bad(); end;
1246+ k := wordIndex(aw, BitOps);
1247+ rm(BitPfx[k], awide, BitCodes[k], ao[0].r, ao[1], false);
1248+ elsif (aw = "movsd") or (aw = "movss") then
1249+ if aw = "movsd" then k := 0F2H; else k := 0F3H; end;
1250+ if (an = 2) and (ao[0].kind = oXmm) and isXM(1) then
1251+ rm(k, false, 100FH, ao[0].r, ao[1], false);
1252+ elsif (an = 2) and (ao[0].kind = oMem) and (ao[1].kind = oXmm) then
1253+ rm(k, false, 110FH, ao[1].r, ao[0], false);
1254+ else
1255+ return bad();
1256+ end;
1257+ elsif (aw = "movq") or (aw = "movd") then
1258+ if (an = 2) and (ao[0].kind = oXmm) and isRMem(1) then
1259+ rm(66H, aw = "movq", 6E0FH, ao[0].r, ao[1], false);
1260+ elsif (an = 2) and (ao[1].kind = oXmm) and isRMem(0) then
1261+ rm(66H, aw = "movq", 7E0FH, ao[1].r, ao[0], false);
1262+ else
1263+ return bad();
1264+ end;
1265+ elsif (aw = "ucomisd") or (aw = "ucomiss") then
1266+ if (an # 2) or (ao[0].kind # oXmm) or not isXM(1) then return bad(); end;
1267+ if aw = "ucomisd" then
1268+ rm(66H, false, 2E0FH, ao[0].r, ao[1], false);
1269+ else
1270+ rm(0, false, 2E0FH, ao[0].r, ao[1], false);
1271+ end;
1272+ elsif (aw = "cvtsi2sd") or (aw = "cvtsi2ss") then
1273+ if (an # 2) or (ao[0].kind # oXmm) or not isRMem(1) then return bad(); end;
1274+ rm(realPfx(aw = "cvtsi2ss"), ao[1].size # 4, 2A0FH, ao[0].r, ao[1], false);
1275+ elsif (aw = "cvttsd2si") or (aw = "cvttss2si") then
1276+ if (an # 2) or (ao[0].kind # oReg) or not isXM(1) then return bad(); end;
1277+ rm(realPfx(aw = "cvttss2si"), awide, 2C0FH, ao[0].r, ao[1], false);
1278+ elsif (aw = "cvtsd2ss") or (aw = "cvtss2sd") then
1279+ if (an # 2) or (ao[0].kind # oXmm) or not isXM(1) then return bad(); end;
1280+ rm(realPfx(aw = "cvtss2sd"), false, 5A0FH, ao[0].r, ao[1], false);
1281+ else
1282+ k := 0;
1283+ while (k <= 14) and (Plain[k] # aw) do INC(k); end;
1284+ if (k > 14) or (an # 0) then
1285+ return Scan.markAt(aat, Diag.say("unknown instruction {}", [Fmt.str(aw)]));
1286+ end;
1287+ opcode(PlainOp[k]);
1288+ end;
1289+ return nil;
1290+end;
1291+
1292+(* One instruction or label, as assemble reads it *)
1293+proc statement(constExpr: ConstFn): ERROR;
1294+var
1295+ i, k, cc, first: INT; wasListing: BOOL; start: Diag.Pos; v: I64;
1296+begin
1297+ aat := Scan.tokPos();
1298+ aw := asmWord();
1299+ if LEN(aw) = 0 then return Scan.mark("expected an instruction"); end;
1300+ Scan.next;
1301+ if Scan.tok = Scan.sColon then
1302+ sayAt(Chunk.pc, Diag.say("{}:", [Fmt.str(aw)]));
1303+ k := try lab(Scan.intern(ADR(aw[0]), LEN(aw)));
1304+ if lplaces[k] >= 0 then
1305+ return Scan.markAt(aat, Diag.say("label {} is defined twice", [Fmt.str(aw)]));
1306+ end;
1307+ lplaces[k] := Chunk.pc;
1308+ fixLink(lchains[k]);
1309+ Scan.next;
1310+ return nil;
1311+ end;
1312+ first := Chunk.pc;
1313+ wasListing := listing;
1314+ listing := false; (* the instruction is said as it is written *)
1315+ if aw = "lock" then
1316+ Chunk.put1(0F0H);
1317+ aw := asmWord();
1318+ Scan.next;
1319+ end;
1320+ cc := -1;
1321+ if aw = "db" then
1322+ repeat
1323+ start := Scan.tokPos();
1324+ v := try constExpr(true);
1325+ if (v < -128) or (v > 255) then
1326+ return Scan.markAt(Scan.spanFrom(start), Diag.say("expected a byte from 0 to 255, found {}", [Fmt.int(v)]));
1327+ end;
1328+ Chunk.put1(INT(v & 0FFH));
1329+ if Scan.tok # Scan.sComma then break; end;
1330+ Scan.next;
1331+ until false;
1332+ elsif (aw[0] = 'j') and ((aw = "jmp") or (cond(part(aw, 1, 3)) >= 0)) and (Scan.tok = Scan.sIdent) then
1333+ (* a jump to a label *)
1334+ k := try lab(Scan.id);
1335+ Scan.next;
1336+ if aw # "jmp" then cc := cond(part(aw, 1, 3)); end;
1337+ if lplaces[k] >= 0 then
1338+ if cc < 0 then jmpBack(lplaces[k]); else jccBack(cc, lplaces[k]); end;
1339+ elsif cc < 0 then
1340+ jmp(lchains[k]);
1341+ else
1342+ jcc(cc, lchains[k]);
1343+ end;
1344+ else
1345+ an := 0;
1346+ if Scan.tok # Scan.sSemicolon then
1347+ repeat
1348+ if an > 2 then return Scan.mark("too many operands"); end;
1349+ try operand(ADR(ao[an]), constExpr);
1350+ INC(an);
1351+ if Scan.tok # Scan.sComma then break; end;
1352+ Scan.next;
1353+ until false;
1354+ end;
1355+ (* the size: a register's, or what the memory operand says *)
1356+ asize := 8;
1357+ for i := an - 1 to 0 by -1 do
1358+ if (ao[i].kind = oReg) or ((ao[i].kind = oMem) and (ao[i].size # 0)) then asize := ao[i].size; end;
1359+ end;
1360+ if an > 0 then
1361+ if (ao[0].kind = oReg) or ((ao[0].kind = oMem) and (ao[0].size # 0)) then asize := ao[0].size; end;
1362+ end;
1363+ awide := asize = 8;
1364+ abyte := asize = 1;
1365+ if asize = 2 then apfx := 66H; else apfx := 0; end;
1366+ try instruction();
1367+ end;
1368+ if Scan.tok # Scan.sSemicolon then return Scan.mark("expected \";\""); end;
1369+ listing := wasListing;
1370+ sayAt(first, Diag.source(Scan.spanFrom(aat)));
1371+ Scan.next;
1372+ return nil;
1373+end;
1374+
1375+proc assemble*(constExpr: ConstFn): ERROR;
1376+var k: INT;
1377+begin
1378+ numLabels := 0;
1379+ while (Scan.tok # Scan.sEnd) and (Scan.tok # Scan.sEof) do
1380+ if Scan.tok = Scan.sSemicolon then
1381+ Scan.next;
1382+ else
1383+ try statement(constExpr);
1384+ end;
1385+ end;
1386+ for k := 0 to numLabels - 1 do
1387+ if lplaces[k] < 0 then
1388+ return Scan.markAt(lusedAt[k], Diag.say("label {} isn't defined", [Fmt.str(Scan.nameOf(lnames[k]))]));
1389+ end;
1390+ end;
1391+ return nil;
1392+end;
1393+
1394+(* Whether s holds a space *)
1395+proc hasSpace(s: []U8): BOOL;
1396+var i: INT;
1397+begin
1398+ for i := 0 to LEN(s) - 1 do
1399+ if s[i] = ' ' then return true; end;
1400+ end;
1401+ return false;
1402+end;
1403+
1404+(* n, in decimal, at least w wide, as write(n: w) *)
1405+proc padded(n, w: INT);
1406+var s: []U8; i: INT;
1407+begin
1408+ s := Diag.say("{}", [Fmt.int(n)]);
1409+ for i := LEN(s) to w - 1 do Out.str(" "); end;
1410+ Out.str(s);
1411+end;
1412+
1413+(* The listing, raz -S: each live procedure of the module in the order
1414+ it was made, each line of source it comes from, and under it the
1415+ instructions made for it, at their offsets in the procedure; a jump
1416+ within it says where to by its offset too. *)
1417+proc list*(home: INT);
1418+var order: ^INT; n, i, j, k, c, t, line: INT; text: []U8;
1419+begin
1420+ order := ^INT(Scan.grab(Chunk.numChunks * SIZE(INT)));
1421+ n := 0;
1422+ for c := 0 to Chunk.numChunks - 1 do
1423+ if Chunk.chunks[c].live and (Chunk.chunks[c].sec = Chunk.secText) and (Chunk.chunks[c].home = home) then
1424+ i := n;
1425+ while (i > 0) and (Chunk.chunks[order[i - 1]].start > Chunk.chunks[c].start) do
1426+ order[i] := order[i - 1];
1427+ DEC(i);
1428+ end;
1429+ order[i] := c;
1430+ INC(n);
1431+ end;
1432+ end;
1433+ i := 0; j := 0;
1434+ for k := 0 to n - 1 do
1435+ c := order[k];
1436+ Out.ln;
1437+ Out.str(Chunk.chunkName(c)); Out.str(":\n");
1438+ line := -1;
1439+ while (i < numSaid) and (said[i].at < Chunk.chunks[c].start) do INC(i); end;
1440+ while (i < numSaid) and (said[i].at < Chunk.chunks[c].start + Chunk.chunks[c].size) do
1441+ while (j < Chunk.numLines) and (Chunk.lines[j].at <= said[i].at) do
1442+ if (Chunk.lines[j].chunk = c) and (Chunk.lines[j].line # line) then
1443+ line := Chunk.lines[j].line;
1444+ padded(line, 6);
1445+ Out.str(" ");
1446+ Out.str(Diag.lineText(Scan.nameOf(Chunk.lines[j].path), line));
1447+ Out.ln;
1448+ end;
1449+ INC(j);
1450+ end;
1451+ text := said[i].text;
1452+ t := said[i].at;
1453+ if (text = "jmp") or (text = "call") then
1454+ text := Diag.say("{} {}", [Fmt.str(text), Fmt.int(t + 5 + Chunk.get4At(t + 1) - Chunk.chunks[c].start)]);
1455+ elsif (text[0] = 'j') and not hasSpace(text) then
1456+ text := Diag.say("{} {}", [Fmt.str(text), Fmt.int(t + 6 + Chunk.get4At(t + 2) - Chunk.chunks[c].start)]);
1457+ end;
1458+ padded(t - Chunk.chunks[c].start, 14);
1459+ Out.str(" ");
1460+ Out.str(text);
1461+ Out.ln;
1462+ INC(i);
1463+ end;
1464+ end;
1465+end;
1466+
1467+begin
1468+ listing := false;
1469+ numSaid := 0;
1470+ saidCap := 0;
1471+ said := nil;
1472+end X64.

src/bench.sh (history) added (executable) +34 -0

@@ -0,0 +1,34 @@
1+#!/bin/sh
2+# The scanner's speed against the seed's, on the compiler's own
3+# benchmark program: the best of seven runs of each. Run from the
4+# repository root, after src/check.sh has built the tests.
5+set -e
6+b=build/self
7+python3 test/genbench.py 12000 >$b/Bench.raz
8+fpc -O2 -Mobjfpc -Sh- -vew -FUbuild -Fuseed -o$b/scanbench.seed src/test/ScanBench.pas >/dev/null
9+./raz -Werror -I src -o $b/scanbench.self src/test/ScanBench.raz
10+echo "$(wc -l <$b/Bench.raz) lines"
11+for t in seed self; do
12+ best=0
13+ for i in 1 2 3 4 5 6 7; do
14+ s=$(date +%s%N); $b/scanbench.$t $b/Bench.raz >/dev/null; e=$(date +%s%N)
15+ d=$(( (e - s) / 1000000 )); if [ $best = 0 ] || [ $d -lt $best ]; then best=$d; fi
16+ done
17+ echo "$t: $best ms"
18+done
19+
20+# The whole compiler's speed, the seed's and this one's, on the same
21+# program: the best of five runs of each, as build/cmp/raz, which finds
22+# the library beside it.
23+mkdir -p build/cmp/bench
24+ln -sfn ../../lib build/cmp/lib
25+cp $b/Bench.raz build/cmp/bench/Bench.raz
26+for t in seed self; do
27+ if [ $t = seed ]; then cp raz build/cmp/raz; else cp $b/raz.self build/cmp/raz; fi
28+ best=0
29+ for i in 1 2 3 4 5; do
30+ s=$(date +%s%N); build/cmp/raz -o build/cmp/bench/Bench.$t build/cmp/bench/Bench.raz; e=$(date +%s%N)
31+ d=$(( (e - s) / 1000000 )); if [ $best = 0 ] || [ $d -lt $best ]; then best=$d; fi
32+ done
33+ echo "compile, $t: $best ms"
34+done

src/check.sh added (executable) +180 -0

@@ -0,0 +1,180 @@
1+#!/bin/sh
2+# Tests src/'s units against the seed's: each dumper reads the same
3+# files and must give the same standard output, standard error and
4+# status. Run from the repository root, after `make raz`; the seed's
5+# side is built by fpc from seed/.
6+set -e
7+b=build/self
8+mkdir -p $b
9+fpc -O2 -Mobjfpc -Sh- -vew -FUbuild -Fuseed -o$b/scandump.seed src/test/ScanDump.pas >/dev/null
10+./raz -Werror -I src -o $b/scandump.self src/test/ScanDump.raz
11+python3 src/test/genreals.py > $b/reals.raz
12+# one small file for each message the scanner makes, and the places
13+# diag shows them in: a tab, a long line, characters before the place
14+mkdir -p $b/lex
15+python3 src/test/genlex.py $b/lex
16+n=0; bad=0
17+for f in $b/lex/*.raz lib/*.raz examples/*.raz tools/*.raz src/*.raz src/test/*.raz test/run/*.raz test/err/*.raz \
18+ conform/*/*.raz $b/reals.raz; do
19+ [ -f "$f" ] || continue
20+ s1=0; s2=0
21+ $b/scandump.seed $f >$b/seed.out 2>$b/seed.err || s1=$?
22+ $b/scandump.self $f >$b/self.out 2>$b/self.err || s2=$?
23+ n=$((n + 1))
24+ if [ $s1 != $s2 ] || ! cmp -s $b/seed.out $b/self.out || ! cmp -s $b/seed.err $b/self.err; then
25+ echo "differs: $f (status $s1 and $s2)"; bad=$((bad + 1))
26+ fi
27+done
28+echo "$n files, $bad differ"
29+test $bad = 0
30+
31+# Jump: a parser's way of going on after an error
32+./raz -Werror -I src -o $b/recover src/test/Recover.raz
33+printf 'a bad b bad bad c\nd bad\n' >$b/rec.raz
34+r=$($b/recover $b/rec.raz 2>/dev/null) || test $? = 1
35+test "$r" = "8 names, 4 failed, 4 errors" && echo "recover ok"
36+
37+# Chunk and Sym: a fixed pseudo-random script each, run by both sides,
38+# which print all they have made or answered; Sym also ends, as the
39+# argument says, in an error, whose message and status must agree
40+for u in Chunk Sym; do
41+ l=$(echo $u | tr A-Z a-z)
42+ fpc -O2 -Mobjfpc -Sh- -vew -FUbuild -Fuseed -o$b/${l}dump.seed src/test/${u}Dump.pas >/dev/null
43+ ./raz -Werror -I src -o $b/${l}dump.self src/test/${u}Dump.raz
44+done
45+for a in "" dup deep; do
46+ for s in seed self; do
47+ t=0; $b/chunkdump.$s >$b/chunk.$s 2>/dev/null || t=$?
48+ t2=0; $b/symdump.$s $a >$b/sym.$s.out 2>$b/sym.$s.err || t2=$?
49+ echo "$t $t2" >$b/status.$s
50+ done
51+ cmp $b/status.seed $b/status.self
52+ cmp $b/chunk.seed $b/chunk.self
53+ cmp $b/sym.seed.out $b/sym.self.out
54+ cmp $b/sym.seed.err $b/sym.self.err
55+done
56+echo "chunk and sym ok"
57+
58+# Link and Elf: a program of chunks made by a script, linked and written
59+# as a static, a dynamic and a stripped executable, which must be the
60+# same file from both sides
61+fpc -O2 -Mobjfpc -Sh- -vew -FUbuild -Fuseed -o$b/linkdump.seed src/test/LinkDump.pas >/dev/null
62+./raz -Werror -I src -o $b/linkdump.self src/test/LinkDump.raz
63+for m in 0 1 2; do
64+ $b/linkdump.seed $m $b/link.seed
65+ $b/linkdump.self $m $b/link.self
66+ cmp $b/link.seed $b/link.self
67+done
68+echo "link and elf ok"
69+
70+# X64: every encoder, then the assembler on a long run of instructions
71+# of every kind and a file for each error it makes; the bytes and the
72+# listing, or the message and status, must be the same
73+fpc -O2 -Mobjfpc -Sh- -vew -FUbuild -Fuseed -o$b/x64dump.seed src/test/X64Dump.pas >/dev/null
74+./raz -Werror -I src -o $b/x64dump.self src/test/X64Dump.raz
75+$b/x64dump.seed >$b/x64.seed
76+$b/x64dump.self >$b/x64.self
77+cmp $b/x64.seed $b/x64.self
78+fpc -O2 -Mobjfpc -Sh- -vew -FUbuild -Fuseed -o$b/asmdump.seed src/test/AsmDump.pas >/dev/null
79+./raz -Werror -I src -o $b/asmdump.self src/test/AsmDump.raz
80+mkdir -p $b/asm
81+python3 src/test/genasm.py $b/asm
82+n=0; bad=0
83+for f in $b/asm/*.raz; do
84+ s1=0; s2=0
85+ $b/asmdump.seed $f >$b/seed.out 2>$b/seed.err || s1=$?
86+ $b/asmdump.self $f >$b/self.out 2>$b/self.err || s2=$?
87+ n=$((n + 1))
88+ if [ $s1 != $s2 ] || ! cmp -s $b/seed.out $b/self.out || ! cmp -s $b/seed.err $b/self.err; then
89+ echo "differs: $f (status $s1 and $s2)"; bad=$((bad + 1))
90+ fi
91+done
92+echo "x64: $n assembler files, $bad differ"
93+test $bad = 0
94+
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.self src/test/GenDump.raz
101+for a in "" dyn; do
102+ $b/gendump.seed $a >$b/gen.seed
103+ $b/gendump.self $a >$b/gen.self
104+ cmp $b/gen.seed $b/gen.self
105+done
106+echo "gen ok"
107+
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.self 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.self $a >$b/self.out 2>$b/self.err || s2=$?
119+ n=$((n + 1))
120+ if [ $s1 != $s2 ] || ! cmp -s $b/seed.out $b/self.out || ! cmp -s $b/seed.err $b/self.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+
127+# 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
130+# one's own options. Both sides run as build/cmp/raz, since a program
131+# holds the paths it was made from and the library is found beside the
132+# compiler.
133+printf 'module Version;\nconst Text* = "%s";\nend Version.\n' "$(tr -d "'" < build/version.inc)" >$b/Version.raz
134+./raz -Werror -I src -I $b -o $b/raz.self src/Raz.raz
135+c=build/cmp
136+mkdir -p $c
137+ln -sfn ../../lib $c/lib
138+# and the big program that times the compiler, 348,025 lines
139+mkdir -p $c/bench
140+python3 test/genbench.py 12000 >$c/bench/Bench.raz
141+files=
142+for f in $c/bench/Bench.raz lib/*.raz examples/*.raz tools/*.raz src/*.raz test/run/*.raz test/libc/*.raz test/bench/*.raz \
143+ conform/run/*.raz test/err/*.raz conform/err/*.raz; do
144+ files="$files $f"
145+done
146+for side in seed self; do
147+ rm -rf $c/$side
148+ mkdir -p $c/$side
149+ if [ $side = seed ]; then cp raz $c/raz; else cp $b/raz.self $c/raz; fi
150+ for f in $files; do
151+ dir=$(dirname $f); name=$(basename $f .raz); x=$(echo $dir | tr / _).$name
152+ flags=
153+ case $dir in
154+ examples|tools|lib|src) flags=-Werror ;;
155+ esac
156+ [ -f $dir/$name.args ] && [ $dir = test/err ] && flags="$flags $(cat $dir/$name.args)"
157+ case $dir in
158+ lib) opts= ;;
159+ src|tools) opts="-I src -I build/self" ;;
160+ test/err) opts="-I test/err/mods -I test/run/mods" ;;
161+ *) opts="-I $dir/mods" ;;
162+ esac
163+ s=0
164+ $c/raz $flags $opts -o $c/$side/$x $f >$c/$side/$x.out 2>$c/$side/$x.err || s=$?
165+ echo $s >$c/$side/$x.status
166+ done
167+done
168+n=0; bad=0
169+for f in $files; do
170+ x=$(dirname $f | tr / _).$(basename $f .raz)
171+ n=$((n + 1))
172+ for e in "" .out .err .status; do
173+ [ -f $c/seed/$x$e ] || [ -f $c/self/$x$e ] || continue
174+ if ! cmp -s $c/seed/$x$e $c/self/$x$e; then
175+ echo "differs: $f ($x$e)"; bad=$((bad + 1)); break
176+ fi
177+ done
178+done
179+echo "raz: $n files, $bad differ"
180+test $bad = 0

src/chunk.pas deleted +0 -318

@@ -1,318 +0,0 @@
1-{ chunk.pas: the compiled program, before it is linked.
2-
3- The code of a program is a set of chunks: one per procedure, module
4- variable and string. A chunk's bytes go in one of three sections:
5- text (code), rodata (strings and other constants), bss (variables,
6- which are all zero). A reference from code to another chunk (a call,
7- or an address) is a fixup, patched once the linker has placed every
8- chunk. Line notes say which place in the source the code from each
9- point on is for.
10-
11- Nothing here depends on the machine: text is bytes, written by the
12- encoder for the target (x64.pas).
13-
14- Depends on: scan, for errors.
15- Leaves out: the instructions; that is x64.pas. }
16-
17-unit chunk;
18-
19-{$mode objfpc}{$H-}
20-
21-interface
22-
23-uses scan, diag;
24-
25-type
26- TSection = (secText, secRodata, secBss);
27-
28- TChunk = record
29- sec: TSection;
30- start, size, align: longint; { in its section's buffer }
31- firstFix, numFix: longint; { its fixups: text's in fixups, rodata's in dataFixups }
32- module, name: longint; { for the symbol table; -1 if none }
33- adr: int64; { its address, set by the linker }
34- live: boolean; { reached from the entry point }
35- ext: boolean; { bss: the address of a C symbol, its name }
36- reals: boolean; { code: computes with reals, first at realsAt }
37- 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 }
40- end;
41-
42- { A place in the source whose code starts at a place in text: for
43- gdb, and for Rt to say where a failed check or a signal was }
44- TLine = record
45- at, chunk: longint; { the place in text, and its chunk }
46- path, line, col: longint; { the file's path, interned, the line and column }
47- end;
48-
49- { A variable of a procedure, for the trap report: Rt shows it, by
50- kind, from its place in the frame }
51- TVarNote = record
52- chunk, name: longint;
53- off: longint; { from the frame pointer }
54- kind: longint; { how Rt shows it: see link.pas }
55- end;
56-
57- TFixup = record
58- at: longint; { the 32-bit field, as an offset in text; in
59- dataFixups, the 64-bit one, from its chunk's start }
60- chunk: longint; { the chunk it refers to }
61- addend: longint; { added to the chunk's address }
62- end;
63-
64- PChunks = ^TChunkArray;
65- TChunkArray = array[0..MaxInt div SizeOf(TChunk) - 1] of TChunk;
66- PLines = ^TLineArray;
67- TLineArray = array[0..MaxInt div SizeOf(TLine) - 1] of TLine;
68- PFixups = ^TFixupArray;
69- TFixupArray = array[0..MaxInt div SizeOf(TFixup) - 1] of TFixup;
70-
71-var
72- code: PBytes; { text }
73- pc: longint; { its length }
74- rodata: PBytes;
75- rolen: longint;
76- chunks: PChunks;
77- numChunks: longint;
78- fixups: PFixups;
79- numFixups: longint;
80- { Addresses in read-only data, as in an array constant of strings:
81- each 8 bytes, the chunk's absolute address, since the executable
82- is loaded where the linker placed it }
83- dataFixups: PFixups;
84- numDataFixups: longint;
85- lines: PLines;
86- numLines: longint;
87- curFile: longint; { the file being compiled, for NoteLine }
88- curChunk: longint; { the chunk of code being written }
89- varNotes: ^TVarNote;
90- numVarNotes: longint;
91-
92-function NewChunk(sec: TSection; module, name: longint): longint;
93-procedure BeginChunk(c: longint);
94-procedure EndChunk(c: longint);
95-procedure SetData(c: longint; p: PBytes; n, align: longint);
96-procedure SetBss(c: longint; size, align: longint);
97-function ExternChunk(name: longint): longint;
98-procedure NoteLine(line, col: longint);
99-procedure AddFixup(at, chunk, addend: longint);
100-procedure AddDataFixup(c, at, chunk, addend: longint);
101-procedure NoteVar(chunk, name, off, kind: longint);
102-function ChunkName(c: longint): shortstring;
103-
104-procedure Put1(b: longint);
105-procedure Put4(v: longint);
106-procedure Put8(v: int64);
107-procedure Put4At(at, v: longint);
108-function Get4At(at: longint): longint;
109-procedure TakeBack(n: longint);
110-
111-implementation
112-
113-var
114- codeCap, roCap, chunkCap, fixCap, lineCap: longint;
115-
116-procedure Room(n: longint);
117-begin
118- if pc + n > codeCap then begin
119- codeCap := codeCap * 2 + n;
120- code := ReAllocMem(code, codeCap);
121- end;
122-end;
123-
124-procedure Put1(b: longint);
125-begin
126- if pc + 16 > codeCap then Room(16);
127- code^[pc] := byte(b);
128- inc(pc);
129-end;
130-
131-procedure Put4(v: longint);
132-begin
133- if pc + 16 > codeCap then Room(16);
134- PLongint(@code^[pc])^ := v;
135- inc(pc, 4);
136-end;
137-
138-procedure Put4At(at, v: longint);
139-begin
140- PLongint(@code^[at])^ := v;
141-end;
142-
143-function Get4At(at: longint): longint;
144-begin
145- Get4At := PLongint(@code^[at])^;
146-end;
147-
148-{ The last n bytes of code taken back. A line noted past the new end
149- now starts there, in place of one noted there before, as NoteLine
150- would have it. }
151-procedure TakeBack(n: longint);
152-begin
153- dec(pc, n);
154- if (numLines > 0) and (lines^[numLines - 1].at > pc) then begin
155- lines^[numLines - 1].at := pc;
156- if (numLines > 1) and (lines^[numLines - 2].at = pc) then begin
157- lines^[numLines - 2] := lines^[numLines - 1];
158- dec(numLines);
159- end;
160- end;
161-end;
162-
163-procedure Put8(v: int64);
164-begin
165- Put4(longint(v and $FFFFFFFF));
166- Put4(longint(v shr 32));
167-end;
168-
169-function NewChunk(sec: TSection; module, name: longint): longint;
170-begin
171- if numChunks = chunkCap then begin
172- chunkCap := chunkCap * 2;
173- chunks := ReAllocMem(chunks, chunkCap * SizeOf(TChunk));
174- end;
175- FillChar(chunks^[numChunks], SizeOf(TChunk), 0);
176- chunks^[numChunks].sec := sec;
177- chunks^[numChunks].module := module;
178- chunks^[numChunks].name := name;
179- chunks^[numChunks].align := 1;
180- chunks^[numChunks].size := -1; { not yet defined }
181- NewChunk := numChunks;
182- inc(numChunks);
183-end;
184-
185-procedure BeginChunk(c: longint);
186-begin
187- { code is aligned to 32 bytes, the windows in which x86 fetches and
188- caches it, so that a procedure's loops sit in them the same way
189- whatever comes before: rat ran 5% slower at 16, by where its loops
190- fell. Padded with CC, x86's int3: a trap if it were ever run }
191- while pc and 31 <> 0 do Put1($CC);
192- curChunk := c;
193- chunks^[c].start := pc;
194- chunks^[c].align := 32;
195- chunks^[c].firstFix := numFixups;
196-end;
197-
198-procedure EndChunk(c: longint);
199-begin
200- chunks^[c].size := pc - chunks^[c].start;
201- chunks^[c].numFix := numFixups - chunks^[c].firstFix;
202-end;
203-
204-procedure SetData(c: longint; p: PBytes; n, align: longint);
205-begin
206- if rolen + n > roCap then begin
207- roCap := roCap * 2 + n;
208- rodata := ReAllocMem(rodata, roCap);
209- end;
210- Move(p^, rodata^[rolen], n);
211- chunks^[c].firstFix := numDataFixups;
212- chunks^[c].numFix := 0;
213- chunks^[c].start := rolen;
214- chunks^[c].size := n;
215- chunks^[c].align := align;
216- inc(rolen, n);
217-end;
218-
219-procedure SetBss(c: longint; size, align: longint);
220-begin
221- chunks^[c].size := size;
222- chunks^[c].align := align;
223-end;
224-
225-{ The code from here on is for line and column of the current file. A
226- place with no code of its own gives way to the next. }
227-procedure NoteLine(line, col: longint);
228-begin
229- if (numLines > 0) and (lines^[numLines - 1].at = pc) then dec(numLines);
230- if (numLines > 0) and (lines^[numLines - 1].chunk = curChunk) and (lines^[numLines - 1].line = line)
231- and (lines^[numLines - 1].col = col) and (lines^[numLines - 1].path = curFile) then exit;
232- if numLines = lineCap then begin
233- lineCap := lineCap * 2;
234- lines := ReAllocMem(lines, lineCap * SizeOf(TLine));
235- end;
236- lines^[numLines].at := pc;
237- lines^[numLines].chunk := curChunk;
238- lines^[numLines].path := curFile;
239- lines^[numLines].line := line;
240- lines^[numLines].col := col;
241- inc(numLines);
242-end;
243-
244-{ The quadword that holds the address of C's symbol name, filled in
245- when the program starts; one for each name. }
246-function ExternChunk(name: longint): longint;
247-var c: longint;
248-begin
249- for c := 0 to numChunks - 1 do
250- if chunks^[c].ext and (chunks^[c].name = name) then exit(c);
251- c := NewChunk(secBss, -1, name);
252- SetBss(c, 8, 8);
253- chunks^[c].ext := true;
254- ExternChunk := c;
255-end;
256-
257-procedure AddFixup(at, chunk, addend: longint);
258-begin
259- if numFixups = fixCap then begin
260- fixCap := fixCap * 2;
261- fixups := ReAllocMem(fixups, fixCap * SizeOf(TFixup));
262- end;
263- fixups^[numFixups].at := at;
264- fixups^[numFixups].chunk := chunk;
265- fixups^[numFixups].addend := addend;
266- inc(numFixups);
267-end;
268-
269-{ The address of chunk, plus addend, at offset at of rodata chunk c,
270- whose data is set: its fixups follow one another. }
271-procedure AddDataFixup(c, at, chunk, addend: longint);
272-begin
273- if numDataFixups and 255 = 0 then
274- dataFixups := ReAllocMem(dataFixups, (numDataFixups + 256) * SizeOf(TFixup));
275- dataFixups^[numDataFixups].at := at;
276- dataFixups^[numDataFixups].chunk := chunk;
277- dataFixups^[numDataFixups].addend := addend;
278- inc(numDataFixups);
279- inc(chunks^[c].numFix);
280-end;
281-
282-procedure NoteVar(chunk, name, off, kind: longint);
283-begin
284- if numVarNotes and 255 = 0 then varNotes := ReAllocMem(varNotes, (numVarNotes + 256) * SizeOf(TVarNote));
285- varNotes[numVarNotes].chunk := chunk;
286- varNotes[numVarNotes].name := name;
287- varNotes[numVarNotes].off := off;
288- varNotes[numVarNotes].kind := kind;
289- inc(numVarNotes);
290-end;
291-
292-{ The name of chunk c: its module's and its own, or literal and its
293- number for a literal }
294-function ChunkName(c: longint): shortstring;
295-begin
296- with chunks^[c] do
297- if name < 0 then ChunkName := 'literal' + IntStr(c)
298- else if module < 0 then ChunkName := NameOf(name)
299- else ChunkName := NameOf(module) + '.' + NameOf(name);
300-end;
301-
302-initialization
303- codeCap := 1 shl 20;
304- code := GetMem(codeCap);
305- pc := 0;
306- roCap := 1 shl 16;
307- rodata := GetMem(roCap);
308- rolen := 0;
309- chunkCap := 1 shl 10;
310- chunks := GetMem(chunkCap * SizeOf(TChunk));
311- numChunks := 0;
312- fixCap := 1 shl 12;
313- fixups := GetMem(fixCap * SizeOf(TFixup));
314- numFixups := 0;
315- lineCap := 1 shl 12;
316- lines := GetMem(lineCap * SizeOf(TLine));
317- numLines := 0;
318-end.

src/diag.pas deleted +0 -316

@@ -1,316 +0,0 @@
1-{ diag.pas: messages.
2-
3- The one place the compiler's messages are made. A message is an
4- error or a warning at a position, which it shows as the file, line
5- and column, then the line of source with the position underlined;
6- notes, each at a position of its own, and help, a line of advice,
7- may follow it. Colour is used when standard error is a terminal and
8- NO_COLOR isn't set. diag keeps every source file it is given, so
9- that a note can show a line of a module compiled earlier.
10-
11- Depends on: BaseUnix and termio, to write and to ask about the
12- terminal.
13- Leaves out: wording. The callers say what is wrong; a message is at
14- most 255 characters, which every message so far keeps well within. }
15-
16-unit diag;
17-
18-{$mode objfpc}{$H-}
19-
20-interface
21-
22-type
23- { A stretch of a source file: bytes a up to but not including b.
24- a = b marks the place between two characters. }
25- TPos = record
26- f, a, b: longint;
27- end;
28-
29-const
30- MaxErrors = 20;
31-
32-var
33- errors, warnings: longint;
34- werror: boolean; { -Werror: a warning counts as an error }
35- { The construct being read uses a name already reported as not
36- declared: its errors follow from that one, and aren't shown. }
37- quiet: boolean;
38-
39-function AddFile(const path: shortstring; buf: PChar; len: longint): longint;
40-function ShownPath(const path: shortstring): shortstring;
41-function PathOf(f: longint): shortstring;
42-function LineOf(const p: TPos): longint;
43-function Join(const p, q: TPos): TPos;
44-function Source(const p: TPos): shortstring;
45-function LineText(const path: shortstring; line: longint): shortstring;
46-procedure Error(const p: TPos; const msg: shortstring);
47-procedure Warning(const p: TPos; const msg: shortstring);
48-procedure Note(const p: TPos; const msg: shortstring);
49-function IntStr(n: int64): shortstring;
50-procedure Help(const msg: shortstring);
51-procedure Fatal(const msg: shortstring);
52-procedure Finish;
53-
54-implementation
55-
56-uses BaseUnix, termio;
57-
58-type
59- TFile = record
60- path: shortstring;
61- buf: PChar;
62- len: longint;
63- end;
64-
65-var
66- files: ^TFile; { numFiles of them, in room for cap }
67- numFiles, cap: longint;
68- colour, colourKnown, cwdKnown: boolean;
69- cwd: shortstring; { the working directory and a /, or '' if unknown }
70- lastError: TPos; { where the last error was }
71- shown: boolean; { whether it was shown: its notes and help are only then }
72-
73-{ Paths are shown from the working directory where they are under it,
74- so messages read the same wherever the compiler or its library is. }
75-function ShownPath(const path: shortstring): shortstring;
76-var d: array[0..255] of char;
77-begin
78- if not cwdKnown then begin
79- if FpGetcwd(@d[0], SizeOf(d)) <> nil then cwd := StrPas(@d[0]) + '/';
80- cwdKnown := true;
81- end;
82- if (cwd <> '') and (copy(path, 1, length(cwd)) = cwd) then ShownPath := copy(path, length(cwd) + 1, 255)
83- else ShownPath := path;
84-end;
85-
86-function AddFile(const path: shortstring; buf: PChar; len: longint): longint;
87-begin
88- if numFiles = cap then begin
89- cap := 2 * cap + 8;
90- ReallocMem(files, cap * SizeOf(TFile));
91- end;
92- files[numFiles].path := ShownPath(path);
93- files[numFiles].buf := buf;
94- files[numFiles].len := len;
95- AddFile := numFiles;
96- inc(numFiles);
97-end;
98-
99-function PathOf(f: longint): shortstring;
100-begin
101- PathOf := files[f].path;
102-end;
103-
104-{ Writing }
105-
106-const
107- Bold = #27'[1m'; Red = #27'[1;31m'; Yellow = #27'[1;33m';
108- Cyan = #27'[1;36m'; Green = #27'[1;32m'; Blue = #27'[1;34m';
109- Plain = #27'[0m';
110-
111-{ Whether NO_COLOR is set, to anything }
112-function NoColour: boolean;
113-var e: PPChar;
114-begin
115- e := envp;
116- while (e^ <> nil) and (CompareByte(e^^, PChar('NO_COLOR=')^, 9) <> 0) do inc(e);
117- NoColour := e^ <> nil;
118-end;
119-
120-{ s in colour c, when colour is on }
121-function Paint(const c, s: shortstring): shortstring;
122-begin
123- if not colourKnown then begin
124- colour := (IsATTY(2) = 1) and not NoColour;
125- colourKnown := true;
126- end;
127- if colour then Paint := c + s + Plain else Paint := s;
128-end;
129-
130-function IntStr(n: int64): shortstring;
131-var s: shortstring;
132-begin
133- Str(n, s);
134- IntStr := s;
135-end;
136-
137-{ Positions }
138-
139-{ The line of p, and the byte where it starts. Lines are counted from
140- the start of the file, which is slow only next to compiling it. }
141-procedure Locate(const p: TPos; out line, start: longint);
142-var i: longint; buf: PChar;
143-begin
144- buf := files[p.f].buf;
145- line := 1; start := 0;
146- for i := 0 to p.a - 1 do
147- if buf[i] = #10 then begin inc(line); start := i + 1 end;
148-end;
149-
150-function LineOf(const p: TPos): longint;
151-var line, start: longint;
152-begin
153- Locate(p, line, start);
154- LineOf := line;
155-end;
156-
157-{ Characters from byte i to byte j of buf: every byte but a UTF-8
158- continuation byte. }
159-function Chars(buf: PChar; i, j: longint): longint;
160-var n: longint;
161-begin
162- n := 0;
163- for i := i to j - 1 do
164- if (byte(buf[i]) and $C0) <> $80 then inc(n);
165- Chars := n;
166-end;
167-
168-{ "file:line:col: kind: msg", then the line with p underlined. A tab
169- before p is copied into the underline, so that the two line up
170- whatever the terminal makes of tabs. }
171-{ A long line is shown cut to this many bytes around the place, its
172- cut ends marked ... }
173-const ShownBytes = 100;
174-
175-procedure Show(const p: TPos; const kind, kindColour, msg: shortstring);
176-var line, start, stop, lo, hi, i, n: longint; buf: PChar; num, gutter: shortstring;
177-begin
178- if p.f >= numFiles then begin
179- { about no place in a file, as for Rt, which the compiler imports
180- before it reads one }
181- writeln(StdErr, Paint(Bold, 'raz:'), ' ', Paint(kindColour, kind + ':'), ' ', Paint(Bold, msg));
182- exit;
183- end;
184- Locate(p, line, start);
185- buf := files[p.f].buf;
186- writeln(StdErr, Paint(Bold, files[p.f].path + ':' + IntStr(line) + ':'
187- + IntStr(Chars(buf, start, p.a) + 1) + ':'), ' ', Paint(kindColour, kind + ':'),
188- ' ', Paint(Bold, msg));
189- stop := start;
190- while (stop < files[p.f].len) and (buf[stop] <> #10) do inc(stop);
191- num := IntStr(line);
192- while length(num) < 5 do num := ' ' + num;
193- gutter := Paint(Blue, num + ' |');
194- lo := start; hi := stop;
195- if hi - lo > ShownBytes then begin
196- if p.a - lo > ShownBytes div 2 then lo := p.a - ShownBytes div 2;
197- while (byte(buf[lo]) and $C0) = $80 do inc(lo);
198- if hi - lo > ShownBytes then hi := lo + ShownBytes;
199- while (hi < stop) and ((byte(buf[hi]) and $C0) = $80) do inc(hi);
200- end;
201- write(StdErr, gutter, ' ');
202- if lo > start then write(StdErr, '...');
203- for i := lo to hi - 1 do write(StdErr, buf[i]);
204- if hi < stop then write(StdErr, '...');
205- writeln(StdErr);
206- write(StdErr, Paint(Blue, ' |'), ' ');
207- if lo > start then write(StdErr, ' ');
208- for i := lo to p.a - 1 do
209- if buf[i] = #9 then write(StdErr, #9)
210- else if (byte(buf[i]) and $C0) <> $80 then write(StdErr, ' ');
211- if p.b < hi then n := Chars(buf, p.a, p.b) else n := Chars(buf, p.a, hi);
212- if n < 1 then n := 1;
213- writeln(StdErr, Paint(kindColour, StringOfChar('^', n)));
214-end;
215-
216-{ From the start of p to the end of q }
217-function Join(const p, q: TPos): TPos;
218-begin
219- Join := p;
220- Join.b := q.b;
221-end;
222-
223-{ The text at p, at most the 255 bytes a shortstring holds }
224-function Source(const p: TPos): shortstring;
225-var n: longint;
226-begin
227- n := p.b - p.a;
228- if n > 255 then n := 255;
229- SetLength(Source, n);
230- Move(files[p.f].buf[p.a], Source[1], n);
231-end;
232-
233-{ Messages }
234-
235-{ Line line of the file at path, as written }
236-function LineText(const path: shortstring; line: longint): shortstring;
237-var i, k, n: longint; s: shortstring;
238-begin
239- s := '';
240- for i := 0 to numFiles - 1 do
241- if files[i].path = ShownPath(path) then begin
242- k := 0; n := 1;
243- while (n < line) and (k < files[i].len) do begin
244- if files[i].buf[k] = #10 then inc(n);
245- inc(k);
246- end;
247- while (k < files[i].len) and (files[i].buf[k] <> #10) and (length(s) < 255) do begin
248- s := s + files[i].buf[k];
249- inc(k);
250- end;
251- break;
252- end;
253- LineText := s;
254-end;
255-
256-procedure Error(const p: TPos; const msg: shortstring);
257-begin
258- { a second error at one place follows from the first: when a symbol
259- ends a construct with an error, the one around it may stop there too }
260- shown := not quiet and not ((errors > 0) and (p.f = lastError.f) and (p.a = lastError.a));
261- if not shown then exit;
262- lastError := p;
263- Show(p, 'error', Red, msg);
264- inc(errors);
265- if errors >= MaxErrors then begin
266- writeln(StdErr, 'raz: stopping after ', MaxErrors, ' errors');
267- Halt(1);
268- end;
269-end;
270-
271-procedure Warning(const p: TPos; const msg: shortstring);
272-begin
273- if werror then Error(p, msg)
274- else begin
275- Show(p, 'warning', Yellow, msg);
276- shown := true;
277- inc(warnings);
278- end;
279-end;
280-
281-{ Notes and help follow an error or a warning, and are shown with it }
282-procedure Note(const p: TPos; const msg: shortstring);
283-begin
284- if shown then Show(p, 'note', Cyan, msg);
285-end;
286-
287-procedure Help(const msg: shortstring);
288-begin
289- if shown then writeln(StdErr, Paint(Green, 'help:'), ' ', msg);
290-end;
291-
292-{ An error with no place in the source, such as a file that can't be
293- read: it stops the compiler at once. }
294-procedure Fatal(const msg: shortstring);
295-begin
296- writeln(StdErr, 'raz: ', msg);
297- Halt(1);
298-end;
299-
300-function Count(n: longint; const what: shortstring): shortstring;
301-begin
302- if n = 1 then Count := '1 ' + what else Count := IntStr(n) + ' ' + what + 's';
303-end;
304-
305-{ Says how many errors and warnings there were, and stops the compiler
306- if there were errors. }
307-procedure Finish;
308-begin
309- if (errors > 0) and (warnings > 0) then
310- writeln(StdErr, 'raz: ', Count(errors, 'error'), ', ', Count(warnings, 'warning'))
311- else if errors > 0 then writeln(StdErr, 'raz: ', Count(errors, 'error'))
312- else if warnings > 0 then writeln(StdErr, 'raz: ', Count(warnings, 'warning'));
313- if errors > 0 then Halt(1);
314-end;
315-
316-end.

src/elf.pas deleted +0 -373

@@ -1,373 +0,0 @@
1-{ elf.pas: the executable file.
2-
3- Writes an ELF64 executable for x86-64 Linux: the ELF header, the
4- program headers, the linked text and rodata, and section headers
5- with a symbol table, so that objdump and gdb can name each procedure
6- and variable. For gdb's line numbers there is DWARF 4: a line table
7- (.debug_line), and the one compile unit that points to it
8- (.debug_info, .debug_abbrev). There are no types or variables.
9-
10- A program that uses C is linked dynamically, in the least way the
11- loader accepts: it names its loader and libraries, and each C symbol
12- it uses is a quadword the loader fills in with the symbol's address
13- (a GLOB_DAT relocation), which the code calls or reads through.
14- There is no PLT and no lazy binding, and the program exports nothing.
15-
16- Depends on: link for the images and addresses, chunk for the chunks,
17- scan for names and errors, BaseUnix to write the file.
18- Leaves out: position independent executables, symbol versions, the
19- rest of DWARF. }
20-
21-unit elf;
22-
23-{$mode objfpc}{$H-}
24-
25-interface
26-
27-uses scan, diag, chunk, link;
28-
29-var
30- needed: array[0..31] of longint; { the libraries to load, names interned }
31- numNeeded: longint; { none: a static program }
32- mainPath: shortstring; { the main module's file, for gdb }
33- stripped: boolean; { -s: no symbols and no line numbers; the sections are there, empty }
34-
35-procedure WriteElf(const path: shortstring; entry: longint);
36-
37-implementation
38-
39-uses BaseUnix;
40-
41-var
42- buf: PBytes;
43- len, cap: int64;
44-
45-procedure Room(n: int64);
46-begin
47- if len + n > cap then begin
48- cap := cap * 2 + n;
49- buf := ReAllocMem(buf, cap);
50- end;
51-end;
52-
53-procedure PutN(v: qword; n: longint);
54-var i: longint;
55-begin
56- Room(n);
57- for i := 0 to n - 1 do begin
58- buf^[len] := byte(v);
59- v := v shr 8;
60- inc(len);
61- end;
62-end;
63-
64-procedure PutBytes(p: PBytes; n: int64);
65-begin
66- Room(n);
67- if n > 0 then Move(p^, buf^[len], n);
68- len := len + n;
69-end;
70-
71-procedure PadTo(off: int64);
72-begin
73- while len < off do PutN(0, 1);
74-end;
75-
76-procedure Patch(at: int64; v: qword; n: longint);
77-var i: longint;
78-begin
79- for i := 0 to n - 1 do begin
80- buf^[at + i] := byte(v);
81- v := v shr 8;
82- end;
83-end;
84-
85-procedure Phdr(typ, flags: longint; off, adr, filesz, memsz, align: int64);
86-begin
87- PutN(typ, 4);
88- PutN(flags, 4);
89- PutN(off, 8);
90- PutN(adr, 8);
91- PutN(adr, 8);
92- PutN(filesz, 8);
93- PutN(memsz, 8);
94- PutN(align, 8);
95-end;
96-
97-const
98- { the section names, in .shstrtab; a section header names its own }
99- ShNames = #0'.text'#0'.rodata'#0'.bss'#0'.symtab'#0'.strtab'#0'.shstrtab'#0 +
100- '.dynamic'#0'.dynstr'#0'.dynsym'#0'.debug_line'#0'.debug_info'#0'.debug_abbrev'#0;
101-
102-{ A section header. Its name is given as a string and stored as its
103- offset in ShNames: the #0 before it, counted from 1, is that offset
104- counted from 0; the empty name, found nowhere, is 0. }
105-procedure Shdr(const name: shortstring; typ: longint; flags, adr, off, size: int64; lnk, info: longint; align, entsize: int64);
106-begin
107- PutN(Pos(#0 + name + #0, ShNames), 4); PutN(typ, 4); PutN(flags, 8); PutN(adr, 8);
108- PutN(off, 8); PutN(size, 8); PutN(lnk, 4); PutN(info, 4);
109- PutN(align, 8); PutN(entsize, 8);
110-end;
111-
112-procedure PutStr(const s: shortstring);
113-begin
114- PutBytes(@s[1], length(s));
115- PutN(0, 1);
116-end;
117-
118-{ LEB128, unsigned }
119-procedure PutU(v: qword);
120-begin
121- while v >= $80 do begin
122- PutN(v and $7F or $80, 1);
123- v := v shr 7;
124- end;
125- PutN(v, 1);
126-end;
127-
128-{ The compile unit, which names the line table, and its abbreviation;
129- the table itself is in the places, in rodata (link.pas). Section
130- offsets go in off, sizes in size: line, info, abbrev. }
131-procedure PutDebug(var off, size: array of int64);
132-var cwd: array[0..255] of char;
133-begin
134- off[0] := chunks^[placesChunk].adr - roAdr + roOff + linesOff;
135- size[0] := linesSize;
136- off[1] := len;
137- PutN(0, 4); PutN(4, 2); PutN(0, 4); PutN(8, 1); { length, version, abbrev, address size }
138- PutU(1);
139- PutStr(mainPath);
140- if FpGetcwd(@cwd, SizeOf(cwd)) = nil then cwd[0] := #0;
141- PutStr(PChar(@cwd));
142- PutStr('raz');
143- PutN(0, 4); { the line table, at 0 }
144- PutN(Base + textOff, 8); PutN(textSize, 8); { the code, all of it }
145- Patch(off[1], len - off[1] - 4, 4);
146- size[1] := len - off[1];
147-
148- off[2] := len;
149- PutU(1); PutU($11); PutN(0, 1); { 1: a compile unit, no children }
150- PutU($03); PutU($08); { name, a string }
151- PutU($1B); PutU($08); { comp_dir, a string }
152- PutU($25); PutU($08); { producer, a string }
153- PutU($10); PutU($17); { stmt_list, a section offset }
154- PutU($11); PutU($01); { low_pc, an address }
155- PutU($12); PutU($07); { high_pc, a length in 8 bytes }
156- PutN(0, 2); PutN(0, 1);
157- size[2] := len - off[2];
158-end;
159-
160-const
161- Interp = '/lib64/ld-linux-x86-64.so.2';
162- { program header types }
163- PtLoad = 1; PtDynamic = 2; PtInterp = 3; PtGnuStack = $6474E551;
164-
165-var
166- { in the room at the end of rodata: where each of the loader's
167- tables starts, from extraAdr }
168- symAt, relaAt, hashAt, strAt: int64;
169- nsym, strLen: longint;
170-
171-{ The sizes of the loader's tables: what LinkAll must leave room for. }
172-procedure SizeTables(var roExtra, dynSize: int64);
173-var c, i: longint;
174-begin
175- nsym := 1;
176- strLen := 1;
177- for i := 0 to numNeeded - 1 do strLen := strLen + length(NameOf(needed[i])) + 1;
178- for c := 0 to numChunks - 1 do
179- if chunks^[c].live and chunks^[c].ext then begin
180- inc(nsym);
181- strLen := strLen + length(NameOf(chunks^[c].name)) + 1;
182- end;
183- symAt := (length(Interp) + 1 + 7) div 8 * 8;
184- relaAt := symAt + nsym * 24;
185- hashAt := relaAt + (nsym - 1) * 24;
186- strAt := hashAt + 4 * (3 + nsym);
187- roExtra := strAt + strLen;
188- dynSize := (numNeeded + 10) * 16;
189-end;
190-
191-{ The loader's tables in the room at the end of rodata, which the
192- buffer already holds as zeros: the loader's name; the symbols, one
193- for each C symbol used; a GLOB_DAT relocation for each, at its
194- quadword; a hash table of one bucket; and their names. }
195-procedure PutTables;
196-var c, k, i, at, name: longint;
197-begin
198- len := extraAdr - roAdr + roOff;
199- PutStr(Interp);
200- PadTo(extraAdr - roAdr + roOff + symAt);
201- PutN(0, 24);
202- name := strLen;
203- for c := numChunks - 1 downto 0 do { names go last in the string table }
204- if chunks^[c].live and chunks^[c].ext then name := name - length(NameOf(chunks^[c].name)) - 1;
205- for c := 0 to numChunks - 1 do
206- if chunks^[c].live and chunks^[c].ext then begin
207- PutN(name, 4); PutN($10, 1); PutN(0, 1); PutN(0, 2); { global, undefined }
208- PutN(0, 8); PutN(0, 8);
209- name := name + length(NameOf(chunks^[c].name)) + 1;
210- end;
211- k := 1;
212- for c := 0 to numChunks - 1 do
213- if chunks^[c].live and chunks^[c].ext then begin
214- PutN(chunks^[c].adr, 8);
215- PutN(qword(k) shl 32 or 6, 8); { R_X86_64_GLOB_DAT }
216- PutN(0, 8);
217- inc(k);
218- end;
219- PutN(1, 4); PutN(nsym, 4); PutN(nsym - 1, 4); { the bucket chains every symbol }
220- PutN(0, 4);
221- for i := 1 to nsym - 1 do PutN(i - 1, 4);
222- PutN(0, 1);
223- for i := 0 to numNeeded - 1 do PutStr(NameOf(needed[i]));
224- for c := 0 to numChunks - 1 do
225- if chunks^[c].live and chunks^[c].ext then PutStr(NameOf(chunks^[c].name));
226- len := roOff + roSize;
227-
228- { the dynamic table, at the start of the writable segment }
229- PadTo(bssOff);
230- at := 1;
231- for i := 0 to numNeeded - 1 do begin
232- PutN(1, 8); PutN(at, 8); { DT_NEEDED }
233- at := at + length(NameOf(needed[i])) + 1;
234- end;
235- PutN(4, 8); PutN(extraAdr + hashAt, 8); { DT_HASH }
236- PutN(5, 8); PutN(extraAdr + strAt, 8); { DT_STRTAB }
237- PutN(6, 8); PutN(extraAdr + symAt, 8); { DT_SYMTAB }
238- PutN(10, 8); PutN(strLen, 8); { DT_STRSZ }
239- PutN(11, 8); PutN(24, 8); { DT_SYMENT }
240- PutN(7, 8); PutN(extraAdr + relaAt, 8); { DT_RELA }
241- PutN(8, 8); PutN((nsym - 1) * 24, 8); { DT_RELASZ }
242- PutN(9, 8); PutN(24, 8); { DT_RELAENT }
243- PutN(21, 8); PutN(0, 8); { DT_DEBUG, for gdb }
244- PutN(0, 16); { DT_NULL }
245-end;
246-
247-procedure WriteElf(const path: shortstring; entry: longint);
248-var
249- nph, nsh, c, nsyms, fd: longint;
250- roExtra, dynSize, symOff, strOff, shstrOff, shOff, strsLen: int64;
251- dbgOff, dbgSize: array[0..2] of int64;
252- strs: PBytes;
253- s, p: shortstring;
254- sec: longint;
255- dynamic: boolean;
256-begin
257- cap := 1 shl 16;
258- buf := GetMem(cap);
259- len := 0;
260- dynamic := numNeeded > 0;
261- roExtra := 0; dynSize := 0;
262- if dynamic then SizeTables(roExtra, dynSize);
263- { room for the most program headers either kind of program has }
264- LinkAll(64 + 6 * 56, roExtra, dynSize);
265- if dynamic then nph := 6
266- else begin
267- nph := 2;
268- if roSize > 0 then inc(nph);
269- if bssSize > 0 then inc(nph);
270- end;
271-
272- { ELF header }
273- PutN($464C457F, 4); { #127 'ELF' }
274- PutN(2, 1); PutN(1, 1); PutN(1, 1); PutN(0, 9); { 64-bit, little-endian, version 1 }
275- PutN(2, 2); { ET_EXEC }
276- PutN(62, 2); { EM_X86_64 }
277- PutN(1, 4);
278- PutN(chunks^[entry].adr, 8);
279- PutN(64, 8); { program headers follow }
280- PutN(0, 8); { section headers: patched below }
281- PutN(0, 4);
282- nsh := 10;
283- if dynamic then nsh := 13;
284- PutN(64, 2); PutN(56, 2); PutN(nph, 2);
285- PutN(64, 2); PutN(nsh, 2); PutN(6, 2); { .shstrtab is section 6 }
286-
287- { flags: 4 read, 5 read and run, 6 read and write }
288- if dynamic then Phdr(PtInterp, 4, extraAdr - roAdr + roOff, extraAdr, length(Interp) + 1, length(Interp) + 1, 1);
289- { the first segment maps the headers too, so text can follow them }
290- Phdr(PtLoad, 5, 0, Base, textOff + textSize, textOff + textSize, Page);
291- if roSize > 0 then Phdr(PtLoad, 4, roOff, roAdr, roSize, roSize, Page);
292- if dynamic then begin
293- Phdr(PtLoad, 6, bssOff, bssAdr, dynSize, bssSize, Page);
294- Phdr(PtDynamic, 6, bssOff, bssAdr, dynSize, dynSize, 8);
295- end else if bssSize > 0 then Phdr(PtLoad, 6, 0, bssAdr, 0, bssSize, Page);
296- Phdr(PtGnuStack, 6, 0, 0, 0, 0, 16); { a stack that can't run code }
297-
298- PadTo(textOff);
299- PutBytes(textImg, textSize);
300- PadTo(roOff); { even when empty, so that every section lies in the file }
301- PutBytes(roImg, roSize);
302- if dynamic then PutTables;
303-
304- { the symbol table: one local symbol for each named live chunk }
305- PadTo((len + 7) div 8 * 8);
306- symOff := len;
307- strs := GetMem(1 shl 16);
308- strsLen := 1;
309- strs^[0] := 0;
310- PutN(0, 24);
311- nsyms := 1;
312- for c := 0 to numChunks - 1 do
313- if not stripped and chunks^[c].live and (chunks^[c].name >= 0) and not chunks^[c].ext then begin
314- s := ChunkName(c);
315- if strsLen + length(s) + 1 > MemSize(strs) then strs := ReAllocMem(strs, strsLen * 2 + 256);
316- Move(s[1], strs^[strsLen], length(s));
317- strs^[strsLen + length(s)] := 0;
318- case chunks^[c].sec of { the section's index in the headers below }
319- secText: sec := 1;
320- secRodata: sec := 2;
321- else sec := 3;
322- end;
323- PutN(strsLen, 4);
324- if sec = 1 then PutN(2, 1) else PutN(1, 1); { STT_FUNC, STT_OBJECT }
325- PutN(0, 1);
326- PutN(sec, 2);
327- PutN(chunks^[c].adr, 8);
328- PutN(chunks^[c].size, 8);
329- strsLen := strsLen + length(s) + 1;
330- inc(nsyms);
331- end;
332- strOff := len;
333- PutBytes(strs, strsLen);
334- shstrOff := len;
335- s := ShNames;
336- PutBytes(@s[1], length(s));
337- if stripped or (placesChunk < 0) then begin
338- for c := 0 to 2 do begin dbgOff[c] := len; dbgSize[c] := 0 end;
339- end else PutDebug(dbgOff, dbgSize);
340-
341- PadTo((len + 7) div 8 * 8);
342- shOff := len;
343- Patch(40, shOff, 8);
344- { types: 1 PROGBITS, 2 SYMTAB, 3 STRTAB, 6 DYNAMIC, 8 NOBITS, 11 DYNSYM;
345- flags: 2 ALLOC, 3 WRITE+ALLOC, 6 ALLOC+EXECINSTR. A symbol table's
346- link is its string table's index: 5 .strtab, 8 .dynstr. The order
347- here is the index the code above relies on. }
348- Shdr('', 0, 0, 0, 0, 0, 0, 0, 0, 0);
349- Shdr('.text', 1, 6, Base + textOff, textOff, textSize, 0, 0, 16, 0);
350- Shdr('.rodata', 1, 2, roAdr, roOff, roSize, 0, 0, 16, 0);
351- Shdr('.bss', 8, 3, bssAdr + dynSize, roOff + roSize, bssSize - dynSize, 0, 0, 16, 0);
352- Shdr('.symtab', 2, 0, 0, symOff, nsyms * 24, 5, nsyms, 8, 24);
353- Shdr('.strtab', 3, 0, 0, strOff, strsLen, 0, 0, 1, 0);
354- Shdr('.shstrtab', 3, 0, 0, shstrOff, length(ShNames), 0, 0, 1, 0);
355- if dynamic then begin { the loader's tables, for readelf and objdump }
356- Shdr('.dynamic', 6, 3, bssAdr, bssOff, dynSize, 8, 0, 8, 16);
357- Shdr('.dynstr', 3, 2, extraAdr + strAt, extraAdr + strAt - roAdr + roOff, strLen, 0, 0, 1, 0);
358- Shdr('.dynsym', 11, 2, extraAdr + symAt, extraAdr + symAt - roAdr + roOff, nsym * 24, 8, 1, 8, 24);
359- end;
360- Shdr('.debug_line', 1, 0, 0, dbgOff[0], dbgSize[0], 0, 0, 1, 0);
361- Shdr('.debug_info', 1, 0, 0, dbgOff[1], dbgSize[1], 0, 0, 1, 0);
362- Shdr('.debug_abbrev', 1, 0, 0, dbgOff[2], dbgSize[2], 0, 0, 1, 0);
363-
364- p := path + #0;
365- fd := FpOpen(@p[1], O_WRONLY or O_CREAT or O_TRUNC, &755);
366- if fd < 0 then Fatal('can''t write ' + path);
367- if FpWrite(fd, buf^, len) <> len then Fatal('can''t write ' + path);
368- FpClose(fd);
369- FreeMem(strs);
370- FreeMem(buf);
371-end;
372-
373-end.

src/fixpoint.sh (history) added (executable) +27 -0

@@ -0,0 +1,27 @@
1+#!/bin/sh
2+# The fixpoint: the seed builds src/ (stage 1), that builds src/
3+# (stage 2), that builds it again (stage 3), and stages 2 and 3 must
4+# be the same file. A program holds the paths it was made from, so each
5+# stage is built by the same command in the same place, from the
6+# compiler before it copied to build/fix/raz. Run from the repository
7+# root, after `make raz`. Then stage 3 stands in for ./raz (messages name
8+# the library by its path from the compiler, so it must be at the root)
9+# while `make check` and `make bench` run on it; the seed's comes back.
10+set -e
11+d=build/fix
12+rm -rf $d
13+mkdir -p $d/v
14+ln -s ../../lib $d/lib
15+printf 'module Version;\nconst Text* = "%s";\nend Version.\n' "$(tr -d "'" < build/version.inc)" >$d/v/Version.raz
16+cp raz $d/stage0
17+for n in 1 2 3; do
18+ cp $d/stage$((n - 1)) $d/raz
19+ $d/raz -Werror -I src -I $d/v -o $d/stage$n src/Raz.raz
20+done
21+cmp $d/stage2 $d/stage3
22+echo "fixpoint: stages 2 and 3 are the same, $(wc -c <$d/stage3) bytes"
23+cp raz $d/seed
24+trap 'cp $d/seed raz' EXIT
25+cp $d/stage3 raz
26+make check
27+make bench

src/gen.pas deleted +0 -2322

@@ -1,2322 +0,0 @@
1-{ gen.pas: the code generator, for x86-64.
2-
3- item.pas and parse.pas drive a stack machine: they push constants,
4- addresses and the values of variables, operate on the values on top,
5- store them and jump on them. Every value has a kind: a word, which
6- is an integer as big as an address, a pointer, a BOOL, a set or a
7- narrower integer; a long, a 64-bit integer on a machine whose word is
8- smaller (never here); an F32; an F64. This unit makes the machine's
9- code for those calls, and nothing above it knows the machine: a port
10- is a new gen.pas, with an encoder of its own.
11-
12- The stack is kept in registers, as in Wirth's compilers (Niklaus
13- Wirth's Pascal and Oberon compilers): the value at depth d, depth 0
14- being the bottom, is in r8 to r11, register d mod 4, or in xmm8 to
15- xmm11 if it is a real. A value that needs a register a lower one
16- holds spills that one: stores it in a frame slot, to free the
17- register. A constant, or an address in the
18- frame or of a chunk, is only noted until something needs it in a
19- register, so that it can be an instruction's operand.
20-
21- A slice is two words, a pointer and then a length.
22-
23- Calls use the System V convention, which x86-64 Linux has for C:
24- arguments in rdi, rsi, rdx, rcx, r8, r9 and xmm0 to xmm7, the rest on
25- the machine's stack; rbx, rbp and r12 to r15 are callee-saved, which
26- is to say a called procedure gives them back as it found them. The
27- arguments are computed left to right onto the stack of values, and
28- moved into their registers just before the call: a call in a later
29- argument spills the earlier ones, as any call spills the values under
30- it, so that it can't disturb them. A slice goes as its two words, as
31- System V passes a 16-byte struct of two integers; a record, array or
32- variant passed by value goes as the address of a copy the caller
33- makes. A slice, or two results that are single values, come back in
34- rax and rdx (InTwoRegs); any other record, or several results, comes
35- back in memory the caller provides, through a hidden pointer
36- (BehindPointer), where C would send a small struct back in registers.
37-
38- A procedure's frame holds its parameters, its variables, and the
39- temporaries of the statement running. The variables are zeroed on
40- entry.
41-
42- Depends on: scan and diag for errors, sym for types, chunk for code
43- and data, x64 for instructions.
44- Leaves out: what the program means, its types and their checks; that
45- is item.pas. }
46-
47-unit gen;
48-
49-{$mode objfpc}{$H-}
50-
51-interface
52-
53-uses scan, diag, sym, chunk, x64;
54-
55-const
56- NoLabel = -1;
57- WordSize = 8; { the size of an address, and of INT }
58- { What the machine catches by itself, which the code needn't test for
59- (report section 10): on x86-64 Linux, a division by zero, a stack
60- overflow (at the guard page under the stack), a call to nil, and
61- a load or store within NilPage bytes of address 0, which is never
62- mapped. }
63- NilPage = 4096;
64-
65-type
66- TKind = (kWord, kLong, kF32, kF64);
67-
68- { Where a variable is: its address is relative to the frame, to a
69- chunk, to an address on the stack, or to one held in a frame slot }
70- TBase = (bFrame, bGlobal, bStack, bSlot, bReg);
71- TAdr = record
72- base: TBase;
73- chunk: longint; { bGlobal: the chunk; bSlot: the frame slot; bReg: the register }
74- off: int64; { added to the address; for bReg, which word, 0 or 8 }
75- hi: longint; { bReg, a slice: the register of its length, the
76- second word; chunk is that of its pointer }
77- end;
78-
79- { The code made so far, to go back to for a second try at a body }
80- TCodeMark = record pc, fixups, lines, said, fails: longint; end;
81-
82- { For EntryPoint: the address of chunk, put in the variable whose
83- chunk is into before the program starts }
84- TLink = record chunk, into: longint; end;
85-
86- TCall = record
87- sig: PType;
88- param: PObj; { the parameter the next argument is for }
89- obj: PObj; { the procedure called, if it has a name }
90- n: longint; { the arguments }
91- isF: array[0..63] of boolean; { ... goes in an xmm register }
92- pair: array[0..63] of boolean; { ... is a slice's first word, the next its second }
93- target: int64; { the frame slot of a procedure value, if chunk < 0 }
94- chunk: longint; { else the procedure's chunk }
95- ext: boolean; { C's: called through the chunk holding its address }
96- ret: int64; { set by Call: the temporary a slice or a record result is in }
97- end;
98-
99-const
100- { the registers a procedure keeps its busiest variables in: System V's
101- callee-saved ones, so they live through calls (a register variable); a procedure saves
102- those it uses, and Rt finds them there for the trap report }
103- VarRegs: array[0..4] of longint = (RBX, R12, R13, R14, R15);
104- { the registers the trap report can show a variable in: VarRegs, then
105- rdi and rsi, where a procedure that calls nothing keeps the
106- parameters that arrive in them (KeptIn) }
107- ShownRegs: array[0..6] of longint = (RBX, R12, R13, R14, R15, RDI, RSI);
108- { the registers a procedure keeps its busiest reals in, xmm12 to
109- xmm15, numbered from XmmVar up so that they aren't taken for r12 to
110- r15 (RegAt). Each has a slot too, written as it is, where the trap
111- report finds it, and from which it is loaded again after a call, as
112- System V has no callee-saved xmm register (XHome). }
113- XmmVar = 16;
114- XVarRegs: array[0..3] of longint = (XmmVar + 12, XmmVar + 13, XmmVar + 14, XmmVar + 15);
115- { a procedure's registers of variables, as bits: bit i is VarRegs[i],
116- bit XBit + i XVarRegs[i] }
117- XBit = 5;
118-
119-var
120- rtFail, argcChunk, argvChunk: longint;
121- { the stubs that Check's code calls, one for each kind of failure,
122- made by EntryPoint for those used }
123- failStubs: array[0..5] of longint = (-1, -1, -1, -1, -1, -1);
124- lost: boolean; { a parameter kept where it arrived was wanted
125- for other work: the procedure is compiled again,
126- the parameter in memory }
127- inPlace: longint = -1; { the register of a variable that the statement
128- being compiled assigns, x := x + e, where the
129- value can be worked out in the variable's own
130- register, from its first push on (lInto) }
131- depth: longint; { the values on the stack }
132- pushed: longint; { quadwords pushed on the machine's stack }
133- codeChunk: longint = -1; { the procedure or body being compiled, or -1 }
134-
135-function KindOf(t: PType): TKind;
136-
137-procedure PushConst(k: TKind; v: int64);
138-procedure PushAdr(const a: TAdr);
139-procedure PushVar(const a: TAdr; size: longint; signed: boolean; k: TKind);
140-procedure PushProc(c: longint; ext: boolean);
141-procedure PopVar(const a: TAdr; size: longint);
142-procedure Drop;
143-procedure Swap;
144-procedure ResetStack(d, p: longint);
145-
146-procedure CopyBlock(size, off: int64);
147-procedure CopyTo(const a: TAdr; size: int64);
148-procedure ZeroVar(const a: TAdr; size: int64);
149-
150-procedure Op(op: TSym; k: TKind; size: longint; signed: boolean);
151-procedure Compare(op: TSym; k: TKind; signed: boolean);
152-procedure Neg(k: TKind; size: longint; signed: boolean);
153-procedure Complement(size: longint; signed: boolean);
154-procedure NotBool;
155-procedure Narrow(size: longint; signed: boolean);
156-procedure IntToReal(k: TKind; big: boolean);
157-procedure RealToInt(k: TKind);
158-procedure RealToReal(k: TKind);
159-procedure CompareSeq(a, b: int64; shift: longint; eq: boolean);
160-procedure ErrorText(tmp: int64);
161-procedure IncDec(size: longint; signed, dec: boolean);
162-procedure IncDecReg(r, size: longint; signed, dec: boolean);
163-procedure ZeroNew(size: int64);
164-procedure Atomic(which: longint);
165-procedure SysCall(n: longint);
166-procedure Fence;
167-
168-procedure Jump(var L: longint);
169-procedure JumpIf(var L: longint; when: boolean);
170-procedure JumpCmp(op: TSym; signed: boolean; var L: longint);
171-procedure JumpOut(op: TSym; signed: boolean; var L: longint);
172-procedure CondValue(notOp: TSym; signed: boolean; fj, tj: longint);
173-procedure JumpBack(top: longint);
174-function JumpTable(slot, lo: int64; n, elseAt: longint; var endL: longint): longint;
175-procedure TableEntry(table, target: longint);
176-procedure AlignLoop;
177-procedure Fix(L: longint);
178-procedure FixTo(L, top: longint);
179-function JoinJumps(L1, L2: longint): longint;
180-
181-procedure CheckIndex(n: int64; const p: TPos);
182-procedure CheckEnum(n: int64; name: longint; const p: TPos);
183-procedure CheckNil(reach: int64; const p: TPos);
184-procedure IndexArray(const a: TAdr; size: int64);
185-procedure IndexSlice(const a: TAdr; size: int64; checked: boolean; const p: TPos);
186-procedure Slice(const a: TAdr; isArray: boolean; n, size, tmp: int64; checked: boolean; const p: TPos);
187-procedure SlicePtr(size, tmp: int64; checked: boolean; const p: TPos);
188-procedure CopySlice(dOff, sOff, size: int64; checked: boolean; const p: TPos);
189-
190-procedure Call(var c: TCall);
191-
192-function AllocTemp(size, align: int64): int64;
193-function AllocPerm(size, align: int64): int64;
194-function TempMark: int64;
195-procedure ReleaseTemps(m: int64);
196-procedure KeepTemps;
197-
198-procedure BeginProc(sig: PType; params: PObj);
199-procedure ResetLocals;
200-procedure KeepArrived(o: PObj);
201-function KeptIn(o: PObj): boolean;
202-procedure UseRegs(mask: longint);
203-procedure XHome(r: longint; slot: int64);
204-procedure MarkCode(var m: TCodeMark);
205-procedure Redo(const m: TCodeMark);
206-procedure Rewind(const m: TCodeMark);
207-procedure EnterBody(c, line: longint);
208-procedure ResultTo(off: int64; size: longint);
209-procedure CopyResult(off, size: int64);
210-procedure ReturnJump;
211-procedure TryAlign;
212-procedure TryReturn(slot: int64);
213-procedure EndProc(c: longint; open: boolean);
214-function DeferBegin(var L, saved: longint): longint;
215-procedure DeferEnd(L, saved: longint);
216-procedure RunDefer(at: longint);
217-
218-function EntryPoint(dynamic: boolean; first: PModule; main: PObj; cExit, exitProc: longint; const links: array of TLink; numLinks: longint): longint;
219-procedure CodeProc(c: longint; constExpr: TConstFn);
220-
221-implementation
222-
223-type
224- { where a value on the stack is }
225- TLoc = (lConst, { not loaded: val is the value }
226- lHeld, { not loaded: in register val, a register
227- variable's own (see VarRegs), read in place, which
228- nothing in an expression can change }
229- lAdr, { not loaded: the address of chunk, or of the frame
230- if chunk is -1, plus val }
231- lIdx, { not loaded: the address m, an element of an array
232- or of a slice in registers: the array's or the
233- pointer's register, or rbp, as the base, and the
234- index in a register variable's or the value's
235- own register (IndexSlice, IndexArray) }
236- lMem, { not loaded: the value of size bytes at m, in the
237- frame, a chunk, or at an address lAdr or lIdx
238- noted, read where it is used (PushVar) }
239- lInto, { in register val, a register variable's own, which
240- is what the value goes to (inPlace): so it is
241- changed in place }
242- lReg, { in its register }
243- lFrame); { spilled: in the frame slot val }
244-
245- TEntry = record
246- loc: TLoc;
247- val: int64; { lConst: the value; lHeld: the register; lAdr: the
248- offset; lFrame: the frame slot }
249- chunk: longint; { lAdr: the chunk, or -1 for the frame }
250- m: TMem; { lIdx, lMem }
251- size: longint; { lMem }
252- signed: boolean; { lMem }
253- k: TKind;
254- off: int64; { lHeld, lReg: a word, its register plus off, the
255- constant of x + 1 not yet added (Op), so that an
256- operand that uses it can take it as its
257- displacement: [r13 + r9 * 8 - 8] }
258- end;
259-
260-const
261- StubNames: array[0..5] of string[6] = ('check0', 'check1', 'check2', 'check3', 'check4', 'check5');
262- { the registers of the stack: the value at depth d is in Regs[d mod
263- NumRegs]. rax, rdx and rcx, which division and shifts need, and rsi
264- and rdi, which copying needs, aren't among them. }
265- NumRegs = 4;
266- Regs: array[0..NumRegs - 1] of longint = (R8, R9, R10, R11);
267- XRegs: array[0..NumRegs - 1] of longint = (8, 9, 10, 11); { xmm8 to xmm11 }
268- IntRegs: array[0..5] of longint = (RDI, RSI, RDX, RCX, R8, R9);
269-
270-var
271- stack: array[0..255] of TEntry;
272- owner: array[0..NumRegs - 1] of longint; { the value in each register, or -1 }
273- frameTop, frameMax, permTop: int64;
274- frameFix: longint; { where the frame size is patched in }
275- paramTop: int64; { the parameters' slots end here }
276- zeroTop: int64; { the locals the prologue zeroes end here }
277- retSlot: int64; { holds the hidden result pointer }
278- resType: PType; { the procedure's result, or nil }
279- exitL: longint;
280- { parameters arriving in registers: where each is stored on entry }
281- inReg: array[0..13] of longint;
282- inSlot: array[0..13] of int64;
283- inSize: array[0..13] of longint;
284- inObj: array[0..13] of PObj;
285- numIn: longint;
286- procParams: PObj; { the parameters, for EnterBody }
287- regMask: longint; { the registers of variables, as bits (XBit) }
288- kept: longint; { bit r: register r holds a parameter, as it arrived }
289- saveAt: int64; { where they are saved, a quadword each }
290- homes: array[0..3] of int64; { the slots of the variables in XVarRegs }
291- frameAt: array[0..2] of int64; { frameTop, frameMax, permTop after the declarations }
292- { the checks of the procedure, whose failures EndFails makes }
293- fails: array[0..4095] of record
294- L, what, ra, name, at: longint;
295- m: TMem;
296- n: int64;
297- end;
298- numFails: longint;
299-
300-function KindOf(t: PType): TKind;
301-begin
302- if t^.form = fReal then begin
303- if t^.size = 4 then KindOf := kF32 else KindOf := kF64
304- end else if t^.size > WordSize then KindOf := kLong
305- else KindOf := kWord;
306-end;
307-
308-{ The stack, as in Wirth's compilers: the value at depth d is held in
309- register d mod NumRegs. A value, when a higher one wants its register,
310- and every value in a register when a call would clobber them, is
311- spilled to a frame slot, and loaded again where it is used. A constant
312- is only noted.
313-
314- Drop emits no code, and a dropped value's register still holds it
315- until the next push claims it: Place (for bStack), Operands,
316- IndexSlice and JumpCmp read a register after dropping its value.
317-
318- Registers outside the stack, free within one operation: rax, rcx and
319- rdx for arithmetic; rsi and rdi for copying; and, where the stack holds
320- nothing in them, r10 for the prologue's zeroing loop and r11 for a call
321- through a procedure value; xmm0 and xmm1 for reals.
322-
323- A real, an F32 or an F64, is held in xmm8 to xmm11 (XRegs), where the
324- machine computes with reals, the value at depth d in XRegs[d mod
325- NumRegs]: so each depth has two registers, and holds its value in the
326- one of its kind, which owner doesn't tell apart. The xmm registers
327- from xmm8 up carry no arguments, so that Call can move a real into
328- xmm0 to xmm7 without overwriting another still to go. }
329-
330-function Fits32(v: int64): boolean;
331-begin
332- Fits32 := (v >= low(longint)) and (v <= high(longint));
333-end;
334-
335-{ The register of kind k for the value at depth i }
336-function RegIn(k: TKind; i: longint): longint;
337-begin
338- if k in [kF32, kF64] then RegIn := XRegs[i mod NumRegs] else RegIn := Regs[i mod NumRegs];
339-end;
340-
341-function RegOf(i: longint): longint;
342-begin
343- RegOf := RegIn(stack[i].k, i);
344-end;
345-
346-function IsReal(i: longint): boolean;
347-begin
348- IsReal := stack[i].k in [kF32, kF64];
349-end;
350-
351-{ A real constant, its bits v, as an operand: 8 bytes in read-only
352- data, as the machine has no instruction that holds one }
353-function RealConst(v: int64): TMem;
354-var c: longint;
355-begin
356- c := NewChunk(secRodata, -1, -1);
357- SetData(c, @v, 8, 8);
358- RealConst := MemRip(c, 0);
359-end;
360-
361-{ The real i into xmm register x, from wherever it is, as ValueTo does
362- for an integer register }
363-procedure XValueTo(i, x: longint);
364-var single: boolean;
365-begin
366- single := stack[i].k = kF32;
367- case stack[i].loc of
368- lConst: MovsXM(x, RealConst(stack[i].val), single);
369- lMem: MovsXM(x, stack[i].m, stack[i].size = 4);
370- lHeld, lInto: if stack[i].val <> x then MovX(x, stack[i].val);
371- lReg: if RegOf(i) <> x then MovX(x, RegOf(i));
372- else MovsXM(x, Mem(RBP, stack[i].val), false); { spilled, as 8 bytes }
373- end;
374-end;
375-
376-function Loaded(i: longint): longint; forward;
377-
378-{ The value i, in a register, goes to a frame slot; one noted that
379- holds its register, as an index, is worked out in it first }
380-procedure Spill(i: longint);
381-var s: int64;
382-begin
383- if (stack[i].loc <> lReg) or (stack[i].off <> 0) then Loaded(i);
384- s := AllocTemp(8, 8);
385- if IsReal(i) then MovsMX(Mem(RBP, s), RegOf(i), false)
386- else Store(Mem(RBP, s), RegOf(i), 8);
387- stack[i].loc := lFrame;
388- stack[i].val := s;
389- owner[i mod NumRegs] := -1;
390-end;
391-
392-{ Each value below depth d read from memory now, as what comes next
393- may change it }
394-procedure ReadMems(d: longint);
395-var i: longint;
396-begin
397- for i := 0 to d - 1 do
398- if stack[i].loc = lMem then Loaded(i);
399-end;
400-
401-{ Every value below depth d in a register, spilled; one noted in memory
402- is read first, as a call may change it }
403-procedure SpillBelow(d: longint);
404-var r: longint;
405-begin
406- ReadMems(d);
407- for r := 0 to NumRegs - 1 do
408- if (owner[r] >= 0) and (owner[r] < d) then Spill(owner[r]);
409-end;
410-
411-{ The register of kind k of value i, for it to hold: a lower value at
412- its depth's registers is spilled. }
413-function Claim(i: longint; k: TKind): longint;
414-var r: longint;
415-begin
416- r := i mod NumRegs;
417- if (owner[r] >= 0) and (owner[r] <> i) then Spill(owner[r]);
418- owner[r] := i;
419- Claim := RegIn(k, i);
420-end;
421-
422-{ The memory at the noted address i, plus off }
423-function AdrMem(i: longint; off: int64): TMem;
424-begin
425- if stack[i].chunk < 0 then AdrMem := Mem(RBP, stack[i].val + off)
426- else AdrMem := MemRip(stack[i].chunk, stack[i].val + off);
427-end;
428-
429-{ The value i, in its register }
430-function Loaded(i: longint): longint;
431-var r: longint;
432-begin
433- if stack[i].loc = lInto then exit(stack[i].val);
434- if (stack[i].loc <> lReg) and IsReal(i) then begin
435- XValueTo(i, Claim(i, stack[i].k));
436- stack[i].loc := lReg;
437- end else if stack[i].loc <> lReg then begin
438- r := Claim(i, kWord);
439- case stack[i].loc of
440- lConst: MovRI(r, stack[i].val);
441- lHeld: MovRR(r, stack[i].val);
442- lAdr: Lea(r, AdrMem(i, 0));
443- lIdx: Lea(r, stack[i].m);
444- lMem: Load(r, stack[i].m, stack[i].size, stack[i].signed);
445- else Load(r, Mem(RBP, stack[i].val), 8, false);
446- end;
447- stack[i].loc := lReg;
448- end;
449- if stack[i].off <> 0 then begin
450- Lea(RegOf(i), Mem(RegOf(i), stack[i].off));
451- stack[i].off := 0;
452- end;
453- Loaded := RegOf(i);
454-end;
455-
456-{ The register value i is in, only to be read: a variable's own, or
457- its register }
458-function Peek(i: longint): longint;
459-begin
460- if (stack[i].loc = lHeld) and (stack[i].off = 0) then Peek := stack[i].val else Peek := Loaded(i);
461-end;
462-
463-{ The offset of value i, taken from it, for the caller to add or to
464- make a displacement of }
465-function TakeOff(i: longint): int64;
466-begin
467- TakeOff := stack[i].off;
468- stack[i].off := 0;
469-end;
470-
471-{ The word on top, in a register, has o added: noted, if o can be a
472- displacement, else added now }
473-procedure PutOff(o: int64);
474-begin
475- if Fits32(stack[depth - 1].off + o) then stack[depth - 1].off := stack[depth - 1].off + o
476- else begin
477- MovRI(RCX, o);
478- Alu(aluAdd, Loaded(depth - 1), RCX);
479- end;
480-end;
481-
482-function Top: longint;
483-begin
484- if depth = 0 then Fatal('internal error: the stack is empty');
485- Top := Loaded(depth - 1);
486-end;
487-
488-procedure NewEntry(k: TKind; loc: TLoc; v: int64);
489-begin
490- if depth > High(stack) then Mark('the expression is too deep');
491- stack[depth].k := k;
492- stack[depth].loc := loc;
493- stack[depth].val := v;
494- stack[depth].chunk := -1;
495- stack[depth].off := 0;
496- inc(depth);
497-end;
498-
499-{ An address, lIdx, or a value at it, lMem, noted as the operand m. Its
500- index may be in the register of the value just dropped, at this
501- depth: it is the new value's own, then. }
502-procedure NewMem(loc: TLoc; const m: TMem; k: TKind; size: longint; signed: boolean);
503-begin
504- NewEntry(k, loc, 0);
505- stack[depth - 1].m := m;
506- stack[depth - 1].size := size;
507- stack[depth - 1].signed := signed;
508- if m.index = Regs[(depth - 1) mod NumRegs] then owner[(depth - 1) mod NumRegs] := depth - 1;
509-end;
510-
511-{ The register a new value on top is to be computed in }
512-function Target: longint;
513-begin
514- Target := Claim(depth, kWord);
515-end;
516-
517-{ The xmm register a new real on top is to be computed in }
518-function XTarget: longint;
519-begin
520- XTarget := Claim(depth, kF64);
521-end;
522-
523-{ The value just computed in Target goes on top }
524-procedure Computed(k: TKind);
525-begin
526- NewEntry(k, lReg, 0);
527-end;
528-
529-procedure Drop;
530-begin
531- dec(depth);
532- if owner[depth mod NumRegs] = depth then owner[depth mod NumRegs] := -1;
533-end;
534-
535-{ rsi and rdi are about to be used for other work, as in copying: a
536- parameter kept in either must go to memory (lost). }
537-procedure ClobberArgs;
538-begin
539- if kept <> 0 then lost := true;
540-end;
541-
542-{ The value i into register r, from wherever it is: a constant or an
543- address is made there, a variable's register or the value's own
544- register copied, a spilled value loaded. Unlike Loaded, it leaves the
545- value where it was, so r is its only new copy. }
546-procedure ValueTo(i, r: longint);
547-begin
548- if IsReal(i) and (stack[i].loc in [lHeld, lInto]) then MovqRX(r, stack[i].val)
549- else case stack[i].loc of
550- lConst: MovRI(r, stack[i].val);
551- lHeld, lInto: MovRR(r, stack[i].val);
552- lAdr: Lea(r, AdrMem(i, 0));
553- lIdx: Lea(r, stack[i].m);
554- lMem: Load(r, stack[i].m, stack[i].size, stack[i].signed);
555- lReg:
556- if IsReal(i) then MovqRX(r, RegOf(i))
557- else if RegOf(i) <> r then MovRR(r, RegOf(i));
558- else Load(r, Mem(RBP, stack[i].val), 8, false);
559- end;
560- if stack[i].off <> 0 then Lea(r, Mem(r, stack[i].off));
561-end;
562-
563-{ The value on top, popped into register r }
564-procedure PopTo(r: longint);
565-begin
566- ValueTo(depth - 1, r);
567- Drop;
568-end;
569-
570-{ Whether the value on top is a constant, and if so, which }
571-function TopConst(var v: int64): boolean;
572-begin
573- TopConst := stack[depth - 1].loc = lConst;
574- v := stack[depth - 1].val;
575-end;
576-
577-procedure ResetStack(d, p: longint);
578-var r: longint;
579-begin
580- depth := d;
581- pushed := p;
582- for r := 0 to NumRegs - 1 do owner[r] := -1;
583-end;
584-
585-procedure PushConst(k: TKind; v: int64);
586-begin
587- NewEntry(k, lConst, v);
588-end;
589-
590-{ The register of the word at a, a variable in registers: the variable's
591- own, or for a slice its pointer's (off 0) or its length's (off 8) }
592-function RegAt(const a: TAdr): longint;
593-begin
594- if a.off = 0 then RegAt := a.chunk else RegAt := a.hi;
595- if RegAt >= XmmVar then RegAt := RegAt - XmmVar; { an xmm register, XVarRegs }
596-end;
597-
598-{ The memory a names. An address on the stack is popped, and is in its
599- register still; one in a slot is loaded into r. }
600-function Place(const a: TAdr; r: longint): TMem;
601-var ra: longint; o: int64;
602-begin
603- if a.base = bReg then Fatal('internal error: a register has no address');
604- case a.base of
605- bFrame: Place := Mem(RBP, a.off);
606- bGlobal: Place := MemRip(a.chunk, a.off);
607- bStack:
608- if stack[depth - 1].loc = lAdr then begin
609- Place := AdrMem(depth - 1, a.off);
610- Drop;
611- end else if stack[depth - 1].loc = lIdx then begin
612- Place := stack[depth - 1].m;
613- Place.disp := Place.disp + a.off;
614- Drop;
615- end else begin
616- { an offset noted on the address is the operand's, as
617- p^.f + 8: [r8 + 8] }
618- if Fits32(a.off + stack[depth - 1].off) then o := TakeOff(depth - 1) else o := 0;
619- ra := Peek(depth - 1);
620- Drop;
621- Place := Mem(ra, a.off + o)
622- end;
623- else { bSlot: the address is in the frame slot a.chunk }
624- Load(r, Mem(RBP, a.chunk), 8, false);
625- Place := Mem(r, a.off);
626- end;
627-end;
628-
629-{ The address a names, on top of the stack }
630-procedure PushAdr(const a: TAdr);
631-var m: TMem; r: longint;
632-begin
633- if (a.base = bStack) and (a.off = 0) then exit; { it is on top already }
634- if a.base in [bFrame, bGlobal] then begin
635- NewEntry(kWord, lAdr, a.off);
636- if a.base = bGlobal then stack[depth - 1].chunk := a.chunk;
637- exit;
638- end;
639- { The order matters. With the address on the stack, Place pops it and
640- must come first, so that Target may reuse its register; otherwise
641- Target comes first, since Place may need r to load a slot's pointer. }
642- if a.base = bStack then begin m := Place(a, -1); r := Target end
643- else begin r := Target; m := Place(a, r) end;
644- Lea(r, m);
645- Computed(kWord);
646-end;
647-
648-procedure PushVar(const a: TAdr; size: longint; signed: boolean; k: TKind);
649-var m: TMem; r: longint;
650-begin
651- r := inPlace;
652- inPlace := -1;
653- if r >= XmmVar then r := r - XmmVar;
654- if (a.base = bReg) and (RegAt(a) = r) then begin
655- NewEntry(k, lInto, r);
656- exit;
657- end;
658- if a.base = bReg then begin
659- NewEntry(k, lHeld, RegAt(a));
660- exit;
661- end;
662- { a variable in the frame or a chunk, or at an address only noted, is
663- only noted too: read where it is used, as an operand if it can be }
664- if (a.base in [bFrame, bGlobal]) or (a.base = bStack) and (stack[depth - 1].loc in [lAdr, lIdx]) then begin
665- m := Place(a, -1);
666- NewMem(lMem, m, k, size, signed);
667- exit;
668- end;
669- { in the order PushAdr explains }
670- if a.base = bStack then begin m := Place(a, -1); r := Target end
671- else begin r := Target; m := Place(a, r) end;
672- if k in [kF32, kF64] then MovsXM(XTarget, m, size = 4)
673- else Load(r, m, size, signed);
674- Computed(k);
675-end;
676-
677-procedure PushProc(c: longint; ext: boolean);
678-var r: longint;
679-begin
680- r := Target;
681- if ext then Load(r, MemRip(c, 0), 8, false)
682- else Lea(r, MemRip(c, 0));
683- Computed(kWord);
684-end;
685-
686-{ The slot of the variable in xmm register x }
687-function HomeOf(x: longint): TMem;
688-begin
689- HomeOf := Mem(RBP, homes[x + XmmVar - XVarRegs[0]]);
690-end;
691-
692-{ Pops a value into the variable at a; an address on the stack is under
693- the value. }
694-procedure PopVar(const a: TAdr; size: longint);
695-var r: longint; v: int64; real: boolean;
696-begin
697- if (a.base = bReg) and IsReal(depth - 1) then begin
698- XValueTo(depth - 1, RegAt(a));
699- Drop;
700- MovsMX(HomeOf(RegAt(a)), RegAt(a), false); { written through, as XHome says }
701- exit;
702- end;
703- if a.base = bReg then begin
704- if TopConst(v) then MovRI(RegAt(a), v)
705- else if Peek(depth - 1) <> RegAt(a) then MovRR(RegAt(a), Peek(depth - 1)); { else it is there, lInto }
706- Drop;
707- exit;
708- end;
709- if TopConst(v) and Fits32(v) then begin
710- Drop;
711- StoreI(Place(a, RCX), v, size);
712- exit;
713- end;
714- if TopConst(v) then begin r := RAX; MovRI(RAX, v) end
715- else r := Peek(depth - 1);
716- real := (stack[depth - 1].loc <> lConst) and IsReal(depth - 1);
717- Drop;
718- if real then MovsMX(Place(a, RCX), r, size = 4)
719- else Store(Place(a, RCX), r, size);
720-end;
721-
722-{ Register src to dst, an xmm register's if real }
723-procedure MovReg(real: boolean; dst, src: longint);
724-begin
725- if real then MovX(dst, src) else MovRR(dst, src);
726-end;
727-
728-{ The two values on top, of one kind, change places. }
729-procedure Swap;
730-var e: TEntry; x, y, t: longint; rx, ry, real: boolean;
731-begin
732- x := depth - 2; y := depth - 1;
733- { a value noted at an address that uses its register is worked out,
734- so that its register moves with it }
735- if stack[x].loc in [lIdx, lMem] then Loaded(x);
736- if stack[y].loc in [lIdx, lMem] then Loaded(y);
737- rx := stack[x].loc = lReg;
738- ry := stack[y].loc = lReg;
739- real := IsReal(y);
740- if real then t := 0 else t := RAX; { xmm0, or rax }
741- if rx and ry then begin
742- MovReg(real, t, RegOf(x));
743- MovReg(real, RegOf(x), RegOf(y));
744- MovReg(real, RegOf(y), t);
745- end else if rx then begin
746- owner[x mod NumRegs] := -1;
747- MovReg(real, Claim(y, stack[y].k), RegOf(x));
748- end else if ry then begin
749- owner[y mod NumRegs] := -1;
750- MovReg(real, Claim(x, stack[x].k), RegOf(y));
751- end;
752- e := stack[x]; stack[x] := stack[y]; stack[y] := e;
753-end;
754-
755-{ Copying }
756-
757-{ size bytes from [rsi] to [rdi], through rcx; rsi and rdi are left
758- as they fall. Up to 64 bytes, as a record or a small array mostly
759- is, they go as moves of 8, 4, 2 and 1 bytes: rep movsb takes some
760- twenty cycles to start, longer than the few moves take. }
761-procedure CopyBytes(size: int64);
762-var o, n: int64;
763-begin
764- if size > 64 then begin
765- MovRI(RCX, size);
766- RepMovsb;
767- exit;
768- end;
769- o := 0;
770- while o < size do begin
771- n := 8;
772- while n > size - o do n := n div 2;
773- Load(RCX, Mem(RSI, o), n, false);
774- Store(Mem(RDI, o), RCX, n);
775- Inc(o, n);
776- end;
777-end;
778-
779-{ Pops a source's address, and a destination's under it, and copies
780- size bytes to off bytes past the destination. }
781-procedure CopyBlock(size, off: int64);
782-begin
783- ClobberArgs;
784- PopTo(RSI);
785- PopTo(RDI);
786- if off <> 0 then Lea(RDI, Mem(RDI, off));
787- CopyBytes(size);
788-end;
789-
790-{ Pops a source's address, and copies size bytes to a: for a slice in
791- registers, its two words into them. }
792-procedure CopyTo(const a: TAdr; size: int64);
793-begin
794- ClobberArgs;
795- PopTo(RSI);
796- if a.base = bReg then begin
797- Load(a.chunk, Mem(RSI, 0), 8, false);
798- Load(a.hi, Mem(RSI, 8), 8, false);
799- exit;
800- end;
801- Lea(RDI, Place(a, RDI));
802- CopyBytes(size);
803-end;
804-
805-procedure ZeroVar(const a: TAdr; size: int64);
806-begin
807- ClobberArgs;
808- Lea(RDI, Place(a, RDI));
809- MovRI(RCX, size);
810- MovRI(RAX, 0);
811- RepStosb;
812-end;
813-
814-{ Operations }
815-
816-{ n if v is 2^n, which is 0 for 1; -1 if v isn't a power of two }
817-function ExactLog2(v: int64): longint;
818-var n: longint;
819-begin
820- n := 0;
821- while (v > 1) and (v and 1 = 0) do begin v := v shr 1; inc(n) end;
822- if v <> 1 then n := -1;
823- ExactLog2 := n;
824-end;
825-
826-{ r times v, a size: by a shift where v is a power of two, as it
827- mostly is, since a shift takes one cycle and imul three }
828-procedure MulI(r: longint; v: int64);
829-begin
830- if ExactLog2(v) > 0 then ShiftI(shShl, r, ExactLog2(v))
831- else if v <> 1 then ImulI(r, v);
832-end;
833-
834-{ r compared with v, through rdx if v needs more than 32 bits; with
835- zero by test, which sets the flags as cmp would and is shorter }
836-procedure CmpI(r: longint; v: int64);
837-begin
838- if v = 0 then TestRR(r, r)
839- else if Fits32(v) then AluI(aluCmp, r, v)
840- else begin MovRI(RDX, v); Alu(aluCmp, r, RDX) end;
841-end;
842-
843-{ r div or mod 2^k, 1 <= k <= 62, with shifts: div truncates towards
844- zero, so a negative dividend first gets 2^k - 1 added (the bias). }
845-procedure DivPow2(op: TSym; r, k: longint; unsign: boolean);
846-begin
847- { unsigned: div shifts right; mod keeps the low k bits, by shifting
848- them up to the top and back down }
849- if unsign then begin
850- if op = sDiv then ShiftI(shShr, r, k)
851- else begin ShiftI(shShl, r, 64 - k); ShiftI(shShr, r, 64 - k) end;
852- exit;
853- end;
854- { signed: sar 63 makes the sign into all ones or all zeros, and shr
855- 64 - k keeps k of them, the bias 2^k - 1 or 0; with it added, sar k
856- rounds towards zero. The remainder is r less the quotient times 2^k. }
857- MovRR(RCX, r);
858- ShiftI(shSar, RCX, 63);
859- ShiftI(shShr, RCX, 64 - k);
860- Alu(aluAdd, RCX, r);
861- ShiftI(shSar, RCX, k);
862- if op = sDiv then MovRR(r, RCX)
863- else begin ShiftI(shShl, RCX, k); Alu(aluSub, r, RCX) end;
864-end;
865-
866-{ Before rax div y, of a signed type of bits < 64: its smallest value
867- divided by -1 overflows it, which must stop the program as it does for
868- an I64 (report section 6.1). idiv on the 64-bit values wouldn't fault,
869- so then rax is made the smallest I64, and it does. }
870-procedure DivTrap(bits, y: longint);
871-var L: longint;
872-begin
873- L := NoLabel;
874- CmpI(y, -1);
875- Jcc(ccNE, L);
876- CmpI(RAX, int64(-1) shl (bits - 1));
877- Jcc(ccNE, L);
878- ShiftI(shShl, RAX, 64 - bits);
879- FixLink(L);
880-end;
881-
882-{ Whether the value on top is a word in memory that can be the right
883- operand of an instruction as it is: add r, [m] }
884-function TopInMem: boolean;
885-begin
886- TopInMem := (stack[depth - 1].loc = lMem) and (stack[depth - 1].size = 8);
887-end;
888-
889-{ The right operand of the two values on top, popped, in register y:
890- its own, or rcx for a constant; the left one stays, in its register,
891- which is returned. }
892-function Operands(var y: longint): longint;
893-var v: int64;
894-begin
895- if TopConst(v) then begin MovRI(RCX, v); y := RCX end else y := Peek(depth - 1);
896- Drop;
897- Operands := Top;
898-end;
899-
900-{ The two reals on top, the left op the right, worked out in the left's
901- xmm register. The right is taken from memory where it is, as a
902- constant, a variable or a spilled value is: mulsd xmm8, [rbp - 16]. }
903-procedure RealOp(op: TSym; k: TKind);
904-var f: boolean; c, x, y: longint; m: TMem;
905-begin
906- f := k = kF32;
907- case op of
908- sPlus: c := $58; { addsd, or addss for an F32 }
909- sMinus: c := $5C; { subsd, subss }
910- sTimes: c := $59; { mulsd, mulss }
911- else c := $5E; { divsd, divss }
912- end;
913- if stack[depth - 1].loc in [lConst, lMem, lFrame] then begin
914- case stack[depth - 1].loc of
915- lConst: m := RealConst(stack[depth - 1].val);
916- lMem: m := stack[depth - 1].m;
917- else m := Mem(RBP, stack[depth - 1].val);
918- end;
919- Drop;
920- SseM(c, Top, m, f);
921- end else begin
922- y := Peek(depth - 1);
923- Drop;
924- x := Top;
925- Sse(c, x, y, f);
926- end;
927-end;
928-
929-{ The group 1 operation of +, -, &, | and xor }
930-function AluOf(op: TSym): longint;
931-begin
932- case op of
933- sPlus: AluOf := aluAdd;
934- sMinus: AluOf := aluSub;
935- sAmp: AluOf := aluAnd;
936- sBar: AluOf := aluOr;
937- else AluOf := aluXor;
938- end;
939-end;
940-
941-{ The two values on top, the left op the right, an integer of size
942- bytes, signed or not, brought back to its width. }
943-procedure Op(op: TSym; k: TKind; size: longint; signed: boolean);
944-var v, o: int64; r, y, sh, bits: longint; c: boolean; m: TMem;
945-begin
946- if k in [kF32, kF64] then begin RealOp(op, k); exit end;
947- bits := size * 8;
948- { a constant on the left of an operation whose order doesn't matter
949- goes right, where it can be an immediate or a shift }
950- if (op in [sPlus, sTimes, sAmp, sBar, sXor]) and (stack[depth - 2].loc = lConst)
951- and (stack[depth - 1].loc <> lConst) then Swap;
952- c := TopConst(v);
953- { A word's offset (see TEntry) is carried through + and -, and
954- through * by a constant, as (x + a) * k is x * k + a * k: the
955- operation is done on the registers, the offsets worked out here,
956- and put on the result. x + 1 is only noted. A value changed in
957- place, lInto, has no offset. }
958- o := 0;
959- if (bits = 64) and (stack[depth - 2].loc <> lInto)
960- and ((op in [sPlus, sMinus]) or (op = sTimes) and c and Fits32(v)) then begin
961- o := TakeOff(depth - 2);
962- if op = sTimes then o := o * v
963- else if c and Fits32(v) then begin
964- if op = sPlus then o := o + v else o := o - v;
965- Drop;
966- if not (stack[depth - 1].loc in [lReg, lHeld]) then Top;
967- PutOff(o);
968- exit;
969- end
970- else if op = sPlus then o := o + TakeOff(depth - 1)
971- else o := o - TakeOff(depth - 1);
972- end;
973- sh := -1;
974- if c and (op in [sTimes, sDiv, sMod]) then sh := ExactLog2(v);
975- if c and (sh >= 1) then begin
976- Drop;
977- r := Top;
978- if op = sTimes then ShiftI(shShl, r, sh) else DivPow2(op, r, sh, not signed);
979- end else if c and Fits32(v) and (op in [sPlus, sMinus, sBar, sXor, sAmp, sTimes, sShl, sShr]) then begin
980- Drop;
981- r := Top;
982- case op of
983- sTimes: ImulI(r, v);
984- sShl: ShiftI(shShl, r, v and (bits - 1));
985- sShr: if signed then ShiftI(shSar, r, v and (bits - 1)) else ShiftI(shShr, r, v and (bits - 1));
986- else AluI(AluOf(op), r, v);
987- end;
988- end else if TopInMem and (op in [sPlus, sMinus, sAmp, sBar, sXor]) then begin
989- m := stack[depth - 1].m;
990- Drop;
991- r := Top;
992- AluM(AluOf(op), r, m);
993- end else begin
994- r := Operands(y);
995- case op of
996- sPlus, sMinus, sAmp, sBar, sXor: Alu(AluOf(op), r, y);
997- sTimes: Imul(r, y);
998- sDiv, sMod: begin
999- MovRR(RAX, r);
1000- if not signed then begin MovRI(RDX, 0); Unary(6, y) end { div }
1001- else begin
1002- { only -1 can make the division overflow, so a constant
1003- divisor other than -1 needs no check }
1004- if (bits < 64) and (not c or (v = -1)) then DivTrap(bits, y);
1005- Cqo; Unary(7, y) { idiv, of rdx:rax, which cqo made from rax }
1006- end;
1007- if op = sDiv then MovRR(r, RAX) else MovRR(r, RDX);
1008- end;
1009- sShl, sShr: begin
1010- { the count modulo the width: the machine takes it modulo 64 }
1011- if y <> RCX then MovRR(RCX, y);
1012- if bits < 64 then AluI(aluAnd, RCX, bits - 1);
1013- if op = sShl then Shift(shShl, r)
1014- else if signed then Shift(shSar, r) else Shift(shShr, r);
1015- end;
1016- end;
1017- end;
1018- if bits < 64 then Extend(r, size, signed);
1019- stack[depth - 1].k := k;
1020- if o <> 0 then PutOff(o);
1021-end;
1022-
1023-{ The left op the right of the two values on top, as a BOOL }
1024-procedure Compare(op: TSym; k: TKind; signed: boolean);
1025-const
1026- CcSigned: array[sEql..sGeq] of longint = (ccE, ccNE, ccL, ccLE, ccG, ccGE);
1027- CcUnsigned: array[sEql..sGeq] of longint = (ccE, ccNE, ccB, ccBE, ccA, ccAE);
1028-var f: boolean; r, x, y: longint; v: int64; m: TMem;
1029-begin
1030- if k in [kF32, kF64] then begin
1031- f := k = kF32;
1032- y := Peek(depth - 1);
1033- Drop;
1034- x := Peek(depth - 1);
1035- Drop;
1036- r := Target; { the BOOL, in the left's integer register }
1037- { ucomis sets the flags as an unsigned comparison would, but for an
1038- unordered pair (a NaN) it sets zero, parity and carry all. So only
1039- "above" can be tested straight: it is false for NaN, as every
1040- comparison but <> must be. a < b is made b > a. = also asks for
1041- no parity, as NaN = NaN sets the zero flag, and <> asks for
1042- parity as well. }
1043- case op of
1044- sEql: begin Ucomis(x, y, f); SetCC(ccE, r); SetCC(ccNP, RCX); Alu(aluAnd, r, RCX) end;
1045- sNeq: begin Ucomis(x, y, f); SetCC(ccNE, r); SetCC(ccP, RCX); Alu(aluOr, r, RCX) end;
1046- sLss: begin Ucomis(y, x, f); SetCC(ccA, r) end;
1047- sLeq: begin Ucomis(y, x, f); SetCC(ccAE, r) end;
1048- sGtr: begin Ucomis(x, y, f); SetCC(ccA, r) end;
1049- sGeq: begin Ucomis(x, y, f); SetCC(ccAE, r) end;
1050- end;
1051- Computed(kWord);
1052- end else begin
1053- if TopConst(v) then begin Drop; r := Top; CmpI(r, v) end
1054- else if TopInMem then begin m := stack[depth - 1].m; Drop; r := Top; AluM(aluCmp, r, m) end
1055- else begin r := Operands(y); Alu(aluCmp, r, y) end;
1056- if signed then SetCC(CcSigned[op], r) else SetCC(CcUnsigned[op], r);
1057- end;
1058- stack[depth - 1].k := kWord;
1059-end;
1060-
1061-{ A real is negated by flipping its sign bit, in rax }
1062-procedure Neg(k: TKind; size: longint; signed: boolean);
1063-var r: longint;
1064-begin
1065- r := Top;
1066- case k of
1067- kF32, kF64: begin
1068- MovqRX(RAX, r);
1069- if k = kF32 then Btc(RAX, 31) else Btc(RAX, 63);
1070- MovqXR(r, RAX);
1071- end;
1072- else
1073- Unary(3, r); { neg }
1074- if size < 8 then Extend(r, size, signed);
1075- end;
1076-end;
1077-
1078-procedure Complement(size: longint; signed: boolean);
1079-var r: longint;
1080-begin
1081- r := Top;
1082- Unary(2, r); { not }
1083- if size < 8 then Extend(r, size, signed);
1084-end;
1085-
1086-procedure NotBool;
1087-begin
1088- AluI(aluXor, Top, 1);
1089-end;
1090-
1091-{ The integer on top, brought to size bytes }
1092-procedure Narrow(size: longint; signed: boolean);
1093-var r: longint;
1094-begin
1095- r := Top;
1096- if size < 8 then Extend(r, size, signed);
1097- stack[depth - 1].k := kWord;
1098-end;
1099-
1100-{ The integer on top, as a real of kind k; big if it may be a U64 above
1101- high(I64), which the machine would take as negative }
1102-procedure IntToReal(k: TKind; big: boolean);
1103-var L1, L2, r, x: longint; f: boolean;
1104-begin
1105- f := k = kF32;
1106- r := Top;
1107- x := RegIn(k, depth - 1); { its xmm register }
1108- if big then begin
1109- { above high(I64): halve, keeping the low bit, and double }
1110- L1 := NoLabel; L2 := NoLabel;
1111- TestRR(r, r);
1112- Jcc(ccS, L1);
1113- Cvtsi2s(x, r, f);
1114- Jmp(L2);
1115- FixLink(L1);
1116- MovRR(RCX, r);
1117- ShiftI(shShr, RCX, 1);
1118- AluI(aluAnd, r, 1);
1119- Alu(aluOr, RCX, r);
1120- Cvtsi2s(x, RCX, f);
1121- Sse($58, x, x, f); { adds it to itself: doubles }
1122- FixLink(L2);
1123- end else Cvtsi2s(x, r, f);
1124- stack[depth - 1].k := k;
1125-end;
1126-
1127-{ The real of kind k on top, truncated to an integer }
1128-procedure RealToInt(k: TKind);
1129-var x: longint;
1130-begin
1131- x := Top;
1132- Cvtts2si(RegIn(kWord, depth - 1), x, k = kF32);
1133- stack[depth - 1].k := kWord;
1134-end;
1135-
1136-{ The real of kind k on top, as the other kind }
1137-procedure RealToReal(k: TKind);
1138-var x: longint;
1139-begin
1140- x := Top;
1141- Sse($5A, x, x, k = kF32); { cvtss2sd, or cvtsd2ss }
1142- if k = kF32 then stack[depth - 1].k := kF64 else stack[depth - 1].k := kF32;
1143-end;
1144-
1145-{ Whether the slices in the frame at a and b (the offsets of their
1146- pointers, the lengths 8 bytes on) are equal (or not, if not eq): the
1147- lengths, then the bytes, len shl shift of them, compared where the
1148- comparison stands. }
1149-procedure CompareSeq(a, b: int64; shift: longint; eq: boolean);
1150-var differ, r: longint;
1151-begin
1152- ClobberArgs;
1153- r := Target;
1154- Load(RCX, Mem(RBP, b + 8), 8, false);
1155- AluM(aluCmp, RCX, Mem(RBP, a + 8));
1156- differ := NoLabel;
1157- Jcc(ccNE, differ);
1158- Load(RSI, Mem(RBP, b), 8, false);
1159- Load(RDI, Mem(RBP, a), 8, false);
1160- if shift > 0 then ShiftI(shShl, RCX, shift);
1161- { repe cmpsb with rcx = 0 leaves the flags alone, so make them say
1162- equal first, which is right if there are no bytes }
1163- Alu(aluCmp, RCX, RCX);
1164- RepeCmpsb;
1165- FixLink(differ);
1166- if eq then SetCC(ccE, r) else SetCC(ccNE, r);
1167- Computed(kWord);
1168-end;
1169-
1170-{ An error points at its message's length, an 8-byte word, with the
1171- text after it; nil is no error. Pops one, and makes the slice of its
1172- message at tmp, empty for nil. }
1173-procedure ErrorText(tmp: int64);
1174-var L: longint;
1175-begin
1176- PopTo(RAX);
1177- MovRI(RCX, 0);
1178- L := NoLabel;
1179- TestRR(RAX, RAX);
1180- Jcc(ccE, L);
1181- Load(RCX, Mem(RAX, 0), 8, false);
1182- Lea(RAX, Mem(RAX, 8));
1183- FixLink(L);
1184- Store(Mem(RBP, tmp), RAX, 8);
1185- Store(Mem(RBP, tmp + 8), RCX, 8);
1186-end;
1187-
1188-{ Pops a step and an integer variable's address, and adds the step to
1189- it, or takes it away. }
1190-procedure IncDec(size: longint; signed, dec: boolean);
1191-var r, y, op: longint; v: int64; a: TAdr;
1192-begin
1193- if TopConst(v) and Fits32(v) then begin
1194- Drop;
1195- a.base := bStack; a.off := 0;
1196- if dec then op := aluSub else op := aluAdd;
1197- AluMI(op, Place(a, RCX), v, size);
1198- exit;
1199- end;
1200- r := Operands(y);
1201- Drop;
1202- Load(RAX, Mem(r, 0), size, signed);
1203- if dec then Alu(aluSub, RAX, y) else Alu(aluAdd, RAX, y);
1204- Store(Mem(r, 0), RAX, size);
1205-end;
1206-
1207-{ INC or DEC of the variable in register r, by the value on top; a
1208- narrow one wraps at its width }
1209-procedure IncDecReg(r, size: longint; signed, dec: boolean);
1210-var y, op: longint; v: int64;
1211-begin
1212- if dec then op := aluSub else op := aluAdd;
1213- if TopConst(v) and Fits32(v) then AluI(op, r, v)
1214- else begin y := Top; Alu(op, r, y) end;
1215- Drop;
1216- if size < 8 then Extend(r, size, signed);
1217-end;
1218-
1219-{ The pointer on top, which NEW got, to size zero bytes unless nil }
1220-procedure ZeroNew(size: int64);
1221-var L, r: longint;
1222-begin
1223- ClobberArgs;
1224- r := Top;
1225- L := NoLabel;
1226- TestRR(r, r);
1227- Jcc(ccE, L);
1228- MovRR(RDI, r);
1229- MovRI(RCX, size);
1230- MovRI(RAX, 0);
1231- RepStosb;
1232- FixLink(L);
1233-end;
1234-
1235-{ CAS(p, old, new), XCHG(p, v) or XADD(p, v), from the stack: the
1236- result where p was }
1237-procedure Atomic(which: longint);
1238-var r, n: longint;
1239-begin
1240- ReadMems(depth - 2 - ord(which = bCas)); { what it writes may be one }
1241- if which = bCas then begin n := Top; Drop end;
1242- PopTo(RAX); { cmpxchg compares with rax, so CAS's old value goes there }
1243- r := Top;
1244- case which of
1245- bCas: begin LockCmpxchg(Mem(r, 0), n); SetCC(ccE, r) end;
1246- bXchg: begin Xchg(Mem(r, 0), RAX); MovRR(r, RAX) end;
1247- bXadd: begin LockXadd(Mem(r, 0), RAX); MovRR(r, RAX) end;
1248- end;
1249- stack[depth - 1].k := kWord;
1250-end;
1251-
1252-{ The system call and its arguments, n values on the stack. Linux takes
1253- the number in rax and the arguments in rdi, rsi, rdx, r10, r8 and r9,
1254- and the syscall instruction clobbers rcx and r11. Every value in a
1255- register is spilled first, as r8 to r11 are the stack's registers,
1256- and the arguments are loaded from their slots. }
1257-procedure SysCall(n: longint);
1258-const SysRegs: array[0..6] of longint = (RAX, RDI, RSI, RDX, R10, R8, R9);
1259-var i: longint;
1260-begin
1261- ClobberArgs;
1262- SpillBelow(depth);
1263- for i := 0 to n - 1 do ValueTo(depth - n + i, SysRegs[i]);
1264- for i := 1 to n do Drop;
1265- x64.Syscall;
1266- MovRR(Target, RAX);
1267- Computed(kWord);
1268-end;
1269-
1270-procedure Fence;
1271-begin
1272- Mfence;
1273-end;
1274-
1275-{ Jumps. A label is the chain of the jumps to it, until it is placed. }
1276-
1277-procedure Jump(var L: longint);
1278-begin
1279- Jmp(L);
1280-end;
1281-
1282-{ Pops a BOOL, and jumps if it is when }
1283-procedure JumpIf(var L: longint; when: boolean);
1284-var r: longint;
1285-begin
1286- r := Peek(depth - 1);
1287- Drop;
1288- TestRR(r, r);
1289- if when then Jcc(ccNE, L) else Jcc(ccE, L);
1290-end;
1291-
1292-{ Pops two integers, and jumps if the left op the right }
1293-procedure JumpCmp(op: TSym; signed: boolean; var L: longint);
1294-const
1295- CcSigned: array[sEql..sGeq] of longint = (ccE, ccNE, ccL, ccLE, ccG, ccGE);
1296- CcUnsigned: array[sEql..sGeq] of longint = (ccE, ccNE, ccB, ccBE, ccA, ccAE);
1297-var r, y: longint; v: int64; m: TMem;
1298-begin
1299- { a comparison changes neither: a variable's register will do }
1300- if TopConst(v) then begin Drop; r := Peek(depth - 1); CmpI(r, v) end
1301- else if TopInMem then begin m := stack[depth - 1].m; Drop; r := Peek(depth - 1); AluM(aluCmp, r, m) end
1302- else begin y := Peek(depth - 1); Drop; r := Peek(depth - 1); Alu(aluCmp, r, y) end;
1303- Drop;
1304- if signed then Jcc(CcSigned[op], L) else Jcc(CcUnsigned[op], L);
1305-end;
1306-
1307-{ JumpCmp out of an expression, past code that may spill: the values
1308- under the two compared are spilled first, so that they are where the
1309- code after the landing place expects them, whichever way it came. In
1310- v + (a < b and f(x) = 0), a call to f spills v on the way through, so
1311- v must be in its slot too where a < b jumps past the call. }
1312-procedure JumpOut(op: TSym; signed: boolean; var L: longint);
1313-begin
1314- SpillBelow(depth - 2);
1315- JumpCmp(op, signed, L);
1316-end;
1317-
1318-{ The two values on top, compared, as a BOOL: true unless notOp, the
1319- opposite comparison, holds. fj and tj are the chains of jumps, made
1320- earlier by and, or and not, that are taken when the whole condition is
1321- false and when it is true; they land here, on the 0 and the 1. }
1322-procedure CondValue(notOp: TSym; signed: boolean; fj, tj: longint);
1323-var r, e: longint;
1324-begin
1325- JumpOut(notOp, signed, fj);
1326- FixLink(tj);
1327- r := Target;
1328- MovRI(r, 1);
1329- e := NoLabel;
1330- Jmp(e);
1331- FixLink(fj);
1332- MovRI(r, 0);
1333- FixLink(e);
1334- Computed(kWord);
1335-end;
1336-
1337-{ JumpBack, Fix, FixTo and JoinJumps are gen's names for the encoder's,
1338- so that a port can place jumps its own way. Fix(L) places label L here;
1339- FixTo(L, top) makes every jump on chain L go to the earlier place top;
1340- JoinJumps makes one chain of two. }
1341-procedure JumpBack(top: longint);
1342-begin
1343- JmpBack(top);
1344-end;
1345-
1346-procedure Fix(L: longint);
1347-begin
1348- FixLink(L);
1349-end;
1350-
1351-{ A jump table, for a match on the integer in frame slot slot, whose
1352- labels run from lo up for n values. The selector less lo, compared
1353- unsigned (so below lo is above n too), is out of the table if it
1354- isn't below n, and goes to the else arm at elseAt, or, if there is
1355- none, to endL, the end of the match. Else it indexes a table of
1356- 4-byte offsets, each from the start of the lea, that follows the
1357- jump, and the code jumps to its start plus the entry:
1358-
1359- mov rax, [slot]
1360- sub rax, lo
1361- cmp rax, n - 1
1362- ja else
1363- lea rcx, [rip + start] start: this very lea
1364- movsxd rax, [rcx + rax*4 + 17]
1365- add rax, rcx
1366- jmp rax
1367- table: .long arm0 - start, arm1 - start, ...
1368-
1369- The four instructions after the compare are 7, 5, 3 and 2 bytes, so
1370- the table is 17 bytes on, which JumpTable checks. It returns start;
1371- the caller then makes the n entries with TableEntry. }
1372-function JumpTable(slot, lo: int64; n, elseAt: longint; var endL: longint): longint;
1373-const TableAt = 17;
1374-var start: longint;
1375-begin
1376- Load(RAX, Mem(RBP, slot), 8, false);
1377- if lo <> 0 then AluI(aluSub, RAX, lo);
1378- AluI(aluCmp, RAX, n - 1);
1379- if elseAt <> NoLabel then JccBack(ccA, elseAt) else Jcc(ccA, endL);
1380- start := pc;
1381- Lea(RCX, Here);
1382- Load(RAX, MemIdx(RCX, RAX, 4, TableAt), 4, true);
1383- Alu(aluAdd, RAX, RCX);
1384- JmpR(RAX);
1385- if pc <> start + TableAt then Fatal('internal error: the jump table is not where it was said');
1386- JumpTable := start;
1387-end;
1388-
1389-{ The next entry of the table that JumpTable started at table: the
1390- code at target }
1391-procedure TableEntry(table, target: longint);
1392-begin
1393- Put4(target - table);
1394-end;
1395-
1396-procedure AlignLoop;
1397-begin
1398- Align(32);
1399-end;
1400-
1401-function JoinJumps(L1, L2: longint): longint;
1402-begin
1403- JoinJumps := JoinLinks(L1, L2);
1404-end;
1405-
1406-procedure FixTo(L, top: longint);
1407-begin
1408- FixLinkTo(L, top);
1409-end;
1410-
1411-{ Checks }
1412-
1413-const
1414- NoBase = -2; { a TMem that is no memory }
1415- ARegister = -3; { a TMem that is no memory but a register, its index }
1416-
1417-{ The program goes on if the condition cc holds, and otherwise stops
1418- in Rt.fail(what, a, b, len, at, name), which says what failed at p,
1419- found by at, which a stub works out from where it was called; what is
1420- an index a (0), a slice a..b (1), each for a length len, a position a
1421- of the enumeration called name (2), a slice of a pointer a..b that
1422- runs backwards (3), or a nil pointer (4). Rt.fail knows 5 and 6, a
1423- division fault and a stack overflow, which this machine catches
1424- itself, so no check here has them. The arguments go in rdi, rsi, rdx,
1425- rcx, r8 and r9: a is in register ra, b in RDX; len is in memory at m,
1426- or n if m.base is NoBase, or in register m.index if it is ARegister.
1427- rdi and rsi are passed on as they were, since a parameter may be kept
1428- in them, for the trap report to show: so a goes to the stub in rax.
1429- The failing code is out of the way, at the
1430- procedure's end (EndFails), so that a check that holds costs a jump
1431- not taken; it has p for its place (at is p's offset in the source),
1432- never returns, and may use any register once it has read what it
1433- needs. }
1434-procedure Check(cc, what: longint; const p: TPos; ra: longint; const m: TMem; n: int64; name: longint);
1435-begin
1436- if numFails > High(fails) then Mark('more than ' + IntStr(High(fails) + 1) + ' checks in one procedure');
1437- fails[numFails].L := NoLabel;
1438- Jcc(cc xor 1, fails[numFails].L); { x86's conditions come in pairs, the other one its last bit flipped }
1439- fails[numFails].what := what;
1440- fails[numFails].ra := ra;
1441- fails[numFails].m := m;
1442- fails[numFails].n := n;
1443- fails[numFails].name := name;
1444- fails[numFails].at := p.a;
1445- inc(numFails);
1446-end;
1447-
1448-{ The failures of the procedure's checks: each gives Rt.fail its values
1449- and the place of the offending expression, through a stub for its
1450- kind, which takes the place from where it was called }
1451-procedure EndFails;
1452-var i, line, col: longint;
1453-begin
1454- for i := 0 to numFails - 1 do
1455- with fails[i] do begin
1456- FixLink(L);
1457- LineCol(at, line, col);
1458- NoteLine(line, col);
1459- if ra <> RAX then MovRR(RAX, ra);
1460- if m.base = NoBase then MovRI(RCX, n)
1461- else if m.base = ARegister then MovRR(RCX, m.index)
1462- else Load(RCX, m, 8, false);
1463- if name >= 0 then Lea(R9, MemRip(name, 0));
1464- if failStubs[what] < 0 then failStubs[what] := NewChunk(secText, Intern('Rt', 2), Intern(@StubNames[what][1], 6));
1465- CallChunk(failStubs[what]);
1466- end;
1467- numFails := 0;
1468-end;
1469-
1470-{ For Check: a length known here, not in memory }
1471-function NoMem: TMem;
1472-begin
1473- NoMem := Mem(NoBase, 0);
1474-end;
1475-
1476-{ For Check: a length in register r, a slice's in registers }
1477-function InRegister(r: longint): TMem;
1478-begin
1479- InRegister := Mem(ARegister, 0);
1480- InRegister.index := r;
1481-end;
1482-
1483-{ The index on top is below n, unsigned }
1484-procedure CheckIndex(n: int64; const p: TPos);
1485-var r: longint;
1486-begin
1487- r := Peek(depth - 1);
1488- CmpI(r, n);
1489- Check(ccB, 0, p, r, NoMem, n, -1);
1490-end;
1491-
1492-{ The integer on top is a position of an enumeration of n names }
1493-procedure CheckEnum(n: int64; name: longint; const p: TPos);
1494-var r: longint;
1495-begin
1496- r := Top;
1497- CmpI(r, n);
1498- Check(ccB, 2, p, r, NoMem, n, name);
1499-end;
1500-
1501-{ The address on top, from a pointer, which is to be used reach bytes
1502- past: the program stops if it is nil, unless the machine would stop
1503- it, as for a reach within NilPage. }
1504-procedure CheckNil(reach: int64; const p: TPos);
1505-var r: longint;
1506-begin
1507- if reach <= NilPage then exit;
1508- r := Top;
1509- TestRR(r, r);
1510- Check(ccNE, 4, p, r, NoMem, 0, -1);
1511-end;
1512-
1513-{ The displacement disp of an element of size bytes, with the offset of
1514- the index on top taken into it if it fits: s[k - 1] is [r13 + r9 * 8
1515- - 8] }
1516-function IndexOff(size, disp: int64): int64;
1517-begin
1518- IndexOff := disp;
1519- if Fits32(disp + stack[depth - 1].off * size) then IndexOff := disp + TakeOff(depth - 1) * size;
1520-end;
1521-
1522-{ Pops an index, and the address of the slice at a if it is on the
1523- stack, and pushes the address of its element of size bytes: the
1524- index, checked against the length, times size, plus the pointer.
1525- It is worked out in the index's own register, which then holds the
1526- address; but if the slice's address is on the stack, under the
1527- index, the element's register is the one that holds that, still
1528- needed, so the work is done in rax. A slice in registers is
1529- compared with and added to them; for an element of 1, 2, 4 or 8
1530- bytes, its address is only noted, as the operand [pointer + index *
1531- size], to be read or written where it is used (lIdx). }
1532-procedure IndexSlice(const a: TAdr; size: int64; checked: boolean; const p: TPos);
1533-var m, ml: TMem; r: longint; inRax: boolean; o: int64;
1534-begin
1535- if (a.base = bReg) and (size in [1, 2, 4, 8]) then begin
1536- o := 0;
1537- if not checked then o := IndexOff(size, 0);
1538- r := Peek(depth - 1);
1539- if checked then begin
1540- Alu(aluCmp, r, a.hi);
1541- Check(ccB, 0, p, r, InRegister(a.hi), 0, -1);
1542- end;
1543- Drop;
1544- NewMem(lIdx, MemIdx(a.chunk, r, size, o), kWord, 8, false);
1545- exit;
1546- end;
1547- inRax := a.base = bStack;
1548- if inRax then begin r := RAX; PopTo(RAX) end
1549- else begin r := Top; Drop end;
1550- if a.base = bReg then begin
1551- if checked then begin
1552- Alu(aluCmp, r, a.hi);
1553- Check(ccB, 0, p, r, InRegister(a.hi), 0, -1);
1554- end;
1555- MulI(r, size);
1556- Alu(aluAdd, r, a.chunk);
1557- end else begin
1558- m := Place(a, RCX);
1559- ml := m; ml.disp := ml.disp + 8;
1560- if checked then begin
1561- AluM(aluCmp, r, ml);
1562- Check(ccB, 0, p, r, ml, 0, -1);
1563- end;
1564- MulI(r, size);
1565- AluM(aluAdd, r, m);
1566- end;
1567- if inRax then MovRR(Target, RAX)
1568- else Claim(depth, kWord); { the index's register again, now for the address }
1569- Computed(kWord);
1570-end;
1571-
1572-{ Pops an index, checked, and makes the address of the element it
1573- picks of the array at a. An element of 1, 2,
1574- 4 or 8 bytes is only noted, as the operand [base + index * size]
1575- (lIdx): an array in the frame has rbp as its base, and one in a
1576- chunk, if the index is a variable's register, its address made in
1577- the value's own register. Any other is added up. }
1578-procedure IndexArray(const a: TAdr; size: int64);
1579-var r, b: longint; o: int64;
1580-begin
1581- if (size in [1, 2, 4, 8]) and (a.base = bFrame) then begin
1582- o := IndexOff(size, a.off);
1583- r := Peek(depth - 1);
1584- Drop;
1585- NewMem(lIdx, MemIdx(RBP, r, size, o), kWord, 8, false);
1586- end else if (size in [1, 2, 4, 8]) and (a.base = bGlobal) and (stack[depth - 1].loc = lHeld) then begin
1587- o := IndexOff(size, 0);
1588- r := Peek(depth - 1);
1589- Drop;
1590- b := Target;
1591- Lea(b, MemRip(a.chunk, a.off));
1592- NewMem(lIdx, MemIdx(b, r, size, o), kWord, 8, false);
1593- end else begin
1594- MulI(Top, size);
1595- PushAdr(a);
1596- Op(sPlus, kWord, 8, false);
1597- end;
1598-end;
1599-
1600-{ Pops lo and hi, and the address of the array or slice at a if it is
1601- on the stack, and makes the slice lo..hi of it, with elements of size
1602- bytes, in the frame at tmp; the array has n elements. }
1603-procedure Slice(const a: TAdr; isArray: boolean; n, size, tmp: int64; checked: boolean; const p: TPos);
1604-var m, ml: TMem;
1605-begin
1606- PopTo(RDX);
1607- PopTo(RCX);
1608- if a.base = bSlot then ClobberArgs; { Place loads its slot into rdi }
1609- if a.base = bReg then ml := InRegister(a.hi) { a slice in registers }
1610- else begin
1611- m := Place(a, RDI);
1612- ml := m; ml.disp := ml.disp + 8;
1613- end;
1614- if checked then begin
1615- { two checks, both unsigned, so that a negative bound fails too:
1616- hi against the length, then lo against hi }
1617- if isArray then begin CmpI(RDX, n); ml := NoMem end
1618- else if a.base = bReg then Alu(aluCmp, RDX, a.hi)
1619- else AluM(aluCmp, RDX, ml);
1620- Check(ccBE, 1, p, RCX, ml, n, -1);
1621- Alu(aluCmp, RCX, RDX);
1622- Check(ccBE, 1, p, RCX, ml, n, -1);
1623- end;
1624- MovRR(RAX, RDX);
1625- Alu(aluSub, RAX, RCX);
1626- Store(Mem(RBP, tmp + 8), RAX, 8);
1627- MulI(RCX, size);
1628- if isArray then Lea(RAX, m)
1629- else if a.base = bReg then MovRR(RAX, a.chunk)
1630- else Load(RAX, m, 8, false);
1631- Alu(aluAdd, RAX, RCX);
1632- Store(Mem(RBP, tmp), RAX, 8);
1633-end;
1634-
1635-{ COPY: the elements of the slice in the frame at sOff, of size bytes
1636- each, to the start of the one at dOff, which must be at least as long
1637- (the source may be shorter), as one block; backwards when the
1638- destination is above the source, so that an overlap comes out right. }
1639-procedure CopySlice(dOff, sOff, size: int64; checked: boolean; const p: TPos);
1640-var ml: TMem; L, E: longint;
1641-begin
1642- ClobberArgs;
1643- Load(RDX, Mem(RBP, sOff + 8), 8, false);
1644- if checked then begin
1645- ml := Mem(RBP, dOff + 8);
1646- MovRI(RAX, 0);
1647- AluM(aluCmp, RDX, ml);
1648- Check(ccBE, 1, p, RAX, ml, 0, -1);
1649- end;
1650- MovRR(RCX, RDX);
1651- MulI(RCX, size);
1652- Load(RSI, Mem(RBP, sOff), 8, false);
1653- Load(RDI, Mem(RBP, dOff), 8, false);
1654- Alu(aluCmp, RDI, RSI);
1655- L := NoLabel;
1656- Jcc(ccBE, L); { the destination is not above: forwards, at L }
1657- { backwards: std makes rep movsb run downward, so it starts at the
1658- last byte of each }
1659- Lea(RSI, MemIdx(RSI, RCX, 1, -1));
1660- Lea(RDI, MemIdx(RDI, RCX, 1, -1));
1661- Std;
1662- RepMovsb;
1663- Cld;
1664- E := NoLabel;
1665- Jmp(E);
1666- FixLink(L);
1667- RepMovsb;
1668- FixLink(E);
1669-end;
1670-
1671-{ Pops a pointer, lo and hi, and makes the slice p[lo..hi] at tmp. Its
1672- bounds can't be known, but it can't run backwards. }
1673-procedure SlicePtr(size, tmp: int64; checked: boolean; const p: TPos);
1674-begin
1675- ClobberArgs;
1676- PopTo(RDX);
1677- PopTo(RCX);
1678- PopTo(RDI);
1679- if checked then begin
1680- Alu(aluCmp, RCX, RDX);
1681- Check(ccLE, 3, p, RCX, NoMem, 0, -1);
1682- end;
1683- MovRR(RAX, RDX);
1684- Alu(aluSub, RAX, RCX);
1685- Store(Mem(RBP, tmp + 8), RAX, 8);
1686- MulI(RCX, size);
1687- Alu(aluAdd, RCX, RDI);
1688- Store(Mem(RBP, tmp), RCX, 8);
1689-end;
1690-
1691-{ Calls }
1692-
1693-{ The call c, its c.n arguments the values on top of the stack, in
1694- registers, noted as constants or spilled. They go to registers or the
1695- machine's stack, the procedure is called, and its result, if any,
1696- comes back: one value is pushed, two results are pushed as two values,
1697- a slice or a record is stored in the temporary c.ret.
1698-
1699- ni and nf count the integer and the real registers used so far, k the
1700- arguments on the machine's stack, and pad is 1 when a padding quadword
1701- is needed. }
1702-
1703-procedure Call(var c: TCall);
1704-var
1705- res: PType; i, ni, nf, k, pad, r, first: longint;
1706- onStack: array[0..63] of boolean; late: array[4..5] of longint;
1707-begin
1708- { the arguments are the c.n values on top, where computing them left
1709- them; the registers in use under them are saved around the call }
1710- ClobberArgs;
1711- first := depth - c.n;
1712- SpillBelow(first);
1713- res := c.sig^.base;
1714- c.ret := 0;
1715- ni := 0; nf := 0;
1716- if (res <> nil) and (BehindPointer(res) or (res^.form = fSlice)) then begin
1717- c.ret := AllocTemp(res^.size, res^.align);
1718- if BehindPointer(res) then ni := 1;
1719- end;
1720- { the System V classes: each argument in the next free register of
1721- its kind, or else on the stack }
1722- k := 0;
1723- for i := 0 to c.n - 1 do begin
1724- if c.isF[i] then begin onStack[i] := nf >= 8; if nf < 8 then inc(nf) end
1725- else begin
1726- { a slice's words both go in registers, or both on the stack }
1727- if (i > 0) and c.pair[i - 1] then onStack[i] := onStack[i - 1]
1728- else if c.pair[i] then onStack[i] := ni > 4
1729- else onStack[i] := ni >= 6;
1730- if not onStack[i] then inc(ni);
1731- end;
1732- if onStack[i] then inc(k);
1733- end;
1734- { System V wants rsp a multiple of 16 at the call. A procedure's body
1735- has it so (push rbp, and a frame size that is a multiple of 16), so
1736- a quadword of padding makes the count pushed since even. The stack
1737- arguments go right to left, so that the first is at the lowest
1738- address. }
1739- pad := ord(odd(pushed + k));
1740- if pad <> 0 then AluI(aluSub, RSP, 8);
1741- for i := c.n - 1 downto 0 do
1742- if onStack[i] then begin
1743- ValueTo(first + i, RAX);
1744- Push(RAX);
1745- end;
1746- ni := 0; nf := 0;
1747- late[4] := -1; late[5] := -1;
1748- if (c.ret <> 0) and BehindPointer(res) then begin Lea(RDI, Mem(RBP, c.ret)); ni := 1 end;
1749- { rdi, rsi, rdx, rcx and the xmm registers first; r8 and r9 last, as
1750- they are stack registers and may hold arguments not yet moved: late
1751- is the value for each. The fifth goes through rax, so that writing r8
1752- doesn't destroy a value still wanted for r9. }
1753- for i := 0 to c.n - 1 do
1754- if not onStack[i] then
1755- if c.isF[i] then begin
1756- XValueTo(first + i, nf);
1757- inc(nf);
1758- end else begin
1759- if ni < 4 then ValueTo(first + i, IntRegs[ni]) else late[ni] := first + i;
1760- inc(ni);
1761- end;
1762- if late[4] >= 0 then ValueTo(late[4], RAX);
1763- if late[5] >= 0 then ValueTo(late[5], R9);
1764- if late[4] >= 0 then MovRR(R8, RAX);
1765- for i := 1 to c.n do Drop;
1766- { a procedure taking ... is told in al how many xmm registers it got }
1767- if c.sig^.variadic then MovRI(RAX, nf);
1768- if c.ext then CallM(MemRip(c.chunk, 0))
1769- else if c.chunk >= 0 then CallChunk(c.chunk)
1770- else begin
1771- { r11 is scratch: caller-saved, carrying no argument, and free,
1772- as the value stack was spilled above }
1773- Load(R11, Mem(RBP, c.target), 8, false);
1774- CallR(R11);
1775- end;
1776- if k + pad > 0 then AluI(aluAdd, RSP, 8 * (k + pad));
1777- { the variables in xmm registers, which the call may have changed,
1778- from their slots }
1779- for i := 0 to 3 do
1780- if regMask and (1 shl (XBit + i)) <> 0 then MovsXM(XVarRegs[i] - XmmVar, Mem(RBP, homes[i]), false);
1781- { the result: a slice in rax and rdx goes to the caller's temporary,
1782- two results on the stack, the first under the second, and a single
1783- value on top }
1784- if res = nil then
1785- { nothing comes back }
1786- else if res^.form = fSlice then begin
1787- Store(Mem(RBP, c.ret), RAX, 8);
1788- Store(Mem(RBP, c.ret + 8), RDX, 8);
1789- end else if InTwoRegs(res) then begin
1790- MovRR(Target, RAX); Computed(kWord);
1791- MovRR(Target, RDX); Computed(kWord);
1792- end else if (c.ret = 0) and (res^.form = fReal) then begin
1793- MovX(XTarget, 0);
1794- Computed(KindOf(res));
1795- end else if c.ret = 0 then begin
1796- r := Target;
1797- MovRR(r, RAX);
1798- if res^.form = fBool then Extend(r, 1, false)
1799- else if (res^.form = fInt) and (res^.size < 8) then Extend(r, res^.size, res^.signed);
1800- Computed(KindOf(res));
1801- end;
1802-end;
1803-
1804-{ Frames }
1805-
1806-{ A slot of size bytes in the frame: its offset from rbp, negative, as
1807- the frame grows down. A temporary is released at the end of its
1808- statement (TempMark, ReleaseTemps); AllocPerm's lasts the procedure. }
1809-function AllocTemp(size, align: int64): int64;
1810-begin
1811- if align < 1 then align := 1;
1812- frameTop := AlignUp(frameTop + size, align);
1813- if frameTop > frameMax then frameMax := frameTop;
1814- AllocTemp := -frameTop;
1815-end;
1816-
1817-function AllocPerm(size, align: int64): int64;
1818-begin
1819- AllocPerm := AllocTemp(size, align);
1820- permTop := frameTop;
1821-end;
1822-
1823-function TempMark: int64;
1824-begin
1825- TempMark := frameTop;
1826-end;
1827-
1828-{ The slots allocated since the mark m are free again, but those
1829- AllocPerm made stay }
1830-procedure ReleaseTemps(m: int64);
1831-begin
1832- if m < permTop then m := permTop;
1833- frameTop := m;
1834-end;
1835-
1836-{ Every slot used so far stays reserved for the rest of the procedure:
1837- a deferred statement's temporaries live until it runs. }
1838-procedure KeepTemps;
1839-begin
1840- frameTop := frameMax;
1841- permTop := frameMax;
1842-end;
1843-
1844-{ The parameters' places: each in a frame slot of its own, stored there
1845- from its register on entry, or above the frame where the caller
1846- pushed it. A var parameter, and a record or array passed by value,
1847- holds an address (ind). }
1848-procedure BeginProc(sig: PType; params: PObj);
1849-var p: PObj; ni, nf, k: longint; stackOff: int64; f: boolean;
1850-begin
1851- frameTop := 0; frameMax := 0; permTop := 0;
1852- ResetStack(0, 0);
1853- exitL := NoLabel;
1854- numIn := 0;
1855- lost := false;
1856- kept := 0;
1857- resType := sig^.base;
1858- procParams := params;
1859- regMask := 0;
1860- ni := 0; nf := 0; stackOff := 16; { stackOff: above the saved rbp and the return address }
1861- if (resType <> nil) and BehindPointer(resType) then begin
1862- retSlot := AllocPerm(8, 8);
1863- inReg[0] := RDI; inSlot[0] := retSlot; inSize[0] := 8; inObj[0] := nil;
1864- numIn := 1; ni := 1;
1865- end;
1866- p := params;
1867- while p <> nil do begin
1868- p^.ind := p^.isVar or (IsAggregate(p^.typ) and (p^.typ^.form <> fSlice));
1869- f := (p^.typ^.form = fReal) and not p^.isVar;
1870- if (p^.typ^.form = fSlice) and not p^.isVar then begin
1871- { its two words, in two registers or both on the stack }
1872- if ni <= 4 then begin
1873- p^.val := AllocPerm(16, 8);
1874- for k := 0 to 1 do begin
1875- inReg[numIn] := IntRegs[ni]; inSlot[numIn] := p^.val + 8 * k;
1876- inSize[numIn] := 8; inObj[numIn] := p;
1877- inc(numIn); inc(ni);
1878- end;
1879- end else begin
1880- p^.val := stackOff;
1881- inc(stackOff, 16);
1882- end;
1883- end else if (f and (nf < 8)) or (not f and (ni < 6)) then begin
1884- p^.val := AllocPerm(8, 8);
1885- { a real's register, xmm nf, is told from an integer register by
1886- a negative number (EnterBody decodes it) }
1887- if f then begin inReg[numIn] := -1 - nf; inc(nf) end
1888- else begin inReg[numIn] := IntRegs[ni]; inc(ni) end;
1889- inSlot[numIn] := p^.val;
1890- inObj[numIn] := p;
1891- if p^.ind then inSize[numIn] := 8
1892- else if p^.typ^.form in [fInt, fBool, fEnum, fSet, fReal] then inSize[numIn] := p^.typ^.size
1893- else inSize[numIn] := 8;
1894- inc(numIn);
1895- end else begin
1896- p^.val := stackOff;
1897- inc(stackOff, 8);
1898- end;
1899- p := p^.next;
1900- end;
1901- paramTop := frameTop;
1902-end;
1903-
1904-{ The frame as BeginProc left it, with the parameters' slots only: the
1905- locals are given theirs again once their registers are chosen. }
1906-procedure ResetLocals;
1907-begin
1908- frameTop := paramTop; frameMax := paramTop; permTop := paramTop;
1909-end;
1910-
1911-{ The register the word (0, or 1 for a slice's second) of parameter o
1912- arrives in, or -1 if it comes on the stack or in an xmm register }
1913-function ArrivesIn(o: PObj; word: longint): longint;
1914-var i: longint;
1915-begin
1916- ArrivesIn := -1;
1917- for i := 0 to numIn - 1 do
1918- if (inObj[i] = o) and (inSlot[i] = o^.val + 8 * word) and (inReg[i] >= 0) then ArrivesIn := inReg[i];
1919-end;
1920-
1921-{ Parameter o, of a procedure that calls nothing, stays in the register
1922- it arrives in if that is rdi or rsi, which only a call or a copy needs:
1923- no register is saved for it, and nothing is moved. A slice stays only
1924- if it has both. If the procedure turns out to copy after all, lost is
1925- set, and it is compiled again with o in memory. }
1926-procedure KeepArrived(o: PObj);
1927-var r: longint;
1928-begin
1929- r := ArrivesIn(o, 0);
1930- if o^.typ^.form = fSlice then begin
1931- if (r = RDI) and (ArrivesIn(o, 1) = RSI) then begin o^.reg := RDI; o^.reg2 := RSI end;
1932- end else if (r = RDI) or (r = RSI) then o^.reg := r;
1933-end;
1934-
1935-{ Whether parameter o is kept where it arrived }
1936-function KeptIn(o: PObj): boolean;
1937-begin
1938- KeptIn := (o^.reg = RDI) or (o^.reg = RSI);
1939-end;
1940-
1941-{ The locals in memory have their slots: the prologue zeroes those and
1942- nothing below. The procedure keeps variables in the registers of
1943- mask, which are saved next, a quadword each, in slots that need no
1944- zeroing; the frame as it then stands is where a second try at the
1945- body starts. }
1946-procedure UseRegs(mask: longint);
1947-var i, k: longint; p: PObj;
1948-begin
1949- zeroTop := permTop;
1950- regMask := mask;
1951- { the parameters left in rdi and rsi, as they arrived }
1952- kept := 0;
1953- p := procParams;
1954- while p <> nil do begin
1955- if p^.reg in [RDI, RSI] then kept := kept or (1 shl p^.reg);
1956- if p^.reg2 in [RDI, RSI] then kept := kept or (1 shl p^.reg2);
1957- p := p^.next;
1958- end;
1959- k := 0;
1960- for i := 0 to 4 do if mask and (1 shl i) <> 0 then inc(k);
1961- if k > 0 then saveAt := AllocPerm(8 * k, 8);
1962- frameAt[0] := frameTop; frameAt[1] := frameMax; frameAt[2] := permTop;
1963-end;
1964-
1965-{ The variable in xmm register r of XVarRegs has a slot of 8 bytes at
1966- slot, kept as it changes }
1967-procedure XHome(r: longint; slot: int64);
1968-begin
1969- homes[r - XVarRegs[0]] := slot;
1970-end;
1971-
1972-procedure MarkCode(var m: TCodeMark);
1973-begin
1974- m.pc := pc; m.fixups := numFixups; m.lines := numLines; m.said := SaidCount;
1975- m.fails := numFails;
1976-end;
1977-
1978-{ The code made since m taken back, as if it had never been made; the
1979- frame is left as it is }
1980-procedure Rewind(const m: TCodeMark);
1981-begin
1982- pc := m.pc; numFixups := m.fixups; numLines := m.lines; Unsay(m.said);
1983- numFails := m.fails;
1984-end;
1985-
1986-{ For a second try at the body: the code as it was at m, and the frame
1987- as UseRegs found it }
1988-procedure Redo(const m: TCodeMark);
1989-begin
1990- pc := m.pc; numFixups := m.fixups; numLines := m.lines; Unsay(m.said);
1991- numFails := 0;
1992- lost := false;
1993- frameTop := frameAt[0]; frameMax := frameAt[1]; permTop := frameAt[2];
1994- exitL := NoLabel;
1995-end;
1996-
1997-{ The prologue, which is for the procedure's first line. Only the
1998- locals in memory are zeroed, from the parameters' slots down to
1999- zeroTop: the parameters are stored over their slots next, the
2000- registers of variables are zeroed in place, their save slots are
2001- written before they are read, and so is every temporary. }
2002-procedure EnterBody(c, line: longint);
2003-var i, top, r: longint; n: int64; p: PObj;
2004-begin
2005- BeginChunk(c);
2006- codeChunk := c;
2007- NoteLine(line, 1); { a declaration starts a line }
2008- Push(RBP);
2009- MovRR(RBP, RSP);
2010- Say('sub rsp, frame');
2011- { sub rsp, imm32: always the form with a 32-bit field, so that EndProc
2012- can patch the frame's size in }
2013- Put1($48); Put1($81); Put1($EC);
2014- frameFix := pc; Put4(0);
2015- n := (AlignUp(zeroTop, 8) - paramTop) div 8;
2016- if n > 0 then MovRI(RAX, 0);
2017- if n <= 4 then
2018- for i := 1 to n do Store(Mem(RBP, -paramTop - 8 * i), RAX, 8)
2019- else begin
2020- { a quadword at a time: r10 runs from -n up to 0, and the store's
2021- address is scaled by it }
2022- MovRI(R10, -n);
2023- top := pc;
2024- Store(MemIdx(RBP, R10, 8, -paramTop), RAX, 8);
2025- AluI(aluAdd, R10, 1);
2026- JccBack(ccNE, top);
2027- end;
2028- { each register that holds a variable is saved, for the caller, and
2029- zeroed, as a variable starts at zero }
2030- chunks^[c].saveMask := regMask and (1 shl XBit - 1);
2031- chunks^[c].saveAt := saveAt;
2032- n := 0;
2033- for i := 0 to 4 do
2034- if regMask and (1 shl i) <> 0 then begin
2035- Store(Mem(RBP, saveAt + 8 * n), VarRegs[i], 8);
2036- MovRI(VarRegs[i], 0);
2037- inc(n);
2038- end;
2039- { and each xmm register that holds a variable, zeroed, as its slot
2040- is: the caller keeps its own }
2041- for i := 0 to 3 do
2042- if regMask and (1 shl (XBit + i)) <> 0 then begin
2043- MovRI(RAX, 0);
2044- MovqXR(XVarRegs[i] - XmmVar, RAX);
2045- end;
2046- { the parameters that came in registers, to their slots or, for a
2047- register variable, to its register: a slice's second word, the one
2048- for the slot 8 bytes into its own, to its length's }
2049- for i := 0 to numIn - 1 do
2050- if inReg[i] < 0 then begin
2051- MovsMX(Mem(RBP, inSlot[i]), -1 - inReg[i], false);
2052- if inObj[i]^.reg <> 0 then MovX(inObj[i]^.reg - XmmVar, -1 - inReg[i]);
2053- end
2054- else if (inObj[i] <> nil) and (inObj[i]^.reg <> 0) then begin
2055- r := inObj[i]^.reg;
2056- if inSlot[i] <> inObj[i]^.val then r := inObj[i]^.reg2;
2057- if r <> inReg[i] then MovRR(r, inReg[i]); { else it is kept where it is }
2058- if inSize[i] < 8 then Extend(r, inSize[i], inObj[i]^.typ^.signed);
2059- end else Store(Mem(RBP, inSlot[i]), inReg[i], inSize[i]);
2060- { a register variable's parameter that came on the stack, above the
2061- frame (val > 0), is loaded from there }
2062- p := procParams;
2063- while p <> nil do begin
2064- if (p^.reg <> 0) and (p^.val > 0) then
2065- if p^.typ^.form = fReal then MovsXM(p^.reg - XmmVar, Mem(RBP, p^.val), p^.typ^.size = 4)
2066- else if p^.typ^.form in [fInt, fBool, fEnum, fSet] then
2067- Load(p^.reg, Mem(RBP, p^.val), p^.typ^.size, p^.typ^.signed)
2068- else begin
2069- Load(p^.reg, Mem(RBP, p^.val), 8, false);
2070- if p^.typ^.form = fSlice then Load(p^.reg2, Mem(RBP, p^.val + 8), 8, false);
2071- end;
2072- p := p^.next;
2073- end;
2074-end;
2075-
2076-{ Pops one of several results, a value of size bytes, into its place
2077- off bytes into the caller's, behind the hidden pointer. }
2078-procedure ResultTo(off: int64; size: longint);
2079-var r: longint; real: boolean;
2080-begin
2081- r := Top;
2082- real := IsReal(depth - 1);
2083- Drop;
2084- Load(RCX, Mem(RBP, retSlot), 8, false);
2085- if real then MovsMX(Mem(RCX, off), r, size = 4)
2086- else Store(Mem(RCX, off), r, size);
2087-end;
2088-
2089-{ Pops an address, and copies size bytes from it to the result, off
2090- bytes into it. }
2091-procedure CopyResult(off, size: int64);
2092-begin
2093- ClobberArgs;
2094- PopTo(RSI);
2095- Load(RDI, Mem(RBP, retSlot), 8, false);
2096- if off <> 0 then Lea(RDI, Mem(RDI, off));
2097- CopyBytes(size);
2098-end;
2099-
2100-{ return: the result, a value on top, goes in rax or xmm0; two words,
2101- the two values on top, in rax and rdx; one behind the hidden pointer
2102- goes back with that pointer in rax. }
2103-procedure ReturnJump;
2104-begin
2105- if resType <> nil then
2106- if BehindPointer(resType) then Load(RAX, Mem(RBP, retSlot), 8, false)
2107- else if InTwoRegs(resType) then begin
2108- PopTo(RDX);
2109- PopTo(RAX);
2110- end else begin
2111- if resType^.form = fReal then begin XValueTo(depth - 1, 0); Drop end
2112- else PopTo(RAX);
2113- end;
2114- Jmp(exitL);
2115-end;
2116-
2117-{ The first of what try does where the error isn't nil (the report, 7.8):
2118- the machine's stack made even, as the deferred statements about to be
2119- run expect to find it. try can stand among the arguments of another
2120- call, where quadwords have been pushed. Nothing is lost: the frame is
2121- above rsp, and the code returns through the frame pointer. }
2122-procedure TryAlign;
2123-begin
2124- AluI(aluAnd, RSP, -16);
2125-end;
2126-
2127-{ The rest of it: the procedure returns the error in the frame slot, and
2128- a zero for each of its other results. Only code is made: no entry of
2129- the stack of values is touched, since the code that follows is the
2130- code for an error that is nil, with the stack as it was. }
2131-procedure TryReturn(slot: int64);
2132-var f: PObj;
2133-begin
2134- if BehindPointer(resType) then begin
2135- Load(RDI, Mem(RBP, retSlot), 8, false);
2136- MovRI(RCX, resType^.size);
2137- MovRI(RAX, 0);
2138- RepStosb;
2139- f := resType^.fields;
2140- while f^.next <> nil do f := f^.next;
2141- Load(RCX, Mem(RBP, slot), 8, false);
2142- Load(RDX, Mem(RBP, retSlot), 8, false);
2143- Store(Mem(RDX, f^.val), RCX, 8);
2144- Load(RAX, Mem(RBP, retSlot), 8, false);
2145- end else if InTwoRegs(resType) then begin
2146- Load(RDX, Mem(RBP, slot), 8, false);
2147- MovRI(RAX, 0);
2148- end else Load(RAX, Mem(RBP, slot), 8, false);
2149- Jmp(exitL);
2150-end;
2151-
2152-{ The end of the procedure in chunk c: the code that returns, and the
2153- frame's size, known only now, patched into its prologue. If it is
2154- open, running off its end, it returns zeros. }
2155-procedure EndProc(c: longint; open: boolean);
2156-var n: int64; i: longint;
2157-begin
2158- codeChunk := -1;
2159- if (depth <> 0) or (pushed <> 0) then Fatal('internal error: stack depth');
2160- if open then begin
2161- if BehindPointer(resType) then begin
2162- Load(RDI, Mem(RBP, retSlot), 8, false);
2163- MovRI(RCX, resType^.size);
2164- MovRI(RAX, 0);
2165- RepStosb;
2166- Load(RAX, Mem(RBP, retSlot), 8, false);
2167- end else begin
2168- MovRI(RAX, 0);
2169- if InTwoRegs(resType) then MovRI(RDX, 0);
2170- MovqXR(0, RAX);
2171- end;
2172- end else DropJumpTo(exitL);
2173- FixLink(exitL);
2174- n := 0;
2175- for i := 0 to 4 do
2176- if regMask and (1 shl i) <> 0 then begin
2177- Load(VarRegs[i], Mem(RBP, saveAt + 8 * n), 8, false);
2178- inc(n);
2179- end;
2180- Leave;
2181- Ret;
2182- EndFails;
2183- n := AlignUp(frameMax, 16);
2184- if n < 16 then n := 16;
2185- if n > high(longint) then Mark('frame too big');
2186- Put4At(frameFix, n);
2187- { the listing's text for the sub, which starts 3 bytes (REX.W, opcode,
2188- ModRM) before its immediate }
2189- Restate(frameFix - 3, 'sub rsp, ' + IntStr(n));
2190- EndChunk(c);
2191-end;
2192-
2193-{ A deferred statement is compiled where it stands, as a subroutine of
2194- its procedure that the code jumps over, in the procedure's own frame
2195- (the same rbp), so that it sees all its variables; DeferBegin gives its address
2196- and starts it, with the return address pushed. The stack is empty
2197- where it is called, and where it begins. }
2198-function DeferBegin(var L, saved: longint): longint;
2199-begin
2200- Jmp(L);
2201- saved := pushed;
2202- pushed := 1;
2203- DeferBegin := pc;
2204-end;
2205-
2206-procedure DeferEnd(L, saved: longint);
2207-begin
2208- KeepTemps;
2209- Ret;
2210- FixLink(L);
2211- pushed := saved;
2212-end;
2213-
2214-procedure RunDefer(at: longint);
2215-begin
2216- CallBack(at);
2217-end;
2218-
2219-{ The entry point, _start, and its chunk: it saves argc and argv, and
2220- the address of the places for Rt; runs every used module's body, then
2221- main; and ends with Rt.exit, its status main's or 0. A dynamic program
2222- starts as C's crt1 does, through __libc_start_main(main, argc, argv,
2223- nil, nil, rtld_fini, stack_end), with rsp aligned; its main first
2224- gives Rt C's exit, in cExit.
2225-
2226- dynamic: the program uses C. first: the first module, whose chain
2227- gives the order of the bodies. main: the program's main procedure, or
2228- nil. cExit and exitProc: the chunks of Rt's cExit and exit. The
2229- first numLinks of links: the addresses Rt is given, of what the program has: the places, and
2230- the profiler and calls; what it isn't given, nothing reaches, and the
2231- linker leaves out. }
2232-function EntryPoint(dynamic: boolean; first: PModule; main: PObj; cExit, exitProc: longint; const links: array of TLink; numLinks: longint): longint;
2233-var entry, start, i: longint; m: PModule;
2234-begin
2235- entry := NewChunk(secText, -1, Intern('_start', 6));
2236- if dynamic then begin
2237- start := NewChunk(secText, -1, Intern('main', 4));
2238- BeginChunk(entry);
2239- { at the start rdx holds rtld_fini, from the dynamic loader, and the
2240- stack argc, then argv }
2241- MovRI(RBP, 0); { no frame above, where a trace stops }
2242- MovRR(R9, RDX); { rtld_fini, the sixth argument }
2243- Pop(RSI); { argc, the second }
2244- MovRR(RDX, RSP); { argv, the third }
2245- AluI(aluAnd, RSP, -16);
2246- Push(RAX); { padding, so that the next push, the seventh }
2247- Push(RSP); { argument, stack_end, leaves rsp aligned }
2248- MovRI(R8, 0); { fini and init: none }
2249- MovRI(RCX, 0);
2250- Lea(RDI, MemRip(start, 0)); { main, the first argument }
2251- CallM(MemRip(ExternChunk(Intern('__libc_start_main', 17)), 0));
2252- Ud2; { it never returns }
2253- EndChunk(entry);
2254- BeginChunk(start);
2255- Push(RBP); { aligns the stack again }
2256- Store(MemRip(argcChunk, 0), RDI, 8);
2257- Store(MemRip(argvChunk, 0), RSI, 8);
2258- Load(RAX, MemRip(ExternChunk(Intern('exit', 4)), 0), 8, false);
2259- Store(MemRip(cExit, 0), RAX, 8);
2260- end else begin
2261- start := entry;
2262- BeginChunk(entry);
2263- Load(RAX, Mem(RSP, 0), 8, false);
2264- Store(MemRip(argcChunk, 0), RAX, 8);
2265- Lea(RAX, Mem(RSP, 8));
2266- Store(MemRip(argvChunk, 0), RAX, 8);
2267- end;
2268- for i := 0 to numLinks - 1 do begin
2269- Lea(RAX, MemRip(links[i].chunk, 0));
2270- Store(MemRip(links[i].into, 0), RAX, 8);
2271- end;
2272- m := first;
2273- while m <> nil do begin
2274- if m^.used and (m^.body >= 0) then CallChunk(m^.body);
2275- m := m^.next;
2276- end;
2277- if main <> nil then CallChunk(main^.chunk);
2278- if (main <> nil) and (main^.typ^.base <> nil) then MovRR(RDI, RAX) else MovRI(RDI, 0);
2279- CallChunk(exitProc);
2280- Ud2; { exit never returns: trap if it does }
2281- EndChunk(start);
2282- { Rt.fail, for the failures of each kind: the place is where the
2283- check's call is. The return address is the next instruction's, which
2284- may belong to another line; one byte back is inside the call, so the
2285- lookup finds the call's line. rsp is aligned for the call, as the
2286- check's code may have pushed an odd number of quadwords. rdi and rsi
2287- as the failing code had them go on the stack, as Rt.fail's last two
2288- arguments, and a comes in rax (EndFails). }
2289- for i := 0 to High(failStubs) do
2290- if failStubs[i] >= 0 then begin
2291- BeginChunk(failStubs[i]);
2292- Load(R8, Mem(RSP, 0), 8, false);
2293- AluI(aluSub, R8, 1);
2294- AluI(aluAnd, RSP, -16);
2295- Push(RSI);
2296- Push(RDI);
2297- MovRR(RSI, RAX);
2298- MovRI(RDI, i);
2299- CallChunk(rtFail);
2300- Ud2;
2301- EndChunk(failStubs[i]);
2302- end;
2303- EntryPoint := entry;
2304-end;
2305-
2306-{ A code procedure: its instructions, read by the assembler (x64.pas),
2307- are the whole of chunk c }
2308-procedure CodeProc(c: longint; constExpr: TConstFn);
2309-begin
2310- BeginChunk(c);
2311- Assemble(constExpr);
2312- EndChunk(c);
2313-end;
2314-
2315-initialization
2316- ResetStack(0, 0);
2317- rtFail := NewChunk(secText, Intern('Rt', 2), Intern('fail', 4));
2318- argcChunk := NewChunk(secBss, -1, Intern('argc', 4));
2319- SetBss(argcChunk, 8, 8);
2320- argvChunk := NewChunk(secBss, -1, Intern('argv', 4));
2321- SetBss(argvChunk, 8, 8);
2322-end.

src/item.pas deleted +0 -1575

@@ -1,1575 +0,0 @@
1-{ item.pas: operands, their types, and what they mean.
2-
3- The parser describes each operand as an item (TItem), as in Wirth's
4- compilers: a constant, a variable at an address it can name, a value
5- on gen's stack, a procedure, a string. The routines here check the
6- items' types, fold constants, and have gen.pas make the code, as calls
7- of its stack machine; nothing here knows the machine.
8-
9- Depends on: scan for errors, sym for types, chunk for data, gen for
10- code.
11- Leaves out: the language's syntax, which is parse.pas; the machine,
12- which is gen.pas. }
13-
14-unit item;
15-
16-{$mode objfpc}{$H-}
17-
18-interface
19-
20-uses scan, diag, sym, chunk, gen;
21-
22-type
23- TMode = (mConst, mVar, mStack, mProc, mType, mStr, mBuiltin, mCase, mNone, mCond,
24- mWords); { two results of a call, on the stack, the first under the second }
25-
26- TItem = record
27- mode: TMode;
28- typ: PType;
29- rel: TSym; { mCond: the comparison of the two integers on
30- the stack, not yet made, as Wirth's compilers
31- keep a condition }
32- relSigned: boolean;
33- fj, tj: longint; { mCond: the chains of jumps already made that are
34- taken when the whole condition is false, and when
35- it is true, not yet given a place (and, or and
36- not make them); see gen's JumpOut }
37- val: int64; { mConst: the value, an F64's bits; mStr: its length }
38- base: TBase; { mVar: what the address is relative to }
39- chunk: longint; { mVar with bGlobal, mStr: the chunk; bSlot: the slot }
40- off: int64; { mVar: added to the base }
41- vol: boolean; { mVar: reached through ^VOLATILE }
42- isVar: boolean; { mVar: a variable of the program, not a temporary }
43- odd: boolean; { mVar: in a packed record, so maybe misaligned }
44- ro: boolean; { mVar: another module's exported variable, or part
45- of one, which only that module changes }
46- deref: boolean; { mVar: at an address from a pointer, which may be
47- nil and isn't tested yet (NilTest) }
48- obj: PObj; { mProc, mBuiltin, mCase; mVar: the variable named }
49- pos: TPos; { where it is in the source, for messages }
50- end;
51-
52-var
53- demoted: boolean; { Address wanted a register variable's address: its
54- procedure is compiled again, the variable in memory }
55- checks: boolean; { the module's index and slice checks are made: it
56- doesn't say check off }
57-
58-procedure MakeConst(var x: TItem; t: PType; v: int64);
59-function What(const x: TItem): shortstring;
60-procedure MakeReal(var x: TItem; r: double);
61-procedure MakeStr(var x: TItem);
62-procedure MakeItem(var x: TItem; o: PObj);
63-function RealOf(const x: TItem): double;
64-function FrameAdr(off: int64): TAdr;
65-function GlobalAdr(c: longint): TAdr;
66-function AdrOf(const x: TItem): TAdr;
67-
68-procedure UsesReals(const p: TPos);
69-procedure Value(var x: TItem);
70-procedure Address(var x: TItem);
71-procedure Discard(const x: TItem);
72-procedure NilTest(var x: TItem);
73-procedure Coerce(var x: TItem; t: PType);
74-procedure CoerceExact(var x: TItem; t: PType; const help: shortstring);
75-procedure NotReadOnly(const x: TItem);
76-procedure Assign(var dst, src: TItem);
77-procedure CopyToTemp(var x: TItem);
78-function ToSlot(var x: TItem): int64;
79-
80-procedure Deref(var x: TItem);
81-procedure Field(var x: TItem; f: PObj);
82-procedure IndexPrep(var x: TItem);
83-procedure Index(var x, y: TItem);
84-procedure SliceLo(var lo: TItem);
85-procedure Slice(var x, lo, hi: TItem);
86-
87-procedure Neg(var x: TItem);
88-procedure NotOp(var x: TItem);
89-procedure Complement(var x: TItem);
90-procedure Op1(op: TSym; var x: TItem; var L: longint);
91-procedure Op2(op: TSym; var x, y: TItem; L: longint);
92-function IsWord(t: PType): boolean;
93-procedure Convert(var x: TItem; t: PType);
94-
95-procedure BeginCall(var c: TCall; var x: TItem);
96-procedure PassArg(var c: TCall; var a: TItem);
97-procedure EndCall(var c: TCall; var x: TItem);
98-
99-procedure ZeroTemp(var x: TItem; t: PType);
100-procedure Construct(var x: TItem; c: PObj);
101-procedure SetField(const x: TItem; f: PObj; var a: TItem);
102-function MatchBegin(var x: TItem): int64;
103-procedure MatchTag(p: int64; tag: int64; var L: longint);
104-procedure MatchRange(p, lo, hi: int64; var body: longint);
105-procedure CondJump(var x: TItem; var L: longint);
106-procedure CondJumpTrue(var x: TItem; var L: longint);
107-
108-procedure SliceOf(var x: TItem; t: PType; len: int64);
109-procedure TempItem(var x: TItem; t: PType; off: int64);
110-function ScalarSize(t: PType): longint;
111-procedure ForStep(o: PObj; step: int64);
112-procedure ForCmp(o: PObj; const lim: TItem; op: TSym; var L: longint);
113-procedure ForNext(o: PObj; const lim: TItem; step: int64; var exitL: longint; top, body: longint);
114-
115-procedure BeginProc(sig: PType; params: PObj);
116-procedure ReturnValue(var x: TItem);
117-procedure ReturnField(f: PObj; var x: TItem);
118-procedure ReturnAll(var x: TItem);
119-procedure ReturnNone;
120-procedure Pin(var x: TItem);
121-procedure IncDec(var v, k: TItem; dec: boolean);
122-procedure CopyDest(var d: TItem);
123-procedure CopyFrom(var d, s: TItem);
124-procedure Msg(var x: TItem);
125-function ErrorChunk(var x: TItem; module, name: longint): longint;
126-
127-implementation
128-
129-const
130- { the comparison that holds when op doesn't, for integers }
131- Negated: array[sEql..sGeq] of TSym = (sNeq, sEql, sGeq, sGtr, sLeq, sLss);
132-
133-var
134- result: PType; { the result of the procedure being compiled, or nil }
135-
136-{ Items }
137-
138-procedure MakeConst(var x: TItem; t: PType; v: int64);
139-var p: TPos;
140-begin
141- p := x.pos;
142- FillChar(x, SizeOf(x), 0);
143- x.pos := p;
144- x.mode := mConst;
145- x.typ := t;
146- x.val := v;
147-end;
148-
149-{ A real constant: untyped, unless typed later. Its value is an F64,
150- which for an F32 is one an F32 can hold. }
151-procedure MakeReal(var x: TItem; r: double);
152-begin
153- MakeConst(x, tRConst, 0);
154- Move(r, x.val, 8);
155-end;
156-
157-function IsF32(t: PType): boolean;
158-begin
159- IsF32 := (t^.form = fReal) and (t^.size = 4);
160-end;
161-
162-{ Gives a real constant the real type t, rounded to it. }
163-procedure RealTo(var x: TItem; t: PType);
164-var r: double;
165-begin
166- r := RealOf(x);
167- if IsF32(t) then MakeReal(x, single(r)) else MakeReal(x, r);
168- x.typ := t;
169-end;
170-
171-function RealOf(const x: TItem): double;
172-var r: double;
173-begin
174- Move(x.val, r, 8);
175- RealOf := r;
176-end;
177-
178-{ The current string literal, as an item of its own chunk. }
179-procedure MakeStr(var x: TItem);
180-begin
181- FillChar(x, SizeOf(x), 0);
182- x.mode := mStr;
183- x.typ := tStr;
184- x.val := slen;
185- x.chunk := NewChunk(secRodata, -1, -1);
186- SetData(x.chunk, @sbuf, slen + 1, 1);
187-end;
188-
189-function FrameAdr(off: int64): TAdr;
190-begin
191- FrameAdr.base := bFrame;
192- FrameAdr.chunk := -1;
193- FrameAdr.off := off;
194- FrameAdr.hi := 0;
195-end;
196-
197-function GlobalAdr(c: longint): TAdr;
198-begin
199- GlobalAdr.base := bGlobal;
200- GlobalAdr.chunk := c;
201- GlobalAdr.off := 0;
202- GlobalAdr.hi := 0;
203-end;
204-
205-{ Where the variable x is, for gen; a slice in registers has two }
206-function AdrOf(const x: TItem): TAdr;
207-begin
208- AdrOf.base := x.base;
209- AdrOf.chunk := x.chunk;
210- AdrOf.off := x.off;
211- AdrOf.hi := 0;
212- if x.base = bReg then AdrOf.hi := x.obj^.reg2;
213-end;
214-
215-{ An item for "found ...": a constant without a type of its own as it
216- is written, so that "found 1.5" says what is wrong; else its type. }
217-function What(const x: TItem): shortstring;
218-begin
219- if (x.mode = mConst) and ((x.typ = tConst) or (x.typ = tRConst)) then What := Source(x.pos)
220- else What := TypeName(x.typ);
221-end;
222-
223-{ Two operands of different types. Numbers convert, so say how. }
224-procedure Mismatch(const x, y: TItem; xt, yt: PType);
225-var msg: shortstring;
226-begin
227- msg := TypeName(xt) + ' and ' + TypeName(yt) + ' are different types';
228- if (IsInt(xt) or (xt^.form = fReal)) and (IsInt(yt) or (yt^.form = fReal))
229- and (xt <> tConst) and (xt <> tRConst) then
230- MarkHelp(Join(x.pos, y.pos), msg, 'convert one to the other''s type, as in ' + TypeName(xt) + '(' + Source(y.pos) + ')')
231- else MarkAt(Join(x.pos, y.pos), msg);
232-end;
233-
234-{ An item that is not a value, by what it is. }
235-procedure NotValue(const x: TItem);
236-begin
237- case x.mode of
238- mType: MarkAt(x.pos, TypeName(x.typ) + ' is a type, not a value');
239- mBuiltin: MarkAt(x.pos, NameOf(x.obj^.name) + ' is a built-in procedure, not a value');
240- mCase: MarkAt(x.pos, NameOf(x.obj^.name) + ' is a case, not a value');
241- mNone:
242- if x.obj <> nil then MarkAt(x.pos, NameOf(x.obj^.name) + ' returns nothing')
243- else MarkAt(x.pos, 'the procedure returns nothing');
244- else MarkAt(x.pos, 'a string can''t be an operand');
245- end;
246-end;
247-
248-procedure MakeItem(var x: TItem; o: PObj);
249-begin
250- FillChar(x, SizeOf(x), 0);
251- x.typ := o^.typ;
252- x.obj := o;
253- case o^.cls of
254- oConst:
255- if o^.typ = tStr then begin
256- x.mode := mStr; x.val := o^.val; x.chunk := o^.chunk
257- end else if o^.typ^.form in [fArray, fRecord] then begin
258- { an array or record constant: a variable in read-only data, not one of
259- the program's, so nothing can change it }
260- x.mode := mVar; x.base := bGlobal; x.chunk := o^.chunk
261- end else begin
262- x.mode := mConst; x.val := o^.val
263- end;
264- oVar: begin
265- x.mode := mVar;
266- x.ro := (o^.lev = 0) and (o^.module <> curModule);
267- x.isVar := not x.ro;
268- if o^.ext then begin
269- PushVar(GlobalAdr(o^.chunk), 8, false, kWord);
270- x.base := bStack;
271- end else if o^.lev = 0 then begin
272- x.base := bGlobal; x.chunk := o^.chunk
273- end else if o^.ind then begin
274- x.base := bSlot; x.chunk := o^.val; x.off := o^.off;
275- end else if o^.reg <> 0 then begin
276- x.base := bReg; x.chunk := o^.reg
277- end else begin
278- x.base := bFrame; x.off := o^.val
279- end;
280- end;
281- oProc: x.mode := mProc;
282- oType: x.mode := mType;
283- oBuiltin: x.mode := mBuiltin;
284- oCase: x.mode := mCase;
285- else Mark(NameOf(o^.name) + ' is not a value');
286- end;
287-end;
288-
289-function ScalarSize(t: PType): longint;
290-begin
291- if t^.form in [fInt, fBool, fEnum, fSet, fReal] then ScalarSize := t^.size
292- else ScalarSize := 8;
293-end;
294-
295-{ The width an operation on t is brought back to, and whether signed }
296-function IntSize(t: PType): longint;
297-begin
298- if t^.form = fInt then IntSize := t^.size else IntSize := 8;
299-end;
300-
301-function Signed(t: PType): boolean;
302-begin
303- Signed := ((t^.form = fInt) and t^.signed) or (t^.form = fConst);
304-end;
305-
306-function Cut(v: int64; t: PType): int64;
307-begin
308- Cut := v;
309- if t^.form <> fInt then exit;
310- case t^.size of
311- 1: if t^.signed then Cut := shortint(v) else Cut := byte(v);
312- 2: if t^.signed then Cut := smallint(v) else Cut := word(v);
313- 4: if t^.signed then Cut := longint(v) else Cut := longword(v);
314- end;
315-end;
316-
317-{ Code computing with a real is noted on its chunk, at the first place,
318- for a target without reals (report 5.1) to refuse if the chunk turns
319- out to be used. A real moved whole, as a record's bytes are copied,
320- needs nothing the target lacks, and isn't noted. }
321-procedure UsesReals(const p: TPos);
322-begin
323- if (codeChunk >= 0) and not chunks^[codeChunk].reals then begin
324- chunks^[codeChunk].reals := true;
325- chunks^[codeChunk].realsAt := p;
326- end;
327-end;
328-
329-{ x, at an address from a pointer, is about to be used: gen tests the
330- address for nil where the machine wouldn't stop at it (report section
331- 10), from its offset to its end. }
332-procedure NilTest(var x: TItem);
333-begin
334- if (x.mode = mVar) and x.deref then CheckNil(x.off + x.typ^.size, x.pos);
335- x.deref := false;
336-end;
337-
338-{ x's value, on top of the stack }
339-procedure Value(var x: TItem);
340-var f: single;
341-begin
342- if x.mode = mCond then begin
343- if (x.fj = NoLabel) and (x.tj = NoLabel) then Compare(x.rel, kWord, x.relSigned)
344- else CondValue(Negated[x.rel], x.relSigned, x.fj, x.tj);
345- x.mode := mStack;
346- exit;
347- end;
348- if x.typ^.form = fReal then UsesReals(x.pos);
349- NilTest(x);
350- case x.mode of
351- mConst:
352- if (x.typ^.form = fError) and (x.val > 0) then PushAdr(GlobalAdr(x.val - 1))
353- else if IsF32(x.typ) then begin
354- f := RealOf(x);
355- PushConst(kF32, PLongword(@f)^);
356- end else PushConst(KindOf(x.typ), x.val);
357- mVar: begin
358- if not IsScalar(x.typ) then MarkAt(x.pos, 'expected a single value, found ' + What(x));
359- PushVar(AdrOf(x), ScalarSize(x.typ), (x.typ^.form = fInt) and x.typ^.signed, KindOf(x.typ));
360- end;
361- mStack: ;
362- mProc: begin
363- if x.obj^.isCode and (x.obj^.typ^.base <> nil) and x.obj^.typ^.base^.tuple then
364- MarkAt(x.pos, 'a code procedure with two results can only be called');
365- PushProc(x.obj^.chunk, x.obj^.ext);
366- end;
367- else NotValue(x);
368- end;
369- x.mode := mStack;
370-end;
371-
372-{ The address of the variable or string x, on top of the stack }
373-procedure Address(var x: TItem);
374-begin
375- NilTest(x);
376- if (x.mode = mVar) and (x.base = bReg) then begin
377- { its address is wanted after all: the procedure is compiled again
378- with the variable in memory; till then, this code is thrown away }
379- x.obj^.reg := 0;
380- x.obj^.reg2 := 0;
381- demoted := true;
382- x.base := bFrame;
383- x.off := x.obj^.val;
384- end;
385- if x.mode = mStr then PushAdr(GlobalAdr(x.chunk))
386- else if x.mode = mVar then begin
387- PushAdr(AdrOf(x));
388- x.base := bStack; x.off := 0;
389- end else MarkAt(x.pos, 'expected a variable');
390-end;
391-
392-{ x isn't wanted: what it has on the stack is dropped }
393-procedure Discard(const x: TItem);
394-var y: TItem;
395-begin
396- if x.mode = mCond then begin y := x; Value(y); Drop; exit end;
397- if (x.mode = mStack) or ((x.mode = mVar) and (x.base = bStack)) then Drop;
398- if x.mode = mWords then begin Drop; Drop end;
399-end;
400-
401-{ Frames }
402-
403-procedure TempItem(var x: TItem; t: PType; off: int64);
404-var p: TPos;
405-begin
406- p := x.pos;
407- FillChar(x, SizeOf(x), 0);
408- x.pos := p;
409- x.mode := mVar; x.typ := t; x.base := bFrame; x.off := off;
410-end;
411-
412-function ToSlot(var x: TItem): int64;
413-var s: int64;
414-begin
415- Value(x);
416- s := AllocTemp(8, 8);
417- PopVar(FrameAdr(s), 8);
418- ToSlot := s;
419-end;
420-
421-{ Copying }
422-
423-{ x, copied to a temporary }
424-procedure CopyToTemp(var x: TItem);
425-var t: int64; f, g: PObj; a: TAdr;
426-begin
427- if x.vol then MarkAt(x.pos, 'can''t copy through a volatile pointer');
428- t := AllocTemp(x.typ^.size, x.typ^.align);
429- if (x.mode = mVar) and (x.base = bReg) then begin
430- { a slice in registers, which has no address: its words stored }
431- a := AdrOf(x);
432- PushVar(a, 8, false, kWord);
433- PopVar(FrameAdr(t), 8);
434- a.off := 8;
435- PushVar(a, 8, false, kWord);
436- PopVar(FrameAdr(t + 8), 8);
437- TempItem(x, x.typ, t);
438- exit;
439- end;
440- if x.mode = mWords then begin
441- { the second result is on top, so it is popped first }
442- f := x.typ^.fields; g := f^.next;
443- PopVar(FrameAdr(t + g^.val), ScalarSize(g^.typ));
444- PopVar(FrameAdr(t + f^.val), ScalarSize(f^.typ));
445- TempItem(x, x.typ, t);
446- exit;
447- end;
448- Address(x);
449- CopyTo(FrameAdr(t), x.typ^.size);
450- TempItem(x, x.typ, t);
451-end;
452-
453-{ A slice made from an address on the stack and a length. }
454-procedure SliceOf(var x: TItem; t: PType; len: int64);
455-var s: int64;
456-begin
457- s := AllocTemp(16, 8);
458- PopVar(FrameAdr(s), 8);
459- PushConst(kWord, len);
460- PopVar(FrameAdr(s + 8), 8);
461- TempItem(x, t, s);
462-end;
463-
464-{ An INT goes silently into an I64, and a UINT into a U64, losing
465- nothing on any target (report section 5.10). }
466-function Widens(s, t: PType): boolean;
467-begin
468- Widens := ((s = tInt) and Same(t, tI64)) or ((s = tUInt) and Same(t, tU64));
469-end;
470-
471-{ Another module's exported variable can be read, not changed, nor
472- handed to anything that could change it (report section 3). }
473-procedure NotReadOnly(const x: TItem);
474-begin
475- if x.ro then MarkAt(x.pos, Source(x.pos) + ' is ' + NameOf(x.obj^.module^.name) + '''s, and can''t be changed outside it');
476-end;
477-
478-var
479- passing: PObj; { the parameter the argument at passingAt goes to }
480- passingAt: TPos;
481-
482-{ An error in x's type; if x is an argument, a note at the parameter
483- it goes to. }
484-procedure Mismatch(const x: TItem; const msg: shortstring);
485-begin
486- Error(x.pos, msg);
487- if (passing <> nil) and (x.pos.f = passingAt.f) and (x.pos.a = passingAt.a) and (x.pos.b = passingAt.b) then
488- Note(passing^.pos, 'it goes to ' + NameOf(passing^.name) + ', declared here');
489- Fail;
490-end;
491-
492-procedure Coerce(var x: TItem; t: PType);
493-var s: PType; tmp: int64;
494-begin
495- if x.mode = mCond then Value(x);
496- s := x.typ;
497- if x.mode = mStr then begin
498- if (t^.form = fSlice) and (t^.base = tU8) then begin
499- Address(x); SliceOf(x, t, x.val)
500- end else if (t^.form = fPtr) and (t^.base = tU8) then begin
501- Address(x); x.mode := mStack; x.typ := t
502- end else if (t^.form = fArray) and (t^.base = tU8) and (t^.len >= x.val) then begin
503- tmp := AllocTemp(t^.size, 1);
504- Address(x);
505- CopyTo(FrameAdr(tmp), x.val);
506- if t^.len > x.val then ZeroVar(FrameAdr(tmp + x.val), t^.len - x.val);
507- TempItem(x, t, tmp);
508- end else Mismatch(x, 'can''t use a string as ' + TypeName(t));
509- exit;
510- end;
511- if x.mode in [mType, mBuiltin, mNone, mCase] then NotValue(x);
512- if Same(s, t) then exit;
513- if Widens(s, t) then x.typ := t { the same bits, on a 64-bit target }
514- else if (s = tRConst) and (t^.form = fReal) then RealTo(x, t)
515- else if (s^.form = fConst) and (t^.form = fInt) then begin
516- if (x.mode = mConst) and not Fits(x.val, t) then MarkAt(x.pos, IntStr(x.val) + ' doesn''t fit ' + TypeName(t));
517- x.typ := t;
518- end else if (s^.form = fNil) and (t^.form in [fPtr, fProc, fError]) then
519- x.typ := t
520- else if (s^.form = fPtr) and (t^.form = fPtr) and t^.vol and not s^.vol
521- and Same(s^.base, t^.base) then
522- x.typ := t
523- else if (s^.form = fArray) and (t^.form = fSlice) and Same(s^.base, t^.base) then begin
524- NotReadOnly(x);
525- if x.vol then MarkAt(x.pos, 'can''t make a slice through a volatile pointer');
526- if x.odd then MarkAt(x.pos, 'can''t make a slice of a field of a packed record');
527- Address(x);
528- SliceOf(x, t, s^.len);
529- end else if (x.mode = mProc) and (t^.form <> fProc) and (s^.base = nil) then
530- MarkAt(x.pos, Source(x.pos) + ' is a procedure, and returns nothing')
531- else if (x.mode = mProc) and (t^.form <> fProc) then
532- MarkHelp(x.pos, 'can''t use ' + TypeName(s) + ' as ' + TypeName(t), 'to call it, write ' + Source(x.pos) + '()')
533- else
534- Mismatch(x, 'can''t use ' + TypeName(s) + ' as ' + TypeName(t));
535-end;
536-
537-{ Coerce where the types must be the same, as in a for loop, INC and
538- several results, which don't widen an INT to an I64 (report sections
539- 5.10, 6.1 and 7.2); help, if not empty, says why. }
540-procedure CoerceExact(var x: TItem; t: PType; const help: shortstring);
541-var h: shortstring;
542-begin
543- if Widens(x.typ, t) then begin
544- h := help;
545- if h = '' then h := 'they don''t mix here: write ' + TypeName(t) + '(' + Source(x.pos) + ')';
546- MarkHelp(x.pos, 'expected ' + TypeName(t) + ', found ' + What(x), h);
547- end;
548- Coerce(x, t);
549-end;
550-
551-{ dst := src. The address of dst, if it has to be computed, is on the
552- stack already, under src's. }
553-procedure Assign(var dst, src: TItem);
554-begin
555- Coerce(src, dst.typ);
556- if IsScalar(dst.typ) then begin
557- Value(src);
558- PopVar(AdrOf(dst), ScalarSize(dst.typ));
559- end else begin
560- if dst.vol or src.vol then MarkAt(src.pos, 'can''t copy through a volatile pointer');
561- if (src.mode = mVar) and (src.base = bReg) then CopyToTemp(src); { a slice in registers }
562- Address(src);
563- if dst.base = bStack then CopyBlock(dst.typ^.size, dst.off)
564- else CopyTo(AdrOf(dst), dst.typ^.size);
565- end;
566-end;
567-
568-{ t's name, ending in a zero byte, for Rt.fail }
569-function NameChunk(t: PType): longint;
570-var s: shortstring; c: longint;
571-begin
572- s := TypeName(t) + #0;
573- c := NewChunk(secRodata, -1, -1);
574- SetData(c, @s[1], length(s), 1);
575- NameChunk := c;
576-end;
577-
578-{ Selectors }
579-
580-procedure Deref(var x: TItem);
581-var t: PType;
582-begin
583- t := x.typ;
584- if t^.form <> fPtr then MarkAt(x.pos, 'expected a pointer, found ' + TypeName(t));
585- if t^.base = nil then MarkAt(x.pos, TypeName(t) + ' points to a type never declared');
586- Value(x);
587- x.mode := mVar; x.base := bStack; x.off := 0; x.deref := true;
588- x.typ := t^.base; x.vol := t^.vol; x.isVar := true; x.odd := false; x.ro := false;
589-end;
590-
591-{ A field of a packed record, of more than one byte's alignment, may
592- sit anywhere; it is read and written, but has no address and no
593- volatile access, which a machine that can't reach a misaligned word
594- couldn't make one access (report section 5.5). }
595-procedure Field(var x: TItem; f: PObj);
596-begin
597- if x.typ^.packd and (f^.typ^.align > 1) then begin
598- if x.vol then MarkAt(x.pos, 'a field of a packed record can''t be volatile');
599- x.odd := true;
600- end;
601- x.off := x.off + f^.val;
602- x.typ := f^.typ;
603-end;
604-
605-procedure IndexPrep(var x: TItem);
606-begin
607- NilTest(x);
608- if x.mode = mStr then Coerce(x, tBytes);
609- if (x.typ^.form = fPtr) and (x.typ^.base^.form = fArray) then
610- MarkAt(x.pos, 'a pointer to an array is indexed as p^[i]');
611- if x.typ^.form = fPtr then Value(x)
612- else if not ((x.mode = mVar) and (x.typ^.form in [fArray, fSlice])) then
613- MarkAt(x.pos, 'expected an array, a slice or a pointer, found ' + What(x));
614-end;
615-
616-{ The index on top, times the size of an element }
617-procedure ScaleBy(s: int64);
618-begin
619- if s <> 1 then begin
620- PushConst(kWord, s);
621- gen.Op(sTimes, kWord, 8, true);
622- end;
623-end;
624-
625-procedure Index(var x, y: TItem);
626-var t: PType; s: int64;
627-begin
628- t := x.typ;
629- s := t^.base^.size;
630- if not IsInt(y.typ) then MarkAt(y.pos, 'an index is an integer, found ' + What(y));
631- if t^.form = fPtr then begin
632- Value(y);
633- ScaleBy(s);
634- gen.Op(sPlus, kWord, 8, false);
635- x.mode := mVar; x.base := bStack; x.off := 0;
636- x.vol := t^.vol; x.isVar := true; x.odd := false; x.ro := false;
637- end else if (t^.form = fArray) and (y.mode = mConst) then begin
638- if (y.val < 0) or (y.val >= t^.len) then MarkAt(y.pos, 'index ' + IntStr(y.val) + ' is out of range for a length of ' + IntStr(t^.len));
639- x.off := x.off + y.val * s;
640- end else if t^.form = fArray then begin
641- Value(y);
642- if checks then CheckIndex(t^.len, y.pos);
643- if x.base = bStack then begin ScaleBy(s); gen.Op(sPlus, kWord, 8, false) end
644- else begin IndexArray(AdrOf(x), s); x.off := 0 end;
645- x.base := bStack;
646- end else begin
647- Value(y);
648- IndexSlice(AdrOf(x), s, checks, y.pos);
649- x.base := bStack; x.off := 0; x.isVar := true; x.vol := false; x.ro := false;
650- end;
651- x.typ := t^.base;
652-end;
653-
654-procedure SliceLo(var lo: TItem);
655-begin
656- if not IsInt(lo.typ) then MarkAt(lo.pos, 'an index is an integer, found ' + What(lo));
657- Value(lo);
658-end;
659-
660-procedure Slice(var x, lo, hi: TItem);
661-var t, st: PType; tmp: int64;
662-begin
663- t := x.typ;
664- if not IsInt(hi.typ) then MarkAt(hi.pos, 'an index is an integer, found ' + What(hi));
665- if x.vol then MarkAt(x.pos, 'can''t make a slice through a volatile pointer');
666- if x.odd then MarkAt(x.pos, 'can''t make a slice of a field of a packed record');
667- if t^.form = fArray then NotReadOnly(x);
668- Value(hi);
669- tmp := AllocTemp(16, 8);
670- if t^.form = fPtr then SlicePtr(t^.base^.size, tmp, checks, lo.pos)
671- else gen.Slice(AdrOf(x), t^.form = fArray, t^.len, t^.base^.size, tmp, checks, lo.pos);
672- st := NewType(fSlice, 16, 8);
673- st^.base := t^.base;
674- TempItem(x, st, tmp);
675-end;
676-
677-{ Operators }
678-
679-procedure Neg(var x: TItem);
680-begin
681- if x.typ^.form = fReal then begin
682- if x.mode = mConst then x.val := x.val xor low(int64)
683- else begin Value(x); gen.Neg(KindOf(x.typ), 8, false) end;
684- end else if IsInt(x.typ) then begin
685- if (x.mode = mConst) and (x.typ^.form = fConst) and (x.val = low(int64)) then
686- MarkAt(x.pos, 'the constant is too big for I64')
687- else if x.mode = mConst then x.val := Cut(-x.val, x.typ)
688- else begin Value(x); gen.Neg(kWord, IntSize(x.typ), Signed(x.typ)) end;
689- end else MarkAt(x.pos, 'can''t negate ' + TypeName(x.typ));
690-end;
691-
692-procedure NotOp(var x: TItem);
693-var L: longint;
694-begin
695- if IsInt(x.typ) then MarkHelp(x.pos, '"not" needs a BOOL, found ' + What(x), 'the bits of an integer flip with ~');
696- if x.typ^.form <> fBool then MarkAt(x.pos, '"not" needs a BOOL, found ' + What(x));
697- if x.mode = mConst then x.val := 1 - x.val
698- else if x.mode = mCond then begin
699- x.rel := Negated[x.rel];
700- L := x.fj; x.fj := x.tj; x.tj := L;
701- end
702- else begin Value(x); NotBool end;
703-end;
704-
705-procedure Complement(var x: TItem);
706-begin
707- if x.typ^.form = fBool then MarkHelp(x.pos, '"~" needs an integer, found ' + What(x), 'a BOOL is negated with not');
708- if not IsInt(x.typ) then MarkAt(x.pos, '"~" needs an integer, found ' + What(x));
709- if x.mode = mConst then x.val := Cut(not x.val, x.typ)
710- else begin Value(x); gen.Complement(IntSize(x.typ), Signed(x.typ)) end;
711-end;
712-
713-{ Arrays, slices and strings, which = and # compare element by element }
714-function IsSeq(t: PType): boolean;
715-begin
716- IsSeq := t^.form in [fStr, fArray, fSlice];
717-end;
718-
719-function ElemOf(t: PType): PType;
720-begin
721- if t^.form = fStr then ElemOf := tU8 else ElemOf := t^.base;
722-end;
723-
724-{ An array, slice or string as a slice in a temporary, for comparing. }
725-procedure SeqSlice(var x: TItem);
726-var t: PType;
727-begin
728- t := NewType(fSlice, 16, 8);
729- t^.base := ElemOf(x.typ);
730- if x.typ^.form = fSlice then begin
731- x.typ := t; CopyToTemp(x)
732- end else begin
733- if x.mode = mStr then begin Address(x); SliceOf(x, t, x.val) end
734- else begin
735- if x.vol then MarkAt(x.pos, 'can''t compare through a volatile pointer');
736- Address(x); SliceOf(x, t, x.typ^.len)
737- end;
738- end;
739-end;
740-
741-{ x, a BOOL, as a condition: a value compared with 0 if it isn't one }
742-procedure MakeCond(var x: TItem);
743-begin
744- if x.mode = mCond then exit;
745- Value(x);
746- PushConst(kWord, 0);
747- x.mode := mCond;
748- x.rel := sNeq;
749- x.relSigned := false;
750- x.fj := NoLabel;
751- x.tj := NoLabel;
752-end;
753-
754-procedure Op1(op: TSym; var x: TItem; var L: longint);
755-begin
756- L := NoLabel;
757- if (op in [sAnd, sOr]) and (x.typ^.form = fBool) then begin
758- if x.mode = mConst then exit; { folded by Op2 }
759- MakeCond(x);
760- if op = sAnd then begin
761- JumpOut(Negated[x.rel], x.relSigned, x.fj);
762- Fix(x.tj);
763- x.tj := NoLabel;
764- end else begin
765- JumpOut(x.rel, x.relSigned, x.tj);
766- Fix(x.fj);
767- x.fj := NoLabel;
768- end;
769- end else if (op in [sEql, sNeq]) and IsSeq(x.typ) then
770- SeqSlice(x)
771- else if (op = sPlus) and (x.mode = mStr) then
772- { two string constants to be joined: nothing to compute }
773- else if (op = sPlus) and IsSeq(x.typ) then
774- MarkHelp(x.pos, '+ doesn''t join ' + What(x), 'strings are joined in a Buf: Buf.str(b, s)')
775- else if x.mode in [mType, mBuiltin, mNone, mCase, mStr] then
776- NotValue(x)
777- else if x.mode <> mConst then
778- Value(x);
779-end;
780-
781-function Log2(v: int64): longint;
782-var n: longint;
783-begin
784- n := 0;
785- while (v > 1) and (v and 1 = 0) do begin v := v shr 1; inc(n) end;
786- if v <> 1 then n := -1;
787- Log2 := n;
788-end;
789-
790-{ Whether a op b, for + - *, overflows an I64: an untyped constant
791- doesn't wrap, it is an error (report section 4). }
792-function Overflows(op: TSym; a, b: int64): boolean;
793-begin
794- case op of
795- sPlus: Overflows := ((b > 0) and (a > high(int64) - b)) or ((b < 0) and (a < low(int64) - b));
796- sMinus: Overflows := ((b < 0) and (a > high(int64) + b)) or ((b > 0) and (a < low(int64) + b));
797- sTimes:
798- if (a = 0) or (b = 0) then Overflows := false
799- else if a = -1 then Overflows := b = low(int64)
800- else if b = -1 then Overflows := a = low(int64)
801- else Overflows := (a * b) div b <> a;
802- else Overflows := false;
803- end;
804-end;
805-
806-{ A type's width in bits; an untyped constant's is an I64's }
807-function Bits(t: PType): longint;
808-begin
809- Bits := t^.size * 8;
810-end;
811-
812-function FoldInt(op: TSym; a, b: int64; t: PType; const p: TPos): int64;
813-var u: boolean;
814-begin
815- u := (t^.form = fInt) and not t^.signed;
816- if (t^.form = fConst) and Overflows(op, a, b) then MarkAt(p, 'the constant is too big for I64');
817- case op of
818- sPlus: FoldInt := a + b;
819- sMinus: FoldInt := a - b;
820- sTimes: FoldInt := a * b;
821- sDiv, sMod: begin
822- if b = 0 then MarkAt(p, 'division by zero');
823- if u then begin
824- if op = sDiv then FoldInt := int64(qword(a) div qword(b))
825- else FoldInt := int64(qword(a) mod qword(b));
826- end else if (b = -1) and (a = int64(-1) shl (Bits(t) - 1)) then MarkAt(p, 'division overflows')
827- else if op = sDiv then FoldInt := a div b
828- else FoldInt := a mod b;
829- end;
830- sAmp: FoldInt := a and b;
831- sBar: FoldInt := a or b;
832- sXor: FoldInt := a xor b;
833- sShl: FoldInt := a shl (b and (Bits(t) - 1));
834- sShr: if u then FoldInt := int64(qword(a) shr (b and (Bits(t) - 1)))
835- else FoldInt := SarInt64(a, b and (Bits(t) - 1));
836- sEql: FoldInt := ord(a = b);
837- sNeq: FoldInt := ord(a <> b);
838- sLss: if u then FoldInt := ord(qword(a) < qword(b)) else FoldInt := ord(a < b);
839- sLeq: if u then FoldInt := ord(qword(a) <= qword(b)) else FoldInt := ord(a <= b);
840- sGtr: if u then FoldInt := ord(qword(a) > qword(b)) else FoldInt := ord(a > b);
841- sGeq: if u then FoldInt := ord(qword(a) >= qword(b)) else FoldInt := ord(a >= b);
842- else MarkAt(p, 'bad operator'); FoldInt := 0;
843- end;
844-end;
845-
846-{ Folds x op y, of the real type t: an F32 rounded at each step, as
847- the machine would. }
848-function FoldReal(op: TSym; const x, y: TItem; t: PType; var r: TItem): boolean;
849-var a, b: double;
850-begin
851- a := RealOf(x); b := RealOf(y);
852- FoldReal := true;
853- case op of
854- sPlus: MakeReal(r, a + b);
855- sMinus: MakeReal(r, a - b);
856- sTimes: MakeReal(r, a * b);
857- sSlash: MakeReal(r, a / b);
858- sEql: MakeConst(r, tBool, ord(a = b));
859- sNeq: MakeConst(r, tBool, ord(a <> b));
860- sLss: MakeConst(r, tBool, ord(a < b));
861- sLeq: MakeConst(r, tBool, ord(a <= b));
862- sGtr: MakeConst(r, tBool, ord(a > b));
863- sGeq: MakeConst(r, tBool, ord(a >= b));
864- else FoldReal := false;
865- end;
866- if r.typ^.form = fReal then RealTo(r, t);
867-end;
868-
869-{ and, or and not are for BOOLs; &, |, xor and ~ for the bits of
870- integers: x is the wrong kind for op, and the message names the
871- operator it may have meant }
872-procedure WrongLogic(op: TSym; var x: TItem);
873-const Bits = 'the bits of integers take ';
874-begin
875- case op of
876- sAnd: if IsInt(x.typ) then MarkHelp(x.pos, '"and" needs BOOLs, found ' + What(x), Bits + '&');
877- sOr: if IsInt(x.typ) then MarkHelp(x.pos, '"or" needs BOOLs, found ' + What(x), Bits + '|');
878- sAmp: MarkHelp(x.pos, '"&" needs integers, found ' + What(x), 'BOOLs take and');
879- sBar: MarkHelp(x.pos, '"|" needs integers, found ' + What(x), 'BOOLs take or');
880- sXor: MarkHelp(x.pos, '"xor" needs integers, found ' + What(x), 'BOOLs that differ are #');
881- end;
882- MarkAt(x.pos, SymText(op) + ' needs BOOLs, found ' + What(x));
883-end;
884-
885-{ x + y, of two string constants: one string, in a chunk of its own
886- (report section 4) }
887-procedure JoinStr(var x, y: TItem);
888-var p: PBytes; c: longint;
889-begin
890- if y.mode <> mStr then MarkAt(y.pos, '"+" joins two strings, found ' + What(y));
891- p := GetMem(x.val + y.val + 1);
892- Move(rodata^[chunks^[x.chunk].start], p^[0], x.val);
893- Move(rodata^[chunks^[y.chunk].start], p^[x.val], y.val + 1);
894- c := NewChunk(secRodata, -1, -1);
895- SetData(c, p, x.val + y.val + 1, 1);
896- FreeMem(p);
897- x.chunk := c;
898- x.val := x.val + y.val;
899-end;
900-
901-{ A set's operations, as operations on its bits: the two values on top }
902-procedure SetOp(op: TSym);
903-begin
904- case op of
905- sPlus: gen.Op(sBar, kWord, 8, false);
906- sTimes: gen.Op(sAmp, kWord, 8, false);
907- sMinus: begin gen.Complement(8, false); gen.Op(sAmp, kWord, 8, false) end;
908- sLeq, sGeq: begin
909- { x <= y has no bit of x outside y }
910- if op = sGeq then Swap;
911- gen.Complement(8, false);
912- gen.Op(sAmp, kWord, 8, false);
913- PushConst(kWord, 0);
914- Compare(sEql, kWord, false);
915- end;
916- sIn: begin
917- Swap;
918- gen.Op(sShr, kWord, 8, false);
919- PushConst(kWord, 1);
920- gen.Op(sAmp, kWord, 8, false);
921- end;
922- else Compare(op, kWord, false);
923- end;
924-end;
925-
926-procedure Op2(op: TSym; var x, y: TItem; L: longint);
927-const
928- Rel = [sEql, sNeq, sLss, sLeq, sGtr, sGeq];
929-var
930- xt, yt, t, e: PType; r: TItem; scale: longint; isPtr: boolean; a, b: int64;
931-begin
932- xt := x.typ; yt := y.typ;
933- if y.mode in [mType, mBuiltin, mNone, mCase] then NotValue(y);
934- if (op = sPlus) and (x.mode = mStr) then begin JoinStr(x, y); exit end;
935-
936- if op in [sAnd, sOr] then begin
937- if xt^.form <> fBool then WrongLogic(op, x);
938- if yt^.form <> fBool then WrongLogic(op, y);
939- if (x.mode = mConst) and (y.mode = mConst) then begin
940- if op = sAnd then x.val := x.val and y.val else x.val := x.val or y.val;
941- end else if x.mode = mConst then begin
942- { true and y, false or y: y; else x, y computed and dropped }
943- if (x.val = 1) = (op = sAnd) then x := y
944- else Discard(y);
945- end else begin
946- MakeCond(y);
947- if op = sAnd then begin x.fj := JoinJumps(x.fj, y.fj); x.tj := y.tj end
948- else begin x.tj := JoinJumps(x.tj, y.tj); x.fj := y.fj end;
949- x.rel := y.rel;
950- x.relSigned := y.relSigned;
951- end;
952- exit;
953- end;
954-
955- if (op in [sAmp, sBar, sXor]) and (xt^.form = fBool) then WrongLogic(op, x);
956- if (op in [sAmp, sBar, sXor]) and (yt^.form = fBool) then WrongLogic(op, y);
957-
958- { the lengths, then the bytes, LEN * SIZE(T) of them: the elements
959- are of types whose bytes say all there is to their values }
960- if (op in [sEql, sNeq]) and IsSeq(xt) then begin
961- e := ElemOf(xt);
962- if not IsSeq(yt) then
963- MarkAt(Join(x.pos, y.pos), 'can''t compare an array with ' + TypeName(yt))
964- else if not Same(e, ElemOf(yt)) then
965- MarkAt(Join(x.pos, y.pos), 'can''t compare an array of ' + TypeName(e) + ' with one of ' + TypeName(ElemOf(yt)));
966- if e^.form = fReal then
967- MarkHelp(Join(x.pos, y.pos), 'can''t compare arrays of reals with ' + SymText(op),
968- '-0.0 = 0.0 and a NaN equals nothing, though their bytes say otherwise: write a loop')
969- else if not (e^.form in [fInt, fBool, fEnum, fSet, fPtr]) then
970- MarkHelp(Join(x.pos, y.pos), 'can''t compare arrays of ' + TypeName(e) + ' with ' + SymText(op), 'write a loop');
971- SeqSlice(y);
972- CompareSeq(x.off, y.off, Log2(e^.size), op = sEql);
973- MakeConst(x, tBool, 0);
974- x.mode := mStack;
975- exit;
976- end;
977-
978- { the type of the result, and the checks }
979- t := nil; scale := 1; isPtr := false;
980- if IsInt(xt) and IsInt(yt) then begin
981- if op = sSlash then MarkHelp(Join(x.pos, y.pos), '"/" divides reals, not integers', 'to divide integers, write ' + Source(x.pos) + ' div ' + Source(y.pos));
982- if op in [sShl, sShr] then begin
983- if xt^.form = fConst then t := tConst else t := xt
984- end else if (xt^.form = fConst) and (yt^.form = fConst) then t := tConst
985- else if xt^.form = fConst then begin
986- if (x.mode = mConst) and not Fits(x.val, yt) then MarkAt(x.pos, IntStr(x.val) + ' doesn''t fit ' + TypeName(yt));
987- t := yt
988- end else if yt^.form = fConst then begin
989- if (y.mode = mConst) and not Fits(y.val, xt) then MarkAt(y.pos, IntStr(y.val) + ' doesn''t fit ' + TypeName(xt));
990- t := xt
991- end else if Same(xt, yt) then t := xt
992- else Mismatch(x, y, xt, yt);
993- if not (op in Rel + [sPlus, sMinus, sTimes, sDiv, sMod, sAmp, sBar, sXor, sShl, sShr]) then
994- MarkAt(Join(x.pos, y.pos), SymText(op) + ' doesn''t apply to ' + TypeName(t));
995- end else if (xt^.form = fReal) and (yt^.form = fReal) then begin
996- if not (op in Rel + [sPlus, sMinus, sTimes, sSlash]) then MarkAt(Join(x.pos, y.pos), SymText(op) + ' doesn''t apply to ' + TypeName(xt));
997- if xt = tRConst then t := yt
998- else if (yt = tRConst) or Same(xt, yt) then t := xt
999- else Mismatch(x, y, xt, yt);
1000- if (x.mode = mConst) and (x.typ <> t) then RealTo(x, t);
1001- if (y.mode = mConst) and (y.typ <> t) then RealTo(y, t);
1002- end else if (xt^.form = fBool) and (yt^.form = fBool) then begin
1003- if not (op in [sEql, sNeq]) then MarkAt(Join(x.pos, y.pos), SymText(op) + ' doesn''t apply to ' + TypeName(xt));
1004- t := tBool;
1005- end else if (xt^.form = fPtr) and IsInt(yt) and (op in [sPlus, sMinus]) then begin
1006- t := xt; scale := xt^.base^.size; isPtr := true;
1007- if y.mode = mConst then y.typ := tInt;
1008- end else if (xt^.form = fPtr) and (yt^.form = fPtr) and (op = sMinus) then begin
1009- if not Same(xt, yt) then Mismatch(x, y, xt, yt);
1010- t := tInt; scale := xt^.base^.size; isPtr := true;
1011- end else if (xt^.form in [fPtr, fProc, fNil, fError]) and (yt^.form in [fPtr, fProc, fNil, fError]) then begin
1012- if not (op in Rel) then MarkAt(Join(x.pos, y.pos), SymText(op) + ' doesn''t apply to ' + TypeName(xt));
1013- if (xt^.form in [fProc, fError]) or (yt^.form in [fProc, fError]) then
1014- if not (op in [sEql, sNeq]) then MarkAt(Join(x.pos, y.pos), SymText(op) + ' doesn''t apply to ' + TypeName(xt));
1015- if (xt^.form <> fNil) and (yt^.form <> fNil) and not Same(xt, yt) then
1016- if not ((xt^.form = fPtr) and (yt^.form = fPtr) and Same(xt^.base, yt^.base)) then
1017- Mismatch(x, y, xt, yt);
1018- t := tU64;
1019- end else if (xt^.form = fEnum) and Same(xt, yt) then begin
1020- if not (op in Rel) then MarkAt(Join(x.pos, y.pos), SymText(op) + ' doesn''t apply to ' + TypeName(xt));
1021- t := xt;
1022- end else if (xt^.form = fSet) and Same(xt, yt) then begin
1023- if not (op in [sPlus, sTimes, sMinus, sEql, sNeq, sLeq, sGeq]) then MarkAt(Join(x.pos, y.pos), SymText(op) + ' doesn''t apply to ' + TypeName(xt));
1024- t := xt;
1025- end else if (op = sIn) and (yt^.form = fSet) and Same(xt, yt^.base) then
1026- t := yt
1027- else
1028- Mismatch(x, y, xt, yt);
1029-
1030- { constants }
1031- if (x.mode = mConst) and (y.mode = mConst) and not isPtr then begin
1032- if t^.form = fReal then begin
1033- if not FoldReal(op, x, y, t, r) then MarkAt(Join(x.pos, y.pos), SymText(op) + ' doesn''t apply to ' + TypeName(xt));
1034- x := r;
1035- end else if t^.form = fSet then begin
1036- a := x.val; b := y.val;
1037- case op of
1038- sPlus: MakeConst(x, t, a or b);
1039- sTimes: MakeConst(x, t, a and b);
1040- sMinus: MakeConst(x, t, a and not b);
1041- sIn: MakeConst(x, tBool, (b shr a) and 1);
1042- sLeq: MakeConst(x, tBool, ord(a and not b = 0));
1043- sGeq: MakeConst(x, tBool, ord(b and not a = 0));
1044- else MakeConst(x, tBool, ord((a = b) = (op = sEql)));
1045- end;
1046- end else if op in Rel then
1047- MakeConst(x, tBool, FoldInt(op, x.val, y.val, t, Join(x.pos, y.pos)))
1048- else
1049- MakeConst(x, t, Cut(FoldInt(op, x.val, y.val, t, Join(x.pos, y.pos)), t));
1050- exit;
1051- end;
1052-
1053- { x and y on the stack, x under y; a constant x goes on after y, and
1054- is left on top where the order doesn't matter, as gen takes a
1055- constant best on the right: 0.25 * e is mulsd xmm8, [0.25] }
1056- Value(y);
1057- if x.mode = mConst then begin
1058- Value(x);
1059- if not (op in [sPlus, sTimes, sAmp, sBar, sXor]) or isPtr then Swap;
1060- end;
1061-
1062- if t^.form = fReal then begin
1063- if op in Rel then Compare(op, KindOf(t), false) else gen.Op(op, KindOf(t), 8, false)
1064- end else if t^.form = fSet then
1065- SetOp(op)
1066- else if op in Rel then begin
1067- x.mode := mCond;
1068- x.rel := op;
1069- x.relSigned := Signed(t);
1070- x.fj := NoLabel;
1071- x.tj := NoLabel;
1072- x.typ := tBool;
1073- exit;
1074- end
1075- else if isPtr then begin
1076- if t <> tInt then ScaleBy(scale);
1077- gen.Op(op, kWord, 8, false);
1078- if (t = tInt) and (scale <> 1) then begin
1079- PushConst(kWord, scale);
1080- gen.Op(sDiv, kWord, 8, true);
1081- end;
1082- end else
1083- gen.Op(op, KindOf(t), IntSize(t), Signed(t));
1084- x.mode := mStack;
1085- if op in Rel + [sIn] then x.typ := tBool else x.typ := t;
1086-end;
1087-
1088-{ INT and UINT, the integers as big as an address, through which
1089- integers and pointers convert (report section 6.7) }
1090-function IsWord(t: PType): boolean;
1091-begin
1092- IsWord := Same(t, tInt) or Same(t, tUInt);
1093-end;
1094-
1095-procedure Convert(var x: TItem; t: PType);
1096-var s: PType; r: double;
1097-begin
1098- s := x.typ;
1099- if x.mode in [mType, mBuiltin, mNone, mCase, mStr] then begin
1100- if x.mode = mStr then MarkAt(x.pos, 'can''t convert a string');
1101- NotValue(x);
1102- end;
1103- if Same(s, t) then exit;
1104- if (IsInt(s) or (s^.form in [fEnum, fSet])) and (t^.form = fInt) then begin
1105- if x.mode = mConst then x.val := Cut(x.val, t)
1106- else begin Value(x); Narrow(t^.size, t^.signed) end;
1107- end else if IsInt(s) and (t^.form = fEnum) then begin
1108- if x.mode = mConst then begin
1109- if (x.val < 0) or (x.val >= t^.len) then MarkAt(x.pos, IntStr(x.val) + ' isn''t a position of ' + TypeName(t))
1110- end else begin Value(x); CheckEnum(t^.len, NameChunk(t), x.pos) end;
1111- end else if IsInt(s) and (t^.form = fSet) then begin
1112- if x.mode = mConst then begin
1113- if t^.len < 64 then x.val := x.val and ((int64(1) shl t^.len) - 1)
1114- end else begin
1115- Value(x);
1116- if t^.len < 64 then begin
1117- PushConst(kWord, (int64(1) shl t^.len) - 1);
1118- gen.Op(sAmp, kWord, 8, false);
1119- end;
1120- end;
1121- end else if IsInt(s) and (t^.form = fReal) then begin
1122- if x.mode = mConst then begin
1123- if (s^.form = fInt) and not s^.signed then r := qword(x.val) else r := x.val;
1124- MakeReal(x, r);
1125- RealTo(x, t);
1126- end else begin
1127- Value(x);
1128- IntToReal(KindOf(t), (s^.form = fInt) and not s^.signed and (s^.size = 8));
1129- end;
1130- end else if (s^.form = fReal) and (t^.form = fReal) then begin
1131- { F32 to F64, F64 to F32, or a real constant to either }
1132- if x.mode = mConst then RealTo(x, t)
1133- else begin Value(x); RealToReal(KindOf(s)) end;
1134- end else if (s^.form = fReal) and (t^.form = fInt) then begin
1135- if x.mode = mConst then begin
1136- r := RealOf(x);
1137- { NaN or out of range folds to low(int64), the "integer
1138- indefinite" cvttsd2si gives at run time }
1139- if (r <> r) or (r >= 9.2233720368547758e18) or (r < -9.2233720368547758e18) then
1140- x.val := Cut(low(int64), t)
1141- else x.val := Cut(trunc(r), t);
1142- end else begin
1143- Value(x); RealToInt(KindOf(s)); Narrow(t^.size, t^.signed)
1144- end;
1145- end else if (IsWord(s) or (s^.form in [fConst, fPtr, fProc, fNil])) and (t^.form in [fPtr, fProc]) then begin
1146- if x.mode <> mConst then Value(x);
1147- end else if (s^.form in [fPtr, fProc]) and IsWord(t) then
1148- Value(x)
1149- else
1150- MarkAt(x.pos, 'can''t convert ' + TypeName(s) + ' to ' + TypeName(t));
1151- x.typ := t;
1152-end;
1153-
1154-{ Calls }
1155-
1156-procedure BeginCall(var c: TCall; var x: TItem);
1157-begin
1158- if x.mode = mProc then begin
1159- c.sig := x.obj^.typ; c.chunk := x.obj^.chunk; c.target := 0;
1160- c.obj := x.obj; c.ext := x.obj^.ext;
1161- end else begin
1162- c.obj := nil; c.ext := false;
1163- if x.typ^.form <> fProc then MarkAt(x.pos, 'expected a procedure, found ' + What(x));
1164- c.sig := x.typ; c.chunk := -1;
1165- c.target := ToSlot(x);
1166- end;
1167- c.param := c.sig^.fields;
1168- c.n := 0;
1169-end;
1170-
1171-{ Too many arguments or too few, at p }
1172-procedure WrongCount(var c: TCall; const p: TPos; const what: shortstring);
1173-begin
1174- if c.obj = nil then MarkAt(p, what);
1175- Error(p, what + ': ' + NameOf(c.obj^.name) + ' takes ' + IntStr(c.sig^.len));
1176- if c.obj^.module <> nil then Note(c.obj^.pos, 'the signature is here');
1177- Fail;
1178-end;
1179-
1180-{ Pushes the two words of x, a slice or two results (InTwoRegs), read
1181- from memory now, so that what comes after can't change them. }
1182-procedure PushWords(var x: TItem);
1183-var adr: TAdr; f: PObj;
1184-begin
1185- if x.mode = mWords then exit; { there already }
1186- { copied to a temporary unless its two words are in memory at a place
1187- that a later argument can't change }
1188- if (x.mode <> mVar) or x.vol or not (x.base in [bFrame, bGlobal, bSlot, bReg]) then CopyToTemp(x);
1189- adr := AdrOf(x);
1190- if x.typ^.form = fSlice then begin
1191- PushVar(adr, 8, false, kWord);
1192- inc(adr.off, 8);
1193- PushVar(adr, 8, false, kWord);
1194- end else begin
1195- f := x.typ^.fields;
1196- while f <> nil do begin
1197- adr.off := AdrOf(x).off + f^.val;
1198- PushVar(adr, ScalarSize(f^.typ), Signed(f^.typ), KindOf(f^.typ));
1199- f := f^.next;
1200- end;
1201- end;
1202-end;
1203-
1204-procedure PassArg(var c: TCall; var a: TItem);
1205-var p: PObj;
1206-begin
1207- p := c.param;
1208- if c.n >= High(c.isF) then MarkAt(a.pos, 'too many arguments');
1209- if p = nil then begin
1210- { past the parameters of a C procedure that ends in ...: a string
1211- goes as a C string, an integer constant as an INT, a real
1212- constant as an F64; C takes no F32 there }
1213- if not c.sig^.variadic then WrongCount(c, a.pos, 'too many arguments');
1214- if a.mode = mStr then Coerce(a, tPtrU8)
1215- else if a.typ^.form = fConst then Coerce(a, tInt)
1216- else if a.typ = tRConst then Coerce(a, tReal)
1217- else if IsF32(a.typ) then MarkAt(a.pos, 'an F32 goes to ... as F64(x)')
1218- else if not IsScalar(a.typ) then MarkAt(a.pos, 'only a single value goes to ...');
1219- c.isF[c.n] := a.typ^.form = fReal;
1220- c.pair[c.n] := false;
1221- Value(a);
1222- inc(c.n);
1223- exit;
1224- end;
1225- c.isF[c.n] := (p^.typ^.form = fReal) and not p^.isVar;
1226- passing := p;
1227- passingAt := a.pos;
1228- if p^.isVar then begin
1229- NotReadOnly(a);
1230- if (a.mode <> mVar) or not a.isVar then MarkAt(a.pos, 'a var parameter needs a variable');
1231- if a.odd then MarkAt(a.pos, 'a field of a packed record can''t be a var parameter');
1232- if not Same(a.typ, p^.typ) then Mismatch(a, 'a var parameter needs exactly ' + TypeName(p^.typ) + ', found ' + What(a));
1233- if a.vol then MarkAt(a.pos, 'can''t pass through a volatile pointer to a var parameter');
1234- Address(a);
1235- end else if p^.typ^.form = fSlice then begin
1236- Coerce(a, p^.typ);
1237- PushWords(a);
1238- c.pair[c.n] := true;
1239- inc(c.n);
1240- c.isF[c.n] := false;
1241- end else if IsAggregate(p^.typ) then begin
1242- Coerce(a, p^.typ);
1243- if a.isVar or a.vol or (a.base <> bFrame) then CopyToTemp(a);
1244- Address(a);
1245- end else begin
1246- Coerce(a, p^.typ);
1247- Value(a);
1248- end;
1249- c.pair[c.n] := false;
1250- inc(c.n);
1251- c.param := p^.next;
1252-end;
1253-
1254-{ The call c made, with x its result as an item: none; a temporary, for a
1255- slice or a record; two results on gen's stack (mWords); else one value
1256- on the stack. }
1257-procedure EndCall(var c: TCall; var x: TItem);
1258-var res: PType;
1259-begin
1260- if c.param <> nil then WrongCount(c, TokPos, 'too few arguments');
1261- Call(c);
1262- res := c.sig^.base;
1263- FillChar(x, SizeOf(x), 0);
1264- if res = nil then begin
1265- x.mode := mNone; x.typ := tNone; x.obj := c.obj
1266- end else if c.ret <> 0 then
1267- TempItem(x, res, c.ret)
1268- else begin
1269- x.mode := mStack; x.typ := res;
1270- if res^.tuple then x.mode := mWords;
1271- end;
1272-end;
1273-
1274-{ Variants }
1275-
1276-{ A temporary of type t, all zero: for variants and record literals. }
1277-procedure ZeroTemp(var x: TItem; t: PType);
1278-var tmp: int64;
1279-begin
1280- tmp := AllocTemp(t^.size, t^.align);
1281- ZeroVar(FrameAdr(tmp), t^.size);
1282- TempItem(x, t, tmp);
1283-end;
1284-
1285-procedure Construct(var x: TItem; c: PObj);
1286-begin
1287- ZeroTemp(x, c^.typ);
1288- PushConst(kWord, c^.val);
1289- PopVar(FrameAdr(x.off), 8);
1290-end;
1291-
1292-procedure SetField(const x: TItem; f: PObj; var a: TItem);
1293-begin
1294- Coerce(a, f^.typ);
1295- if IsScalar(f^.typ) then begin
1296- Value(a);
1297- PopVar(FrameAdr(x.off + f^.val), ScalarSize(f^.typ));
1298- end else begin
1299- if a.vol then MarkAt(a.pos, 'can''t copy through a volatile pointer');
1300- Address(a);
1301- CopyTo(FrameAdr(x.off + f^.val), f^.typ^.size);
1302- end;
1303-end;
1304-
1305-{ The slot match tests: a variant's address, or an enumeration's or an
1306- integer's value. }
1307-function MatchBegin(var x: TItem): int64;
1308-var p: int64;
1309-begin
1310- if x.typ^.form in [fEnum, fInt] then exit(ToSlot(x));
1311- if (x.mode <> mVar) or (x.typ^.form <> fVariant) then MarkAt(x.pos, 'match needs a variant, an enumeration or an integer, found ' + What(x));
1312- if x.ro then CopyToTemp(x); { its arms' names stand for a copy's fields }
1313- Address(x);
1314- p := AllocTemp(8, 8);
1315- PopVar(FrameAdr(p), 8);
1316- MatchBegin := p;
1317-end;
1318-
1319-{ To L unless the tag of the variant whose address is in slot p is tag }
1320-procedure MatchTag(p: int64; tag: int64; var L: longint);
1321-var a: TAdr;
1322-begin
1323- PushVar(FrameAdr(p), 8, false, kWord);
1324- a.base := bStack; a.chunk := -1; a.off := 0;
1325- PushVar(a, 8, false, kWord);
1326- PushConst(kWord, tag);
1327- JumpCmp(sNeq, false, L);
1328-end;
1329-
1330-{ To body if the integer in slot p is from lo to hi: less its lo, it is
1331- then at most hi - lo, compared unsigned, which holds for a signed type
1332- or not, with no second jump. }
1333-procedure MatchRange(p, lo, hi: int64; var body: longint);
1334-begin
1335- PushVar(FrameAdr(p), 8, false, kWord);
1336- if lo = hi then begin
1337- PushConst(kWord, lo);
1338- JumpCmp(sEql, false, body);
1339- exit;
1340- end;
1341- if lo <> 0 then begin
1342- PushConst(kWord, lo);
1343- gen.Op(sMinus, kWord, 8, false);
1344- end;
1345- PushConst(kWord, hi - lo);
1346- JumpCmp(sLeq, false, body);
1347-end;
1348-
1349-{ A for loop's variable o, stepped by step, wrapping as its type does }
1350-procedure ForStep(o: PObj; step: int64);
1351-var v, w: TItem;
1352-begin
1353- MakeItem(v, o);
1354- if v.base = bReg then begin
1355- { a variable in a register is stepped in it }
1356- PushConst(kWord, step);
1357- IncDecReg(v.chunk, IntSize(o^.typ), Signed(o^.typ), false);
1358- exit;
1359- end;
1360- MakeItem(w, o);
1361- Value(w);
1362- PushConst(kWord, step);
1363- gen.Op(sPlus, kWord, IntSize(o^.typ), Signed(o^.typ));
1364- Assign(v, w);
1365-end;
1366-
1367-{ For a for loop: pushes the variable o and the limit lim, a constant or
1368- the slot it was put in, and jumps to L if the one is op the other, as
1369- the type of o compares }
1370-procedure ForCmp(o: PObj; const lim: TItem; op: TSym; var L: longint);
1371-var v, b: TItem;
1372-begin
1373- MakeItem(v, o);
1374- Value(v);
1375- b := lim;
1376- Value(b);
1377- JumpCmp(op, o^.typ^.signed, L);
1378-end;
1379-
1380-{ The end of a round of a for loop, for a positive step s, as the report
1381- has it: if v <= b and b - v < s, the loop ends; otherwise v becomes
1382- v + s and the loop goes on while v <= b. Counting the distance left,
1383- rather than comparing after the step, can't be fooled by v wrapping
1384- around. A negative step is the same the other way round: Before, Past
1385- and Within are indexed by up, whether the step is positive.
1386- For a step of 1: v < b goes on to top, where v is stepped; v = b
1387- ends; otherwise the body moved v past b.
1388- For another step: v past b goes to past; else b - v (unsigned, as
1389- v <= b) >= |step| goes on to top, and else the loop ends.
1390- Past: v is stepped here and tested, going to body if within b. }
1391-procedure ForNext(o: PObj; const lim: TItem; step: int64; var exitL: longint; top, body: longint);
1392-const
1393- Before: array[boolean] of TSym = (sGtr, sLss); { by a negative step, by a positive }
1394- Past: array[boolean] of TSym = (sLss, sGtr);
1395- Within: array[boolean] of TSym = (sGeq, sLeq);
1396-var v, b: TItem; L, pastL: longint; up: boolean;
1397-begin
1398- up := step > 0;
1399- L := NoLabel;
1400- pastL := NoLabel;
1401- if abs(step) = 1 then begin
1402- ForCmp(o, lim, Before[up], L);
1403- FixTo(L, top);
1404- ForCmp(o, lim, sEql, exitL);
1405- end else begin
1406- ForCmp(o, lim, Past[up], pastL);
1407- MakeItem(v, o);
1408- b := lim;
1409- if up then begin Value(b); Value(v) end
1410- else begin Value(v); Value(b) end;
1411- gen.Op(sMinus, kWord, 8, false);
1412- PushConst(kWord, abs(step));
1413- JumpCmp(sGeq, false, L);
1414- FixTo(L, top);
1415- Jump(exitL);
1416- end;
1417- Fix(pastL);
1418- ForStep(o, step);
1419- L := NoLabel;
1420- ForCmp(o, lim, Within[up], L);
1421- FixTo(L, body);
1422-end;
1423-
1424-{ Jumps to L if the condition x is false. The jumps waiting in x.fj join
1425- L; those in x.tj are placed here, as x is true past this. }
1426-procedure CondJump(var x: TItem; var L: longint);
1427-begin
1428- if x.typ^.form <> fBool then MarkAt(x.pos, 'a condition is a BOOL, found ' + What(x));
1429- if x.mode = mCond then begin
1430- JumpCmp(Negated[x.rel], x.relSigned, L);
1431- L := JoinJumps(L, x.fj);
1432- Fix(x.tj);
1433- exit;
1434- end;
1435- Value(x);
1436- JumpIf(L, false);
1437-end;
1438-
1439-{ As CondJump, but the jump to L is taken where the condition is true;
1440- x.tj joins L and x.fj is placed here }
1441-procedure CondJumpTrue(var x: TItem; var L: longint);
1442-begin
1443- if x.typ^.form <> fBool then MarkAt(x.pos, 'a condition is a BOOL, found ' + What(x));
1444- if x.mode = mCond then begin
1445- JumpCmp(x.rel, x.relSigned, L);
1446- L := JoinJumps(L, x.tj);
1447- Fix(x.fj);
1448- exit;
1449- end;
1450- Value(x);
1451- JumpIf(L, true);
1452-end;
1453-
1454-{ Procedures }
1455-
1456-procedure BeginProc(sig: PType; params: PObj);
1457-begin
1458- result := sig^.base;
1459- gen.BeginProc(sig, params);
1460-end;
1461-
1462-{ The result of return x: a value on top, a slice's two words on top,
1463- or one copied behind the hidden pointer }
1464-procedure ReturnValue(var x: TItem);
1465-begin
1466- if result = nil then MarkAt(x.pos, 'this procedure returns nothing');
1467- Coerce(x, result);
1468- if InTwoRegs(result) then PushWords(x)
1469- else if IsAggregate(result) then begin
1470- if x.vol then MarkAt(x.pos, 'can''t copy through a volatile pointer');
1471- Address(x);
1472- CopyResult(0, result^.size);
1473- end else Value(x);
1474-end;
1475-
1476-{ One of several results: of two words, a value left on top for
1477- ReturnJump to put in rax or rdx; else into its place behind the
1478- hidden pointer. }
1479-procedure ReturnField(f: PObj; var x: TItem);
1480-begin
1481- Coerce(x, f^.typ);
1482- if InTwoRegs(result) then Value(x)
1483- else if IsScalar(f^.typ) then begin
1484- Value(x);
1485- ResultTo(f^.val, ScalarSize(f^.typ));
1486- end else begin
1487- if x.vol then MarkAt(x.pos, 'can''t copy through a volatile pointer');
1488- Address(x);
1489- CopyResult(f^.val, f^.typ^.size);
1490- end;
1491-end;
1492-
1493-{ Several results at once, the call's that return f(x) passes on. }
1494-procedure ReturnAll(var x: TItem);
1495-begin
1496- if InTwoRegs(result) then PushWords(x)
1497- else begin
1498- Address(x);
1499- CopyResult(0, result^.size);
1500- end;
1501-end;
1502-
1503-procedure ReturnNone;
1504-begin
1505- if result <> nil then Mark('return needs a result of ' + TypeName(result));
1506- ReturnJump;
1507-end;
1508-
1509-{ Keeps a variable's address in a frame slot, rather than on the stack,
1510- while other code runs. }
1511-procedure Pin(var x: TItem);
1512-var s: int64;
1513-begin
1514- if (x.mode = mVar) and (x.base = bStack) then begin
1515- Address(x);
1516- s := AllocTemp(8, 8);
1517- PopVar(FrameAdr(s), 8);
1518- x.base := bSlot;
1519- x.chunk := s;
1520- end;
1521-end;
1522-
1523-{ INC(v, k) or DEC: v's address is on the stack, from Address. }
1524-procedure IncDec(var v, k: TItem; dec: boolean);
1525-begin
1526- CoerceExact(k, v.typ, '');
1527- Value(k);
1528- if v.base = bReg then IncDecReg(v.chunk, ScalarSize(v.typ), v.typ^.signed, dec)
1529- else gen.IncDec(ScalarSize(v.typ), v.typ^.signed, dec);
1530-end;
1531-
1532-{ COPY(d, s): d, an array variable or a slice, as a slice in the frame,
1533- before s is read }
1534-procedure CopyDest(var d: TItem);
1535-begin
1536- if not IsSeq(d.typ) or (d.mode = mStr) or (d.typ^.form = fArray) and ((d.mode <> mVar) or not d.isVar) then
1537- MarkAt(d.pos, 'COPY copies into an array variable or a slice, found ' + What(d));
1538- if d.typ^.form = fArray then NotReadOnly(d);
1539- SeqSlice(d);
1540-end;
1541-
1542-{ ... and the elements of s copied to its start }
1543-procedure CopyFrom(var d, s: TItem);
1544-begin
1545- if not IsSeq(s.typ) or not Same(ElemOf(s.typ), d.typ^.base) then
1546- MarkAt(s.pos, 'COPY copies elements of ' + TypeName(d.typ^.base) + ', found ' + What(s));
1547- SeqSlice(s);
1548- CopySlice(d.off, s.off, d.typ^.base^.size, checks, s.pos);
1549-end;
1550-
1551-{ An error is the address of its length, followed by its message. }
1552-function ErrorChunk(var x: TItem; module, name: longint): longint;
1553-var c: longint; p: PBytes;
1554-begin
1555- if x.mode <> mStr then MarkAt(x.pos, 'an error is made from a string');
1556- p := GetMem(x.val + 8);
1557- PInt64(p)^ := x.val;
1558- Move(rodata^[chunks^[x.chunk].start], p^[8], x.val);
1559- c := NewChunk(secRodata, module, name);
1560- SetData(c, p, x.val + 8, 8);
1561- FreeMem(p);
1562- ErrorChunk := c;
1563-end;
1564-
1565-procedure Msg(var x: TItem);
1566-var s: int64;
1567-begin
1568- Coerce(x, tError);
1569- Value(x);
1570- s := AllocTemp(16, 8);
1571- ErrorText(s);
1572- TempItem(x, tBytes, s);
1573-end;
1574-
1575-end.

src/link.pas deleted +0 -334

@@ -1,334 +0,0 @@
1-{ link.pas: tree shaking, layout and patching.
2-
3- Starting from the entry chunk, marks every chunk the program can
4- reach through fixups; the rest is left out. Then gives each live
5- chunk its address and builds the images of text and rodata, with
6- every fixup patched.
7-
8- The file is laid out so that each section can be mapped as it lies:
9- text right after the headers, rodata on the next page, then a
10- writable page that starts with the table the dynamic loader reads
11- (none in a static program) and goes on as bss, in memory only. The
12- loader's other tables come at the end of rodata; elf.pas writes them
13- in the room left there.
14-
15- Depends on: chunk for chunks and fixups, scan for names and errors.
16- Leaves out: the file format; that is elf.pas. }
17-
18-unit link;
19-
20-{$mode objfpc}{$H-}
21-
22-interface
23-
24-uses scan, diag, chunk;
25-
26-const
27- Base = $400000;
28- Page = 4096;
29-
30-var
31- textOff, textSize: int64; { file offset and size of text, at Base + textOff }
32- roOff, roSize: int64; { rodata, the room for the loader's tables included }
33- roAdr: int64; { where rodata is loaded }
34- extraAdr: int64; { that room }
35- bssAdr, bssSize: int64; { the writable segment, the loader's table first }
36- bssOff: int64; { the file offset of that table }
37- textImg, roImg: PBytes;
38- placesChunk: longint = -1; { the rodata chunk of the places, made here }
39- linesOff, linesSize: int64; { the line table, in the places: .debug_line }
40-
41-procedure MarkLive(entry: longint);
42-procedure LinkAll(headerSize, roExtra, dynSize: int64);
43-
44-implementation
45-
46-{ Marks live each chunk reached from entry through the fixups. }
47-procedure MarkLive(entry: longint);
48-var stack: PLongs; sp, c, f, t: longint; fx: PFixups;
49-begin
50- stack := GetMem(numChunks * 4);
51- sp := 0;
52- chunks^[entry].live := true;
53- stack^[0] := entry;
54- sp := 1;
55- while sp > 0 do begin
56- dec(sp);
57- c := stack^[sp];
58- if chunks^[c].size < 0 then Fatal(ChunkName(c) + ' is declared but never defined');
59- { code and constants have fixups; variables start at zero, holding
60- no addresses }
61- case chunks^[c].sec of
62- secText: fx := fixups;
63- secRodata: fx := dataFixups;
64- else continue;
65- end;
66- for f := chunks^[c].firstFix to chunks^[c].firstFix + chunks^[c].numFix - 1 do begin
67- t := fx^[f].chunk;
68- if not chunks^[t].live then begin
69- chunks^[t].live := true;
70- stack^[sp] := t;
71- inc(sp);
72- end;
73- end;
74- end;
75- FreeMem(stack);
76-end;
77-
78-{ Gives the live chunks of one section their places, from start;
79- returns the end. }
80-function Place(sec: TSection; start: int64): int64;
81-var c: longint; a: int64;
82-begin
83- a := start;
84- for c := 0 to numChunks - 1 do
85- if chunks^[c].live and (chunks^[c].sec = sec) then begin
86- a := (a + chunks^[c].align - 1) div chunks^[c].align * chunks^[c].align;
87- chunks^[c].adr := a;
88- a := a + chunks^[c].size;
89- end;
90- Place := a;
91-end;
92-
93-{ The line table, DWARF 4's line program, which gdb reads as
94- .debug_line and Rt to say where code comes from: one sequence for
95- each live procedure with lines, a row for each place noted, its
96- address, file, line and column. A row whose address and line move a
97- little is one byte, a special opcode; the others are made of the
98- standard ones. Made in lp, lpLen bytes long. }
99-const
100- LineBase = -5; LineRange = 14; OpcodeBase = 13; { the special opcodes' }
101-
102-var
103- lp: PBytes;
104- lpLen, lpCap: longint;
105-
106-procedure PutB(v: int64);
107-begin
108- if lpLen = lpCap then begin
109- lpCap := lpCap * 2 + 256;
110- lp := ReAllocMem(lp, lpCap);
111- end;
112- lp^[lpLen] := byte(v);
113- inc(lpLen);
114-end;
115-
116-procedure PutN(v: int64; n: longint);
117-var i: longint;
118-begin
119- for i := 1 to n do begin PutB(v); v := v shr 8 end;
120-end;
121-
122-{ LEB128, unsigned and signed }
123-procedure PutU(v: int64);
124-begin
125- while v >= $80 do begin PutB(v and $7F or $80); v := v shr 7 end;
126- PutB(v);
127-end;
128-
129-procedure PutS(v: int64);
130-begin
131- while (v < -64) or (v >= 64) do begin PutB(v and $7F or $80); v := SarInt64(v, 7) end;
132- PutB(v and $7F);
133-end;
134-
135-{ The line program of the files paths, nfiles of them, numbered from
136- 1, as they are written in the table }
137-procedure MakeLines(paths: PLongs; nfiles: longint);
138-var i, f, c, cf, cl, cc, op: longint; at, da, dl: int64; s: shortstring;
139-begin
140- lpLen := 0;
141- PutN(0, 4); { unit_length, patched below }
142- PutN(4, 2); { version }
143- PutN(0, 4); { header_length, patched below }
144- PutB(1); PutB(1); { minimum_instruction_length, maximum_operations }
145- PutB(1); { default_is_stmt }
146- PutB(LineBase); PutB(LineRange); PutB(OpcodeBase);
147- for i := 1 to OpcodeBase - 1 do PutB(ord(i in [2, 3, 4, 5, 9, 12])); { their operands }
148- PutB(0); { no include directories }
149- for f := 0 to nfiles - 1 do begin
150- s := ShownPath(NameOf(paths^[f]));
151- for i := 1 to length(s) do PutB(ord(s[i]));
152- PutN(0, 4); { its end, directory, time, length }
153- end;
154- PutB(0);
155- PLongint(@lp^[6])^ := lpLen - 10;
156- i := 0;
157- while i < numLines do begin
158- c := lines^[i].chunk;
159- if not chunks^[c].live then begin inc(i); continue end;
160- PutB(0); PutU(9); PutB(2); { DW_LNE_set_address }
161- PutN(chunks^[c].adr + lines^[i].at - chunks^[c].start, 8);
162- at := lines^[i].at; cf := 1; cl := 1; cc := 0;
163- while (i < numLines) and (lines^[i].chunk = c) do begin
164- f := 1;
165- while paths^[f - 1] <> lines^[i].path do inc(f);
166- if f <> cf then begin PutB(4); PutU(f); cf := f end; { DW_LNS_set_file }
167- if lines^[i].col <> cc then begin PutB(5); PutU(lines^[i].col); cc := lines^[i].col end; { DW_LNS_set_column }
168- da := lines^[i].at - at;
169- dl := lines^[i].line - cl;
170- op := (dl - LineBase) + LineRange * da + OpcodeBase;
171- if (dl >= LineBase) and (dl < LineBase + LineRange) and (op <= 255) then PutB(op) { a special opcode: a row }
172- else begin
173- if da > 0 then begin PutB(2); PutU(da) end; { DW_LNS_advance_pc }
174- if dl <> 0 then begin PutB(3); PutS(dl) end; { DW_LNS_advance_line }
175- PutB(1); { DW_LNS_copy: a row }
176- end;
177- at := lines^[i].at; cl := lines^[i].line;
178- inc(i);
179- end;
180- PutB(2); PutU(chunks^[c].start + chunks^[c].size - at);
181- PutB(0); PutU(1); PutB(1); { DW_LNE_end_sequence }
182- end;
183- PLongint(@lp^[0])^ := lpLen - 4;
184-end;
185-
186-{ The places that Rt reads to say where a failed check or a signal
187- was, and what calls were under way: where the line table is in them,
188- where text starts and stops, the numbers of procedures and of their
189- variables (I64s); for each live procedure where it starts and stops,
190- the offset of its name, its first variable and how many it has, and
191- the registers of variables it saves, as bits of gen's VarRegs, and
192- the frame offset they are saved at (U32s); for each variable the
193- offset of its name, its place in the frame and its kind, as
194- parse.pas's VarKind (U32s); then the names, each ending in a zero
195- byte; then the line table (MakeLines), at linesOff. They are in no
196- order, since Rt looks at them only as the program stops. }
197-procedure MakePlaces(start, stop: int64);
198-var
199- files, first, count: PLongs; buf: PBytes;
200- i, f, nfiles, k, np, nv, c, v, at, names: longint;
201-
202- procedure Name(const s: shortstring);
203- begin
204- PLongint(@buf^[at])^ := names - k;
205- Move(s[1], buf^[names], length(s));
206- buf^[names + length(s)] := 0;
207- names := names + length(s) + 1;
208- at := at + 4;
209- end;
210-
211-begin
212- files := GetMem(numLines * 4 + 4);
213- first := GetMem(numChunks * 4);
214- count := GetMem(numChunks * 4);
215- FillChar(count^, numChunks * 4, 0);
216- for v := numVarNotes - 1 downto 0 do begin
217- first^[varNotes[v].chunk] := v;
218- inc(count^[varNotes[v].chunk]);
219- end;
220- nfiles := 0; k := 0; np := 0; nv := 0;
221- for i := 0 to numLines - 1 do
222- if chunks^[lines^[i].chunk].live then begin
223- f := 0;
224- while (f < nfiles) and (files^[f] <> lines^[i].path) do inc(f);
225- if f = nfiles then begin
226- files^[f] := lines^[i].path;
227- inc(nfiles);
228- end;
229- end;
230- MakeLines(files, nfiles);
231- for c := 0 to numChunks - 1 do
232- if chunks^[c].live and (chunks^[c].sec = secText) and (chunks^[c].module >= 0) then begin
233- inc(np);
234- k := k + length(ChunkName(c)) + 1;
235- for v := first^[c] to first^[c] + count^[c] - 1 do k := k + length(NameOf(varNotes[v].name)) + 1;
236- nv := nv + count^[c];
237- end;
238- buf := GetMem(40 + 28 * np + 12 * nv + k + lpLen);
239- { the pool of names starts at k, the line table after it }
240- k := 40 + 28 * np + 12 * nv;
241- names := k;
242- at := 40;
243- v := 0;
244- for c := 0 to numChunks - 1 do
245- if chunks^[c].live and (chunks^[c].sec = secText) and (chunks^[c].module >= 0) then begin
246- PLongint(@buf^[at])^ := chunks^[c].adr;
247- PLongint(@buf^[at + 4])^ := chunks^[c].adr + chunks^[c].size;
248- at := at + 8;
249- Name(ChunkName(c));
250- PLongint(@buf^[at])^ := v;
251- PLongint(@buf^[at + 4])^ := count^[c];
252- PLongint(@buf^[at + 8])^ := chunks^[c].saveMask;
253- PLongint(@buf^[at + 12])^ := chunks^[c].saveAt;
254- at := at + 16;
255- v := v + count^[c];
256- end;
257- for c := 0 to numChunks - 1 do
258- if chunks^[c].live and (chunks^[c].sec = secText) and (chunks^[c].module >= 0) then
259- for v := first^[c] to first^[c] + count^[c] - 1 do begin
260- Name(NameOf(varNotes[v].name));
261- PLongint(@buf^[at])^ := varNotes[v].off;
262- PLongint(@buf^[at + 4])^ := varNotes[v].kind;
263- at := at + 8;
264- end;
265- linesOff := names;
266- linesSize := lpLen;
267- Move(lp^, buf^[names], lpLen);
268- PInt64(@buf^[0])^ := linesOff;
269- PInt64(@buf^[8])^ := start;
270- PInt64(@buf^[16])^ := stop;
271- PInt64(@buf^[24])^ := np;
272- PInt64(@buf^[32])^ := nv;
273- SetData(placesChunk, buf, names + lpLen, 8);
274- FreeMem(buf); FreeMem(files); FreeMem(first); FreeMem(count);
275-end;
276-
277-{ Places the live chunks, leaving roExtra bytes at the end of rodata
278- and dynSize at the start of the writable segment. The segments follow
279- each other in the file with no padding, and each is loaded a page
280- further from its file offset than the one before: rodata at Base +
281- Page + roOff, the writable segment at Base + 2 * Page + bssOff. So an
282- address and its offset agree within a page, as the loader needs, and
283- no two segments, with their different permissions, share a page.
284- The bss of a program without the loader's table has no bytes in the
285- file, and starts on a page of its own. }
286-procedure LinkAll(headerSize, roExtra, dynSize: int64);
287-var c, f, at: longint; e, p, v: int64;
288-begin
289- textOff := (headerSize + 31) div 32 * 32; { as each code chunk is }
290- e := Place(secText, Base + textOff);
291- textSize := e - (Base + textOff);
292- if placesChunk >= 0 then MakePlaces(Base + textOff, e);
293- roOff := (textOff + textSize + 31) div 32 * 32;
294- roAdr := Base + Page + roOff;
295- e := Place(secRodata, roAdr);
296- extraAdr := (e + 7) div 8 * 8;
297- if roExtra > 0 then e := extraAdr + roExtra;
298- roSize := e - roAdr;
299- bssOff := (roOff + roSize + 31) div 32 * 32;
300- if dynSize > 0 then bssAdr := Base + 2 * Page + bssOff
301- else bssAdr := (roAdr + roSize + Page - 1) div Page * Page;
302- e := Place(secBss, bssAdr + dynSize);
303- bssSize := e - bssAdr;
304-
305- textImg := GetMem(textSize + 1);
306- { the gaps between code chunks are int3, a trap if ever run }
307- FillChar(textImg^, textSize + 1, $CC);
308- roImg := GetMem(roSize + 1);
309- FillChar(roImg^, roSize + 1, 0);
310- for c := 0 to numChunks - 1 do
311- if chunks^[c].live then
312- case chunks^[c].sec of
313- secText: begin
314- p := chunks^[c].adr - (Base + textOff);
315- Move(code^[chunks^[c].start], textImg^[p], chunks^[c].size);
316- for f := chunks^[c].firstFix to chunks^[c].firstFix + chunks^[c].numFix - 1 do begin
317- at := fixups^[f].at - chunks^[c].start;
318- { rel32: from the end of the field to the target }
319- v := chunks^[fixups^[f].chunk].adr + fixups^[f].addend
320- - (chunks^[c].adr + at + 4);
321- PLongint(@textImg^[p + at])^ := longint(v);
322- end;
323- end;
324- secRodata: begin
325- p := chunks^[c].adr - roAdr;
326- Move(rodata^[chunks^[c].start], roImg^[p], chunks^[c].size);
327- for f := chunks^[c].firstFix to chunks^[c].firstFix + chunks^[c].numFix - 1 do
328- PInt64(@roImg^[p + dataFixups^[f].at])^ :=
329- chunks^[dataFixups^[f].chunk].adr + dataFixups^[f].addend;
330- end;
331- end;
332-end;
333-
334-end.

src/parse.pas deleted +0 -3285

@@ -1,3285 +0,0 @@
1-{ parse.pas: the parser.
2-
3- Reads modules by recursive descent and has gen.pas emit code as it
4- goes: one pass, no tree. Importing a module that isn't compiled yet
5- compiles it there and then, so modules are finished in an order where
6- each comes after the modules it imports; that is the order in which
7- their bodies run.
8-
9- A module may come in one file per target (Name.linux-x86_64.raz and
10- so on). The file for this target is compiled; the others beside it
11- are read for their declarations only, and must export the same
12- interface.
13-
14- Depends on: scan, sym, chunk for data, item and gen for code.
15- Leaves out: linking; a module only records the libraries it names,
16- and whether it uses C or says link static. }
17-
18-unit parse;
19-
20-{$mode objfpc}{$H-}
21-
22-interface
23-
24-uses scan, diag, sym, chunk, gen, item;
25-
26-const
27- Target = 'linux-x86_64';
28- TargetOS = 'linux';
29- TargetArch = 'x86_64';
30- { Whether the target has reals (report, appendix A): x86-64 always has
31- SSE2. Without them, used code that computes with one is an error,
32- which raz.pas reports once it knows what the program uses. }
33- HasReals: boolean = true;
34-
35-var
36- libDir, mainDir: shortstring;
37- incDirs: array[0..15] of shortstring;
38- numInc: longint;
39- firstModule, lastModule: PModule; { in the order they were finished }
40-
41-function CompileMain(const path: shortstring): PModule;
42-function ImportModule(name: longint; const args: TArgs): PModule;
43-
44-implementation
45-
46-uses BaseUnix;
47-
48-type
49- PLoop = ^TLoop;
50- TLoop = record
51- brk: longint; { the chain of its breaks }
52- base: longint; { the deferred statements in force outside it }
53- end;
54-
55- { A generic module's import whose instance isn't made yet (deferred,
56- numDeferred); not to be confused with a defer statement (defers) }
57- TDeferred = record
58- o: PObj; { the name it imports as }
59- m: PModule; { the module that imports it }
60- mname: longint; { the generic module }
61- args: TScanState; { at the "(" of its arguments }
62- at: TPos; { the import }
63- end;
64-
65-var
66- checkMode: boolean; { reading a file only for its interface }
67- inTypes: boolean; { in a type section: ^T may name a later type }
68- fwdTypes: array[0..255] of PType;
69- fwdPos: array[0..255] of TPos; { where each names its type }
70- numFwd: longint;
71- lastCalled: PObj; { the procedure the last call was of, if it had a name }
72- passOn: boolean; { the next factor may be a call with several results, for return }
73- curProc: PObj; { the procedure being compiled, or nil }
74- declExported: boolean; { the export mark of the declaration being read }
75- curLoop: PLoop; { the innermost loop, or nil }
76- defers: array[0..63] of longint; { the defer statements in force, their code's addresses }
77- numDefers: longint;
78- deferring: boolean; { compiling a defer statement's statement }
79- directDefer: boolean; { ... as the statement itself, not in a list }
80- deferSlot: int64; { keeps a result while deferred statements run }
81- curResult: PType; { the result type of the procedure being compiled }
82- inExtern: boolean; { reading an extern's signature: ... allowed }
83- tArgv, tBodySig: PType;
84- nameRt, nameFail, nameMain, nameBody, nameStatic, nameCheck, nameOff, nameAdr: longint;
85- declaring: array[0..63] of longint; { the names the declaration being read declares }
86- numDeclaring: longint;
87- skipped: boolean; { the last statement had an error and was skipped }
88- deferred: array[0..63] of TDeferred; { generic imports not yet made, not defer statements }
89- numDeferred: longint;
90- making: boolean; { reading an instance's arguments, at its first use }
91- stray: boolean; { an "end" in this procedure stood left of its statement's line }
92- strayAt: TPos; { ... the first such statement }
93- elseIf: boolean; { an "else if" in this procedure }
94- drops: array[0..4095] of record
95- at: TPos; { a call standing on its own that drops results }
96- n: longint; { ... how many }
97- end;
98- numDrops: longint; { the module being compiled has those from its
99- first one, saved by CompileFile, to here }
100- ends: boolean; { the statements just read never go on past
101- their end: each way through them returns }
102- useAt: TPos; { ... which is here }
103-
104-procedure Expression(var x: TItem; want: PType); forward;
105-function ParseType: PType; forward;
106-procedure Statements; forward;
107-procedure Statement; forward;
108-
109-{ Little helpers }
110-
111-{ A missing symbol is reported just after the one before it. }
112-procedure Expected(const what: shortstring);
113-begin
114- if tok = sBlank then Mark('_ isn''t a name: it is the blank, which stands only left of :=');
115- MarkAt(MissingPos, 'expected ' + what + ', found ' + Found);
116-end;
117-
118-procedure Expect(s: TSym);
119-begin
120- if (tok = sLbrace) and (s in [sThen, sDo]) then
121- MarkHelp(MissingPos, 'expected ' + SymText(s) + ', found ' + Found, 'a block is written ' + SymText(s) + ' ... end');
122- if tok <> s then Expected(SymText(s));
123- Next;
124-end;
125-
126-{ The end of a block statement at start, whose line is indented to
127- ind. An "end" left of that was most likely meant for a block around
128- the statement, which leaves the statement's own "end" missing: the
129- first such is kept for EndMissing. }
130-procedure CloseEnd(const start: TPos; ind: longint);
131-begin
132- if (tok = sEnd) and not stray and (Indent < ind) then begin
133- stray := true;
134- strayAt := start;
135- end;
136- Expect(sEnd);
137-end;
138-
139-{ The error of a procedure or module whose own "end" isn't where it
140- should be, with what CloseEnd saw }
141-procedure EndMissing(const p: TPos; const msg: shortstring);
142-begin
143- Error(p, msg);
144- if stray then Note(strayAt, 'is this statement''s "end" missing? one further left closes it');
145- if elseIf then Help('raz writes elsif: "else if" begins an if that needs its own "end"');
146- Fail;
147-end;
148-
149-function Name(const s: shortstring): longint;
150-begin
151- Name := Intern(@s[1], length(s));
152-end;
153-
154-{ A name being declared, and whether it is exported; at is the name }
155-procedure IdentDef(var n: longint; var exp: boolean; var at: TPos);
156-begin
157- if tok <> sIdent then Expected('a name');
158- n := id;
159- at := TokPos;
160- Next;
161- exp := false;
162- if tok = sTimes then begin
163- exp := true;
164- Next;
165- end;
166-end;
167-
168-{ Declares o in the innermost scope. Its module keeps its declarations
169- in order: its own, for the interface check, and its procedures', to
170- warn of those never used. }
171-procedure Declare(o: PObj);
172-begin
173- Insert(o, TopScope);
174- if TopScope = curModule^.scope then begin
175- if curModule^.last = nil then curModule^.first := o
176- else curModule^.last^.link := o;
177- curModule^.last := o;
178- end else begin
179- if curModule^.lastLocal = nil then curModule^.locals := o
180- else curModule^.lastLocal^.link := o;
181- curModule^.lastLocal := o;
182- end;
183-end;
184-
185-{ o is named: a procedure naming itself doesn't count }
186-procedure Named(o: PObj);
187-begin
188- if o <> curProc then begin
189- o^.used := true;
190- o^.read := true;
191- end;
192-end;
193-
194-{ Recovery
195-
196- After an error the parser goes on with the next statement or
197- declaration, so that one run reports every error. Each statement and
198- declaration is a recovery point: it notes the state of the scanner
199- and the parser where it starts, and an error (MarkAt) jumps back to
200- it. The state is put back, the scanner reads the construct again
201- from its start, skipping to its end, and the parser carries on after
202- it. Nothing is generated after an error, so the code half made for
203- the construct does no harm. A name that isn't declared is declared
204- where it is used, with type tPoison, and what follows from it is not
205- reported again; so are the names of a declaration that had an error.
206-
207- Skipping counts the words that open and close blocks. A symbol at
208- the start of a line is taken to start a declaration of the module,
209- as layout has it: a statement skipped up to one gives up its
210- procedure, and the procedure is skipped up to its end. }
211-
212-type
213- TRecover = record
214- jb: jmp_buf;
215- outer: ^jmp_buf;
216- scan: TScanState;
217- scopes, depth, pushed, numDefers: longint;
218- loop: PLoop;
219- result: PType;
220- deferring, directDefer, quiet: boolean;
221- end;
222-
223-procedure Guard(var r: TRecover);
224-begin
225- r.outer := recovery;
226- SaveScan(r.scan);
227- r.scopes := ScopeDepth; r.depth := depth; r.pushed := pushed; r.numDefers := numDefers;
228- r.loop := curLoop; r.result := curResult;
229- r.deferring := deferring; r.directDefer := directDefer; r.quiet := quiet;
230- recovery := @r.jb;
231- quiet := false;
232-end;
233-
234-procedure Unguard(var r: TRecover);
235-begin
236- recovery := r.outer;
237- quiet := r.quiet;
238- skipping := false;
239-end;
240-
241-{ After an error: the state as it was at the start of r's construct,
242- whose first symbol is again the current one }
243-procedure Restore(var r: TRecover);
244-begin
245- RestoreScan(r.scan);
246- skipping := true;
247- CutScopes(r.scopes); ResetStack(r.depth, r.pushed); numDefers := r.numDefers;
248- curLoop := r.loop; curResult := r.result;
249- deferring := r.deferring; directDefer := r.directDefer;
250- inTypes := false; declExported := false; inExtern := false; making := false;
251-end;
252-
253-{ Gives up the construct r is for, and the one around it }
254-procedure GiveUp(var r: TRecover);
255-begin
256- Unguard(r);
257- if recovery = nil then Finish;
258- longjmp(recovery^, 1);
259-end;
260-
261-{ Reads to the end of a statement or declaration, from its first
262- symbol: up to the ";" that ends it, not read, or to the "end",
263- "else", "elsif", "until" or "|" of the statement around it (an arm's
264- "|" comes after a ";", the operator's after an operand). False if it
265- stopped at a symbol that starts a line, or the end of the file. }
266-function SkipConstruct: boolean;
267-var d, p: longint; prev: TSym;
268-begin
269- d := 0; p := 0; prev := sSemicolon;
270- repeat
271- case tok of
272- sIf, sWhile, sFor, sMatch, sRepeat, sRecord, sVariant: inc(d);
273- sEnd, sUntil: if d = 0 then exit(true) else dec(d);
274- sElse, sElsif: if (d = 0) and (p = 0) then exit(true);
275- sBar: if (d = 0) and (p = 0) and (prev = sSemicolon) then exit(true);
276- sLparen, sLbrak, sLbrace: inc(p);
277- sRparen, sRbrak, sRbrace: if p > 0 then dec(p);
278- sSemicolon: if (d = 0) and (p = 0) then exit(true);
279- sEof: exit(false);
280- end;
281- prev := tok;
282- Next;
283- until AtLineStart;
284- SkipConstruct := false;
285-end;
286-
287-{ Declares n where it is used, after it was reported as not declared,
288- or after the declaration of it had an error }
289-function Poison(n: longint): PObj;
290-var o: PObj;
291-begin
292- o := NewObj(oConst, n, tPoison);
293- Insert(o, TopScope);
294- Poison := o;
295-end;
296-
297-procedure WillDeclare(n: longint);
298-begin
299- if numDeclaring <= High(declaring) then declaring[numDeclaring] := n;
300- inc(numDeclaring);
301-end;
302-
303-{ After a declaration had an error: its names are poison, and reading
304- goes on after it }
305-procedure SkipDeclaration;
306-var i: longint;
307-begin
308- for i := 0 to numDeclaring - 1 do
309- if (i <= High(declaring)) and (Find(TopScope, declaring[i]) = nil) then
310- Poison(declaring[i]);
311- if SkipConstruct and (tok = sSemicolon) then Next;
312-end;
313-
314-function ConstValue(var x: TItem): int64;
315-begin
316- if x.mode <> mConst then MarkAt(x.pos, 'expected a constant');
317- ConstValue := x.val;
318-end;
319-
320-function ConstExpr: int64;
321-var x: TItem;
322-begin
323- Expression(x, nil);
324- if not IsInt(x.typ) then MarkAt(x.pos, 'expected an integer constant, found ' + What(x));
325- ConstExpr := ConstValue(x);
326-end;
327-
328-{ Help after a name that isn't found: o, the closest name in reach }
329-procedure DidYouMean(o: PObj);
330-begin
331- if o <> nil then Help('did you mean ' + NameOf(o^.name) + '?');
332-end;
333-
334-{ Where module n is found, if it is: dir and the file in it }
335-function ModuleFile(n: longint; var dir, f: shortstring): boolean; forward;
336-
337-{ Reports name n at p as not declared, with what it may have meant }
338-procedure NotDeclared(const p: TPos; n: longint);
339-var dir, f: shortstring;
340-begin
341- Error(p, NameOf(n) + ' isn''t declared');
342- if ModuleFile(n, dir, f) then Help(NameOf(n) + ' is a module: import ' + NameOf(n))
343- else if (NameOf(n) = 'elif') or (NameOf(n) = 'elseif') then Help('raz writes elsif')
344- else if Reserved(Name(LowerCase(NameOf(n)))) then Help('a reserved word is written in lower case: ' + LowerCase(NameOf(n)))
345- else DidYouMean(Closest(n, -1));
346-end;
347-
348-procedure FirstUse(o: PObj; const at: TPos); forward;
349-procedure InstancesFor(wholeRest: boolean); forward;
350-procedure AddImport(m, im: PModule); forward;
351-
352-function QualIdent: PObj;
353-var o: PObj; m: PModule; at: TPos;
354-begin
355- if tok <> sIdent then Expected('a name');
356- at := TokPos;
357- o := Lookup(id);
358- if o = nil then begin
359- if not making then Poison(id); { it may yet be declared }
360- quiet := false;
361- NotDeclared(at, id);
362- if making then Note(useAt, 'the instance is made here, where it is first used');
363- Fail;
364- end;
365- if o^.typ = tPoison then quiet := true;
366- Named(o);
367- Next;
368- if o^.cls = oModule then begin
369- if o^.module = nil then FirstUse(o, at);
370- Expect(sPeriod);
371- if tok <> sIdent then Expected('a name');
372- m := o^.module;
373- o := Find(m^.scope, id);
374- if (o = nil) or not o^.exported then begin
375- Error(TokPos, NameOf(id) + ' isn''t exported by ' + NameOf(m^.name));
376- if o <> nil then Note(o^.pos, NameOf(id) + ' is declared here, without a *')
377- else DidYouMean(Closest(id, m^.scope));
378- Fail;
379- end;
380- Next;
381- end;
382- QualIdent := o;
383-end;
384-
385-{ The field of record type t named by the current symbol }
386-function FieldOf(t: PType): PObj;
387-var f: PObj;
388-begin
389- f := Find(t^.scope, id);
390- if f = nil then begin
391- Error(TokPos, TypeName(t) + ' has no field ' + NameOf(id));
392- DidYouMean(Closest(id, t^.scope));
393- Fail;
394- end;
395- if not f^.exported and (t^.module <> curModule) then begin
396- Error(TokPos, 'field ' + NameOf(id) + ' of ' + TypeName(t) + ' isn''t exported');
397- Note(f^.pos, NameOf(id) + ' is declared here, without a *');
398- Fail;
399- end;
400- FieldOf := f;
401-end;
402-
403-function NewPtr(base: PType; vol: boolean): PType;
404-var t: PType;
405-begin
406- t := NewType(fPtr, 8, 8);
407- t^.base := base;
408- t^.vol := vol;
409- NewPtr := t;
410-end;
411-
412-{ Types }
413-
414-function RecordType: PType;
415-var
416- t, ft: PType; f, last: PObj; names: array[0..63] of longint;
417- exps: array[0..63] of boolean; poss: array[0..63] of TPos;
418- n, i: longint; off, a, maxA: int64;
419-begin
420- t := NewType(fRecord, 0, 1);
421- if tok = sPacked then begin t^.packd := true; Next end;
422- Expect(sRecord);
423- t^.scope := NewScope;
424- off := 0; maxA := 1; last := nil;
425- while tok = sIdent do begin
426- n := 0;
427- repeat
428- if n > High(names) then Mark('more than ' + IntStr(High(names) + 1) + ' names in one declaration');
429- IdentDef(names[n], exps[n], poss[n]);
430- inc(n);
431- if tok <> sComma then break;
432- Next;
433- until false;
434- Expect(sColon);
435- ft := ParseType;
436- if t^.packd then a := 1 else a := ft^.align;
437- for i := 0 to n - 1 do begin
438- off := AlignUp(off, a);
439- f := NewObj(oField, names[i], ft);
440- f^.exported := exps[i];
441- f^.pos := poss[i];
442- f^.val := off;
443- Insert(f, t^.scope);
444- if last = nil then t^.fields := f else last^.next := f;
445- last := f;
446- off := off + ft^.size;
447- end;
448- if a > maxA then maxA := a;
449- Expect(sSemicolon);
450- end;
451- Expect(sEnd);
452- t^.align := maxA;
453- t^.size := AlignUp(off, maxA);
454- RecordType := t;
455-end;
456-
457-function VariantType: PType;
458-var t, ft: PType; c, lastC, f, lastF: PObj; tag, off, maxSize: int64; n: longint;
459-begin
460- Expect(sVariant);
461- t := NewType(fVariant, 8, 8);
462- tag := 0; maxSize := 8; lastC := nil;
463- while tok = sIdent do begin
464- c := NewObj(oCase, id, t);
465- c^.val := tag;
466- c^.exported := declExported;
467- Declare(c);
468- if lastC = nil then t^.fields := c else lastC^.next := c;
469- lastC := c;
470- Next;
471- off := 8;
472- if tok = sLparen then begin
473- Next;
474- lastF := nil;
475- repeat
476- n := 0;
477- repeat
478- if tok <> sIdent then Expected('a name');
479- f := NewObj(oField, id, nil);
480- f^.exported := true;
481- if lastF = nil then c^.fields := f else lastF^.next := f;
482- lastF := f;
483- inc(n);
484- Next;
485- if tok <> sComma then break;
486- Next;
487- until false;
488- Expect(sColon);
489- ft := ParseType;
490- f := c^.fields;
491- while f^.typ <> nil do f := f^.next;
492- while f <> nil do begin
493- f^.typ := ft;
494- off := AlignUp(off, ft^.align);
495- f^.val := off;
496- off := off + ft^.size;
497- f := f^.next;
498- end;
499- if ft^.align > t^.align then t^.align := ft^.align;
500- if tok <> sSemicolon then break;
501- Next;
502- until false;
503- Expect(sRparen);
504- end;
505- if off > maxSize then maxSize := off;
506- Expect(sSemicolon);
507- inc(tag);
508- end;
509- Expect(sEnd);
510- t^.len := tag;
511- t^.size := AlignUp(maxSize, t^.align);
512- VariantType := t;
513-end;
514-
515-{ Several results: a record of them, laid out as C would, and
516- returned in rax and rdx if they are two words (InTwoRegs), or else
517- through a hidden pointer. }
518-function Results: PType;
519-var t, ft: PType; f, last: PObj; off: int64;
520-begin
521- Next;
522- t := NewType(fRecord, 0, 1);
523- t^.tuple := true;
524- off := 0; last := nil;
525- repeat
526- ft := ParseType;
527- off := AlignUp(off, ft^.align);
528- f := NewObj(oField, -1, ft);
529- f^.val := off;
530- off := off + ft^.size;
531- if ft^.align > t^.align then t^.align := ft^.align;
532- if last = nil then t^.fields := f else last^.next := f;
533- last := f;
534- inc(t^.len);
535- if tok <> sComma then break;
536- Next;
537- until false;
538- Expect(sRparen);
539- t^.size := AlignUp(off, t^.align);
540- if t^.len = 1 then Results := t^.fields^.typ else Results := t;
541-end;
542-
543-function Signature: PType;
544-var
545- t, pt: PType; p, first, last: PObj; isVar: boolean; n: longint;
546-begin
547- t := NewType(fProc, 8, 8);
548- last := nil; n := 0;
549- if tok = sLparen then begin
550- Next;
551- if tok <> sRparen then
552- repeat
553- if tok = sEllipsis then begin
554- if not inExtern then Mark('... is only for extern procedures');
555- Next; t^.variadic := true; break
556- end;
557- isVar := tok = sVar;
558- if isVar then Next;
559- first := nil;
560- repeat
561- if tok <> sIdent then Expected('a name');
562- p := NewObj(oVar, id, nil);
563- p^.isVar := isVar;
564- p^.lev := 1;
565- if last = nil then t^.fields := p else last^.next := p;
566- last := p;
567- if first = nil then first := p;
568- inc(n);
569- Next;
570- if tok <> sComma then break;
571- Next;
572- until false;
573- Expect(sColon);
574- pt := ParseType;
575- while first <> nil do begin first^.typ := pt; first := first^.next end;
576- if tok <> sSemicolon then break;
577- Next;
578- until false;
579- Expect(sRparen);
580- end;
581- t^.len := n;
582- if tok = sColon then begin
583- Next;
584- if tok = sLparen then t^.base := Results else t^.base := ParseType;
585- end;
586- Signature := t;
587-end;
588-
589-function EnumType: PType;
590-var t: PType; o, last: PObj; start: TPos;
591-begin
592- start := TokPos;
593- t := NewType(fEnum, 1, 1);
594- last := nil;
595- repeat
596- Next;
597- if tok <> sIdent then Expected('a name');
598- o := NewObj(oConst, id, t);
599- o^.val := t^.len;
600- o^.exported := declExported;
601- o^.used := true; { an enumeration's names are its type's, warned of with it }
602- Declare(o);
603- if last = nil then t^.fields := o else last^.next := o;
604- last := o;
605- inc(t^.len);
606- Next;
607- until tok <> sComma;
608- Expect(sRparen);
609- if t^.len > 256 then MarkAt(SpanFrom(start), 'an enumeration has at most 256 names');
610- EnumType := t;
611-end;
612-
613-function SetOf(e: PType; const at: TPos): PType;
614-var t: PType;
615-begin
616- if (e^.form <> fEnum) or (e^.len > 64) then MarkAt(at, 'a set needs an enumeration of at most 64 names, found ' + TypeName(e));
617- t := NewType(fSet, 8, 8);
618- if e^.len <= 8 then t^.size := 1
619- else if e^.len <= 16 then t^.size := 2
620- else if e^.len <= 32 then t^.size := 4;
621- t^.align := t^.size;
622- t^.base := e;
623- t^.len := e^.len;
624- SetOf := t;
625-end;
626-
627-function ParseType: PType;
628-var t: PType; o: PObj; n: int64; vol: boolean; start: TPos;
629-begin
630- start := TokPos;
631- case tok of
632- sIdent: begin
633- o := QualIdent;
634- if o^.cls <> oType then MarkAt(SpanFrom(start), NameOf(o^.name) + ' isn''t a type');
635- t := o^.typ;
636- end;
637- sLbrak: begin
638- Next;
639- if tok = sRbrak then begin
640- Next;
641- t := NewType(fSlice, 16, 8);
642- t^.base := ParseType();
643- end else begin
644- start := TokPos;
645- n := ConstExpr;
646- if (n <= 0) or (n > (int64(1) shl 40)) then MarkAt(SpanFrom(start), 'an array''s length is from 1 to 2^40, found ' + IntStr(n));
647- Expect(sRbrak);
648- t := NewType(fArray, 0, 1);
649- t^.len := n;
650- t^.base := ParseType();
651- t^.size := n * t^.base^.size;
652- t^.align := t^.base^.align;
653- end;
654- end;
655- sArrow: begin
656- Next;
657- vol := tok = sVolatile;
658- if vol then Next;
659- if inTypes and (tok = sIdent) and (Lookup(id) = nil) then begin
660- { a type declared later in this section }
661- t := NewPtr(nil, vol);
662- t^.fwd := id;
663- if numFwd > High(fwdTypes) then Mark('more than ' + IntStr(High(fwdTypes) + 1) + ' pointers to types not yet declared');
664- fwdTypes[numFwd] := t;
665- fwdPos[numFwd] := TokPos;
666- inc(numFwd);
667- Next;
668- end else
669- t := NewPtr(ParseType(), vol);
670- end;
671- sPacked, sRecord: t := RecordType;
672- sVariant: t := VariantType;
673- sProc: begin Next; t := Signature end;
674- sLparen: t := EnumType;
675- sSet: begin
676- Next;
677- Expect(sOf);
678- start := TokPos;
679- t := SetOf(ParseType(), start);
680- end;
681- else Expected('a type');
682- end;
683- ParseType := t;
684-end;
685-
686-{ Expressions }
687-
688-procedure Call(var x: TItem);
689-var c: TCall; a: TItem; want: PType;
690-begin
691- BeginCall(c, x);
692- Expect(sLparen);
693- if tok <> sRparen then
694- repeat
695- if c.param <> nil then want := c.param^.typ else want := nil;
696- Expression(a, want);
697- PassArg(c, a);
698- if tok <> sComma then break;
699- Next;
700- until false;
701- Expect(sRparen);
702- EndCall(c, x);
703-end;
704-
705-procedure Atomic(var x: TItem; which: longint);
706-var p, a: TItem; t: PType; i, n: longint;
707-begin
708- Expression(p, nil);
709- if p.typ^.form <> fPtr then MarkAt(p.pos, 'expected a pointer, found ' + What(p));
710- t := p.typ^.base;
711- if not (IsWord(t) or ((t^.form = fPtr) and (which <> bXadd))) then
712- if which = bXadd then MarkAt(p.pos, 'expected a pointer to an INT or a UINT, found ' + TypeName(p.typ))
713- else MarkAt(p.pos, 'expected a pointer to an INT, a UINT or a pointer, found ' + TypeName(p.typ));
714- Value(p);
715- if which = bCas then n := 2 else n := 1;
716- for i := 1 to n do begin
717- Expect(sComma);
718- Expression(a, t);
719- Coerce(a, t);
720- Value(a);
721- end;
722- gen.Atomic(which);
723- MakeConst(x, t, 0);
724- if which = bCas then x.typ := tBool;
725- x.mode := mStack;
726-end;
727-
728-{ NEW(p, a): p := a^.alloc(a, SIZE(T), alignment), zeroed if not nil.
729- a is a ^Mem.Allocator, the one interface the compiler knows. }
730-procedure New_(var x: TItem);
731-var y, z: TItem; t: PType; f: PObj; s: int64; c: TCall;
732-begin
733- Expression(x, nil);
734- NotReadOnly(x);
735- if (x.mode <> mVar) or not x.isVar or (x.typ^.form <> fPtr) then MarkAt(x.pos, 'NEW needs a pointer variable');
736- t := x.typ^.base;
737- Expect(sComma);
738- Expression(y, nil);
739- if (y.typ^.form <> fPtr) or (y.typ^.base^.obj = nil) or (y.typ^.base^.obj^.module = nil)
740- or (NameOf(y.typ^.base^.obj^.name) <> 'Allocator')
741- or (NameOf(y.typ^.base^.obj^.module^.name) <> 'Mem') then MarkAt(y.pos, 'NEW needs a ^Mem.Allocator, found ' + What(y));
742- f := Find(y.typ^.base^.scope, Name('alloc'));
743- s := ToSlot(y);
744- PushVar(FrameAdr(s), 8, false, kWord);
745- MakeConst(z, f^.typ, 0);
746- z.mode := mVar; z.base := bStack; z.off := f^.val;
747- BeginCall(c, z);
748- PushVar(FrameAdr(s), 8, false, kWord);
749- MakeConst(z, y.typ, 0);
750- z.mode := mStack;
751- PassArg(c, z);
752- MakeConst(z, tInt, t^.size);
753- PassArg(c, z);
754- MakeConst(z, tInt, t^.align);
755- PassArg(c, z);
756- EndCall(c, z);
757- ZeroNew(t^.size);
758- z.typ := x.typ;
759- Assign(x, z);
760- MakeConst(x, tNone, 0);
761- x.mode := mNone;
762-end;
763-
764-function IncOrDec(which: longint): shortstring;
765-begin
766- if which = bDec then IncOrDec := 'DEC' else IncOrDec := 'INC';
767-end;
768-
769-procedure Builtin(var x: TItem);
770-var which, n: longint; y: TItem; t: PType;
771-begin
772- which := x.obj^.val;
773- if which in [bFence, bArgc, bArgv] then begin
774- if tok = sLparen then begin Next; Expect(sRparen) end;
775- MakeConst(x, tNone, 0);
776- case which of
777- bFence: begin Fence; x.mode := mNone end;
778- bArgc: begin PushVar(GlobalAdr(argcChunk), 8, false, kWord); x.typ := tInt; x.mode := mStack end;
779- bArgv: begin PushVar(GlobalAdr(argvChunk), 8, false, kWord); x.typ := tArgv; x.mode := mStack end;
780- end;
781- exit;
782- end;
783- Expect(sLparen);
784- case which of
785- bSize: begin
786- t := ParseType;
787- MakeConst(x, tConst, t^.size);
788- end;
789- bAdr: begin
790- Expression(y, nil);
791- NotReadOnly(y);
792- if (y.mode <> mVar) or not y.isVar then MarkAt(y.pos, 'ADR needs a variable');
793- if y.odd then MarkAt(y.pos, 'a field of a packed record has no address');
794- t := NewPtr(y.typ, y.vol);
795- Address(y);
796- MakeConst(x, t, 0);
797- x.mode := mStack;
798- end;
799- bLen: begin
800- Expression(y, nil);
801- if y.mode = mStr then MakeConst(x, tConst, y.val)
802- else if y.typ^.form = fArray then begin
803- Discard(y);
804- MakeConst(x, tConst, y.typ^.len)
805- end else if (y.typ^.form = fSlice) and (y.mode = mVar) then begin
806- { its length, the word after its pointer }
807- y.off := y.off + 8;
808- y.typ := tInt;
809- Value(y);
810- x := y;
811- end else MarkAt(y.pos, 'LEN needs an array or a slice, found ' + What(y));
812- end;
813- bSyscall: begin
814- n := 0;
815- repeat
816- if n > 0 then Next;
817- Expression(y, nil);
818- if not (IsScalar(y.typ) and (y.typ^.form <> fReal)) then MarkAt(y.pos, 'expected an integer or a pointer, found ' + What(y));
819- if y.typ^.form = fConst then Coerce(y, tInt);
820- Value(y);
821- inc(n);
822- until (tok <> sComma) or (n = 7);
823- SysCall(n);
824- MakeConst(x, tInt, 0);
825- x.mode := mStack;
826- end;
827- bCas, bXchg, bXadd: Atomic(x, which);
828- bMsg: begin Expression(x, tError); Msg(x) end;
829- bInc, bDec: begin
830- Expression(x, nil);
831- NotReadOnly(x);
832- if (x.mode <> mVar) or not x.isVar or (x.typ^.form <> fInt) then
833- MarkAt(x.pos, IncOrDec(which) + ' needs an integer variable');
834- if x.base <> bReg then Address(x);
835- if tok = sComma then begin
836- Next;
837- Expression(y, x.typ);
838- end else MakeConst(y, x.typ, 1);
839- IncDec(x, y, which = bDec);
840- MakeConst(x, tNone, 0);
841- x.mode := mNone;
842- end;
843- bNew: New_(x);
844- bCopy: begin
845- Expression(x, nil);
846- CopyDest(x);
847- Expect(sComma);
848- Expression(y, nil);
849- CopyFrom(x, y);
850- MakeConst(x, tNone, 0);
851- x.mode := mNone;
852- end;
853- end;
854- Expect(sRparen);
855-end;
856-
857-procedure ConstructCase(var x: TItem; c: PObj; const at: TPos);
858-var f: PObj; a: TItem;
859-begin
860- Construct(x, c);
861- f := c^.fields;
862- if tok = sLparen then begin
863- Next;
864- while f <> nil do begin
865- Expression(a, f^.typ);
866- SetField(x, f, a);
867- f := f^.next;
868- if f <> nil then Expect(sComma);
869- end;
870- Expect(sRparen);
871- end else if f <> nil then MarkAt(at, NameOf(c^.name) + ' needs its fields');
872-end;
873-
874-{ x, before ".", has no fields; tok is what follows. Other languages
875- write p.f through a pointer and s.len for a length. }
876-procedure FieldOfWhat(const x: TItem);
877-var msg, f: shortstring;
878-begin
879- msg := 'expected a record, found ' + What(x);
880- if tok = sIdent then f := NameOf(id) else f := '';
881- if (x.typ^.form = fPtr) and (x.typ^.base^.form = fRecord) then
882- MarkHelp(x.pos, msg, 'through a pointer, write ' + Source(x.pos) + '^.' + f)
883- else if (x.typ^.form in [fArray, fSlice]) and ((f = 'len') or (f = 'length') or (f = 'size') or (f = 'count')) then
884- MarkHelp(x.pos, msg, 'its length is LEN(' + Source(x.pos) + ')');
885- MarkAt(x.pos, msg);
886-end;
887-
888-{ A designator, with any selectors and calls after it. called tells
889- whether the last thing done was a call. }
890-procedure Designator(var x: TItem; var called: boolean);
891-var o, f: PObj; y, z: TItem; t: PType; start: TPos;
892-begin
893- start := TokPos;
894- o := QualIdent;
895- called := false;
896- if o^.cls = oModule then MarkAt(SpanFrom(start), NameOf(o^.name) + ' is a module, not a value');
897- MakeItem(x, o);
898- if x.mode = mBuiltin then begin
899- Builtin(x);
900- called := true;
901- end else if x.mode = mCase then begin
902- ConstructCase(x, o, SpanFrom(start));
903- end;
904- repeat
905- x.pos := SpanFrom(start);
906- case tok of
907- sPeriod: begin
908- Next;
909- if (x.mode <> mVar) or (x.typ^.form <> fRecord) then FieldOfWhat(x);
910- if tok <> sIdent then Expected('a field');
911- f := FieldOf(x.typ);
912- Next;
913- Field(x, f);
914- called := false;
915- end;
916- sArrow: begin Next; Deref(x); called := false end;
917- sLbrak: begin
918- Next;
919- IndexPrep(x);
920- Expression(y, nil);
921- if tok = sUpto then begin
922- Next;
923- SliceLo(y);
924- Expression(z, nil);
925- Slice(x, y, z);
926- end else Index(x, y);
927- Expect(sRbrak);
928- called := false;
929- end;
930- sLparen: begin
931- if x.mode = mType then begin
932- t := x.typ;
933- Next;
934- Expression(x, nil);
935- Expect(sRparen);
936- Convert(x, t);
937- end else begin
938- if x.mode = mProc then lastCalled := x.obj else lastCalled := nil;
939- Call(x);
940- called := true;
941- end;
942- end;
943- else break;
944- end;
945- until false;
946- x.pos := SpanFrom(start);
947- NilTest(x);
948-end;
949-
950-procedure ArrayLiteral(var x: TItem; want: PType);
951-var
952- et, at: PType; e: TItem; slots: array[0..1023] of int64; n, i: longint;
953- off, es: int64; start: TPos;
954-begin
955- start := TokPos;
956- if (want = nil) or not (want^.form in [fArray, fSlice]) then
957- Mark('an array literal needs a known array or slice type');
958- et := want^.base;
959- es := et^.size;
960- Next;
961- n := 0;
962- if tok <> sRbrak then
963- repeat
964- if n > High(slots) then Mark('more than ' + IntStr(High(slots) + 1) + ' elements');
965- Expression(e, et);
966- Coerce(e, et);
967- if IsScalar(et) then slots[n] := ToSlot(e)
968- else begin
969- if e.isVar or e.vol or (e.mode <> mVar) or (e.base <> bFrame) then CopyToTemp(e);
970- slots[n] := e.off;
971- end;
972- inc(n);
973- if tok <> sComma then break;
974- Next;
975- until false;
976- Expect(sRbrak);
977- if (want^.form = fArray) and (n <> want^.len) then MarkAt(SpanFrom(start), 'expected ' + IntStr(want^.len) + ' elements, found ' + IntStr(n));
978- if n = 0 then begin
979- PushConst(kWord, 0);
980- SliceOf(x, want, 0);
981- exit;
982- end;
983- if want^.form = fArray then begin
984- at := want;
985- off := AllocTemp(at^.size, at^.align);
986- end else begin
987- at := NewType(fArray, n * es, et^.align);
988- at^.len := n;
989- at^.base := et;
990- off := AllocPerm(at^.size, at^.align); { lives as long as the call }
991- end;
992- for i := 0 to n - 1 do
993- if IsScalar(et) then begin
994- PushVar(FrameAdr(slots[i]), 8, false, KindOf(et));
995- PopVar(FrameAdr(off + i * es), ScalarSize(et));
996- end else begin
997- PushAdr(FrameAdr(slots[i]));
998- CopyTo(FrameAdr(off + i * es), es);
999- end;
1000- TempItem(x, at, off);
1001-end;
1002-
1003-{ A record literal: a zeroed temporary, with the fields named filled in. }
1004-procedure RecordLiteral(var x: TItem; t: PType);
1005-var f: PObj; a: TItem; seen: array[0..63] of longint; n, i: longint;
1006-begin
1007- Next;
1008- ZeroTemp(x, t);
1009- FillChar(seen, SizeOf(seen), 0);
1010- n := 0;
1011- if tok <> sRbrace then
1012- repeat
1013- if tok <> sIdent then Expected('a field');
1014- f := FieldOf(t);
1015- for i := 0 to n - 1 do if seen[i] = id then Mark('field ' + NameOf(id) + ' is given twice');
1016- if n <= High(seen) then begin seen[n] := id; inc(n) end;
1017- Next;
1018- Expect(sColon);
1019- Expression(a, f^.typ);
1020- SetField(x, f, a);
1021- if tok <> sComma then break;
1022- Next;
1023- until false;
1024- Expect(sRbrace);
1025-end;
1026-
1027-{ A set literal: the bits of the constant names, or'd at run time with
1028- those of the others. }
1029-procedure SetLiteral(var x: TItem; t: PType);
1030-var e: TItem; bits, slot: int64; start: TPos; s: shortstring;
1031-begin
1032- start := TokPos;
1033- Next;
1034- if (t <> nil) and (t^.form <> fSet) then MarkAt(SpanFrom(start), 'expected a set type, found ' + TypeName(t));
1035- bits := 0;
1036- slot := 0;
1037- if tok <> sRbrace then
1038- repeat
1039- if t = nil then Expression(e, nil) else Expression(e, t^.base);
1040- if t = nil then begin
1041- if e.typ^.form <> fEnum then MarkAt(e.pos, 'a set holds names of an enumeration, found ' + What(e));
1042- t := SetOf(e.typ, e.pos);
1043- end;
1044- if not Same(e.typ, t^.base) then begin
1045- if e.obj <> nil then s := NameOf(e.obj^.name) else s := What(e);
1046- MarkAt(e.pos, s + ' isn''t a name of ' + TypeName(t^.base));
1047- end;
1048- if e.mode = mConst then bits := bits or (int64(1) shl e.val)
1049- else begin
1050- if slot = 0 then begin
1051- slot := AllocTemp(8, 8);
1052- PushConst(kWord, 0);
1053- PopVar(FrameAdr(slot), 8);
1054- end;
1055- Value(e);
1056- PushConst(kWord, 1);
1057- Swap;
1058- Op(sShl, kWord, 8, false);
1059- PushVar(FrameAdr(slot), 8, false, kWord);
1060- Op(sBar, kWord, 8, false);
1061- PopVar(FrameAdr(slot), 8);
1062- end;
1063- if tok <> sComma then break;
1064- Next;
1065- until false;
1066- Expect(sRbrace);
1067- if t = nil then MarkAt(SpanFrom(start), '{} needs a known set type');
1068- MakeConst(x, t, bits);
1069- if slot <> 0 then begin
1070- PushVar(FrameAdr(slot), 8, false, kWord);
1071- PushConst(kWord, bits);
1072- Op(sBar, kWord, 8, false);
1073- x.mode := mStack;
1074- end;
1075-end;
1076-
1077-procedure RunDefers(base: longint); forward;
1078-
1079-{ The type of the last result of t, the results of a procedure: t if
1080- it has one, else the last of its several. }
1081-function LastResult(t: PType): PType;
1082-var f: PObj;
1083-begin
1084- if not t^.tuple then exit(t);
1085- f := t^.fields;
1086- while f^.next <> nil do f := f^.next;
1087- LastResult := f^.typ;
1088-end;
1089-
1090-{ The results of the tuple t but the last: the same fields, one fewer }
1091-function WithoutLast(t: PType): PType;
1092-var r: PType;
1093-begin
1094- r := NewType(fRecord, t^.size, t^.align);
1095- r^.tuple := true;
1096- r^.fields := t^.fields;
1097- r^.len := t^.len - 1;
1098- WithoutLast := r;
1099-end;
1100-
1101-{ try c (the report, 7.8): the call c, then the error it returned, its
1102- last result: if that isn't nil, the procedure returns it, and a zero
1103- for each of its other results, after running the deferred statements
1104- in force. x is left c's other results: none (mNone), one (a value) or
1105- several (a tuple, for a multiple assignment). The error is kept in a
1106- slot of the frame, and tested there; the code for it, out of line,
1107- is made with the stack of values as it stands, and leaves it so,
1108- since what follows is the code for an error that is nil. }
1109-procedure TryCall(var x: TItem);
1110-var
1111- called: boolean; c: TCall; start, at: TPos; res: PType; last: PObj; slot: int64; ok: longint;
1112-begin
1113- start := TokPos;
1114- Next;
1115- if deferring then MarkAt(SpanFrom(start), 'try can''t leave a deferred statement');
1116- if curResult = nil then
1117- MarkAt(SpanFrom(start), 'try needs a procedure that ends in an ERROR result, and this returns nothing')
1118- else if LastResult(curResult) <> tError then
1119- MarkAt(SpanFrom(start), 'try needs a procedure that ends in an ERROR result, and this returns ' + TypeName(curResult));
1120- Designator(x, called);
1121- if not called and ((x.mode = mProc) or ((x.mode in [mVar, mStack]) and (x.typ^.form = fProc))) then begin
1122- { a procedure without parameters, written without parentheses }
1123- at := x.pos;
1124- BeginCall(c, x);
1125- EndCall(c, x);
1126- x.pos := at;
1127- called := true;
1128- end;
1129- if not called then MarkAt(x.pos, 'try needs a call, found ' + What(x));
1130- if x.mode = mNone then
1131- MarkAt(x.pos, 'try needs a call that returns an ERROR last, and this returns nothing');
1132- if LastResult(x.typ) <> tError then
1133- MarkAt(x.pos, 'try needs a call that returns an ERROR last, and this returns ' + TypeName(x.typ));
1134- res := x.typ;
1135- if x.mode = mStack then begin
1136- { an ERROR alone }
1137- slot := AllocTemp(8, 8);
1138- PopVar(FrameAdr(slot), 8);
1139- x.mode := mNone; x.typ := tNone;
1140- end else if x.mode = mWords then begin
1141- { two words, the error on top }
1142- slot := AllocTemp(8, 8);
1143- PopVar(FrameAdr(slot), 8);
1144- x.mode := mStack; x.typ := res^.fields^.typ;
1145- end else begin
1146- { several, in a temporary: the error is where it is }
1147- last := res^.fields;
1148- while last^.next <> nil do last := last^.next;
1149- slot := x.off + last^.val;
1150- if res^.len = 2 then Field(x, res^.fields) else x.typ := WithoutLast(res);
1151- end;
1152- ok := NoLabel;
1153- PushVar(FrameAdr(slot), 8, false, kWord);
1154- JumpIf(ok, false);
1155- if numDefers > 0 then TryAlign;
1156- RunDefers(0);
1157- TryReturn(slot);
1158- Fix(ok);
1159- x.pos := SpanFrom(start);
1160-end;
1161-
1162-procedure Factor(var x: TItem; want: PType);
1163-var called, vol, several: boolean; t: PType; start: TPos; s: shortstring;
1164-begin
1165- several := passOn;
1166- passOn := false;
1167- start := TokPos;
1168- case tok of
1169- sInt, sChar: begin
1170- { only a hex number can be above high(I64), and it is a U64 }
1171- if ival < 0 then MakeConst(x, tU64, ival) else MakeConst(x, tConst, ival);
1172- Next;
1173- end;
1174- sReal: begin MakeReal(x, rval); UsesReals(TokPos); Next end;
1175- sString: begin MakeStr(x); Next end;
1176- sIdent: begin
1177- Designator(x, called);
1178- if x.mode = mNone then begin
1179- if lastCalled <> nil then s := NameOf(lastCalled^.name) else s := 'this procedure';
1180- MarkAt(x.pos, s + ' returns nothing');
1181- end;
1182- if x.typ^.tuple and not several then begin
1183- if lastCalled <> nil then s := NameOf(lastCalled^.name) else s := 'this procedure';
1184- MarkHelp(x.pos, s + ' returns several results', 'they go to variables: a, b := ' + s + '(...)');
1185- if x.mode = mWords then CopyToTemp(x);
1186- end;
1187- end;
1188- sLparen: begin Next; Expression(x, want); Expect(sRparen) end;
1189- sTry: begin
1190- TryCall(x);
1191- if x.mode = mNone then MarkAt(x.pos, 'this try has no value');
1192- if x.typ^.tuple then
1193- MarkHelp(x.pos, 'this try has several values', 'they go to variables: a, b := try f(...)');
1194- end;
1195- sNot: begin Next; Factor(x, nil); NotOp(x) end;
1196- sTilde: begin Next; Factor(x, nil); Complement(x) end;
1197- sLbrak: ArrayLiteral(x, want);
1198- sLbrace: if (want <> nil) and (want^.form = fRecord) then RecordLiteral(x, want)
1199- else SetLiteral(x, want);
1200- sArrow: begin
1201- Next;
1202- vol := tok = sVolatile;
1203- if vol then Next;
1204- t := NewPtr(ParseType, vol);
1205- Expect(sLparen);
1206- Expression(x, nil);
1207- Expect(sRparen);
1208- Convert(x, t);
1209- { a conversion is a factor, not a designator: nothing selects from it }
1210- if tok = sArrow then
1211- MarkHelp(TokPos, 'a conversion can''t be dereferenced', 'convert into a pointer variable, then dereference that');
1212- end;
1213- else Expected('an expression');
1214- end;
1215- x.pos := SpanFrom(start);
1216-end;
1217-
1218-procedure Term(var x: TItem; want: PType);
1219-var op: TSym; y: TItem; L: longint; start: TPos;
1220-begin
1221- start := TokPos;
1222- Factor(x, want);
1223- while tok in [sTimes, sSlash, sDiv, sMod, sAmp, sShl, sShr] do begin
1224- op := tok;
1225- Next;
1226- Op1(op, x, L);
1227- Factor(y, nil);
1228- Op2(op, x, y, L);
1229- x.pos := SpanFrom(start);
1230- end;
1231-end;
1232-
1233-procedure SimpleExpr(var x: TItem; want: PType);
1234-var op: TSym; y: TItem; L: longint; start: TPos;
1235-begin
1236- start := TokPos;
1237- if tok = sMinus then begin
1238- Next;
1239- Term(x, nil);
1240- x.pos := SpanFrom(start);
1241- Neg(x);
1242- end else Term(x, want);
1243- while tok in [sPlus, sMinus, sBar, sXor] do begin
1244- op := tok;
1245- Next;
1246- Op1(op, x, L);
1247- Term(y, nil);
1248- Op2(op, x, y, L);
1249- x.pos := SpanFrom(start);
1250- end;
1251-end;
1252-
1253-procedure Relation(var x: TItem; want: PType);
1254-var op: TSym; y: TItem; L: longint;
1255-begin
1256- SimpleExpr(x, want);
1257- if tok in [sEql, sNeq, sLss, sLeq, sGtr, sGeq, sIn] then begin
1258- op := tok;
1259- Next;
1260- Op1(op, x, L);
1261- if op = sIn then SimpleExpr(y, nil) else SimpleExpr(y, x.typ);
1262- Op2(op, x, y, L);
1263- x.pos := Join(x.pos, y.pos);
1264- end;
1265-end;
1266-
1267-{ and binds tighter than or, and both below the relations }
1268-procedure Conjunct(var x: TItem; want: PType);
1269-var y: TItem; L: longint; start: TPos;
1270-begin
1271- start := TokPos;
1272- Relation(x, want);
1273- while tok = sAnd do begin
1274- Next;
1275- Op1(sAnd, x, L);
1276- Relation(y, nil);
1277- Op2(sAnd, x, y, L);
1278- x.pos := SpanFrom(start);
1279- end;
1280-end;
1281-
1282-procedure Expression(var x: TItem; want: PType);
1283-var y: TItem; L: longint; start: TPos;
1284-begin
1285- start := TokPos;
1286- Conjunct(x, want);
1287- while tok = sOr do begin
1288- Next;
1289- Op1(sOr, x, L);
1290- Conjunct(y, nil);
1291- Op2(sOr, x, y, L);
1292- x.pos := SpanFrom(start);
1293- end;
1294-end;
1295-
1296-{ Statements }
1297-
1298-procedure Loop(var lp: TLoop; var old: PLoop);
1299-begin
1300- lp.brk := NoLabel;
1301- lp.base := numDefers;
1302- old := curLoop;
1303- curLoop := @lp;
1304-end;
1305-
1306-{ Runs the deferred statements in force above base, newest first. }
1307-procedure RunDefers(base: longint);
1308-var i: longint;
1309-begin
1310- for i := numDefers - 1 downto base do RunDefer(defers[i]);
1311-end;
1312-
1313-{ Whether what follows "then" is a lone "break;", with no deferred
1314- statement to run on the way out of the loop: the break must be the
1315- branch's last statement, so ";" and then end, elsif or else follow. }
1316-function LoneBreak: boolean;
1317-var st: TScanState;
1318-begin
1319- LoneBreak := false;
1320- if (tok <> sBreak) or (curLoop = nil) or (numDefers <> curLoop^.base) then exit;
1321- SaveScan(st);
1322- Next;
1323- if tok = sSemicolon then begin
1324- Next;
1325- LoneBreak := tok in [sEnd, sElsif, sElse];
1326- end;
1327- RestoreScan(st);
1328-end;
1329-
1330-{ The condition x of if or elsif, and the statements it guards, which
1331- L skips when it is false. "if c then break; end" is one jump out of
1332- the loop when c holds, not one past a jump out. }
1333-procedure ThenPart(var x: TItem; var L: longint);
1334-begin
1335- Expect(sThen);
1336- L := NoLabel; { stays so with a lone break: there is nothing to skip }
1337- if LoneBreak then begin
1338- NoteLine(CurLine, CurCol); { the jump gets the break's line }
1339- CondJumpTrue(x, curLoop^.brk);
1340- Next; Next; { skip "break" and ";" }
1341- ends := true;
1342- end else begin
1343- CondJump(x, L);
1344- Statements;
1345- end;
1346-end;
1347-
1348-{ if, elsif and else: each condition's jump skips its branch to the
1349- next; each branch that doesn't end jumps to the end. A branch that
1350- ends, in return or break, needs no jump past the others, and all of
1351- them ending is told to the caller in the global ends. }
1352-procedure IfStatement(const start: TPos; ind: longint);
1353-var x: TItem; L, endL: longint; all: boolean;
1354-begin
1355- Next;
1356- Expression(x, nil);
1357- ThenPart(x, L);
1358- all := ends;
1359- endL := NoLabel;
1360- while tok = sElsif do begin
1361- if not ends then Jump(endL);
1362- Fix(L);
1363- Next;
1364- Expression(x, nil);
1365- ThenPart(x, L);
1366- all := all and ends;
1367- end;
1368- if tok = sElse then begin
1369- if not ends then Jump(endL);
1370- Fix(L);
1371- Next;
1372- if tok = sIf then elseIf := true;
1373- Statements;
1374- all := all and ends;
1375- end else begin
1376- Fix(L);
1377- all := false;
1378- end;
1379- CloseEnd(start, ind);
1380- Fix(endL);
1381- ends := all;
1382-end;
1383-
1384-{ while c do s end: the test comes after the body, and the loop jumps to
1385- it first, so that a round takes one jump, back to the top if c holds:
1386-
1387- jmp test rather than top: c, jump to out if false
1388- top: s s
1389- test: c, jump to top if true jmp top
1390- out:
1391-
1392- One pass reads c before s: so c is compiled where it is written, for
1393- its messages, and its code taken back (Rewind); then read again, and
1394- compiled, after s (SaveScan, RestoreScan). }
1395-procedure WhileStatement(const start: TPos; ind: longint);
1396-var x: TItem; top, L, test: longint; lp: TLoop; old: PLoop; cond, after: TScanState; m: TCodeMark;
1397-begin
1398- Next;
1399- SaveScan(cond);
1400- MarkCode(m);
1401- Expression(x, nil);
1402- Discard(x);
1403- Rewind(m);
1404- Expect(sDo);
1405- test := NoLabel;
1406- Jump(test);
1407- AlignLoop;
1408- top := pc;
1409- Loop(lp, old);
1410- Statements;
1411- curLoop := old;
1412- SaveScan(after);
1413- RestoreScan(cond);
1414- Fix(test);
1415- NoteLine(CurLine, CurCol);
1416- Expression(x, nil);
1417- ends := (x.mode = mConst) and (x.val <> 0) and (lp.brk = NoLabel); { while true }
1418- if (x.mode = mConst) and (x.typ^.form = fBool) then begin
1419- if x.val <> 0 then JumpBack(top);
1420- end else begin
1421- L := NoLabel;
1422- CondJumpTrue(x, L);
1423- FixTo(L, top);
1424- end;
1425- RestoreScan(after);
1426- CloseEnd(start, ind);
1427- Fix(lp.brk);
1428-end;
1429-
1430-procedure RepeatStatement;
1431-var x: TItem; top, L: longint; lp: TLoop; old: PLoop;
1432-begin
1433- Next;
1434- top := pc;
1435- Loop(lp, old);
1436- Statements;
1437- curLoop := old;
1438- Expect(sUntil);
1439- Expression(x, nil);
1440- ends := (x.mode = mConst) and (x.val = 0) and (lp.brk = NoLabel); { until false }
1441- L := NoLabel;
1442- CondJump(x, L);
1443- FixTo(L, top);
1444- Fix(lp.brk);
1445-end;
1446-
1447-{ for v := a to b by s do ... end, laid out as
1448- v := a; the limit b, in a slot unless it is a constant
1449- if v is past b then goto exit
1450- goto body
1451- top: v := v + s
1452- body: the statements
1453- the end of a round: goto top, or exit (ForNext)
1454- exit:
1455- so that a round of a loop by 1 takes one compare and one jump. }
1456-procedure ForStatement(const start: TPos; ind: longint);
1457-var
1458- o: PObj; v, a, b, s: TItem; step: int64; top, body, bodyL, exitL: longint;
1459- lp: TLoop; old: PLoop;
1460-begin
1461- Next;
1462- if tok <> sIdent then Expected('a name');
1463- o := Lookup(id);
1464- if o = nil then begin NotDeclared(TokPos, id); Fail end;
1465- Named(o);
1466- if (o^.cls <> oVar) or not (o^.typ^.form in [fInt, fEnum]) then
1467- if o^.cls = oVar then
1468- Mark('a for loop needs an integer or enumeration variable, found ' + TypeName(o^.typ))
1469- else Mark(NameOf(id) + ' isn''t a variable');
1470- Next;
1471- Expect(sBecomes);
1472- MakeItem(v, o);
1473- Expression(a, o^.typ);
1474- CoerceExact(a, o^.typ, '');
1475- Assign(v, a);
1476- Expect(sTo);
1477- Expression(b, o^.typ);
1478- CoerceExact(b, o^.typ, '');
1479- { the limit, evaluated once: a constant as it is, else in a slot }
1480- if b.mode <> mConst then TempItem(b, b.typ, ToSlot(b));
1481- step := 1;
1482- if tok = sBy then begin
1483- Next;
1484- Expression(s, nil);
1485- step := ConstValue(s);
1486- if step = 0 then MarkAt(s.pos, 'the step can''t be zero');
1487- end;
1488- Expect(sDo);
1489- exitL := NoLabel;
1490- if step > 0 then ForCmp(o, b, sGtr, exitL) else ForCmp(o, b, sLss, exitL);
1491- bodyL := NoLabel;
1492- Jump(bodyL);
1493- AlignLoop;
1494- top := pc;
1495- ForStep(o, step);
1496- Fix(bodyL);
1497- body := pc;
1498- Loop(lp, old);
1499- Statements;
1500- curLoop := old;
1501- CloseEnd(start, ind);
1502- ForNext(o, b, step, exitL, top, body);
1503- Fix(exitL);
1504- Fix(lp.brk);
1505-end;
1506-
1507-type
1508- TLabels = record
1509- lo, hi: array[0..1023] of int64; { the ranges of the labels so far }
1510- at: array[0..1023] of longint; { where the arm of each starts }
1511- n: longint;
1512- end;
1513-
1514-{ a < b, for values of an integer type, unsigned or not }
1515-function Below(a, b: int64; unsign: boolean): boolean;
1516-begin
1517- if unsign then Below := qword(a) < qword(b) else Below := a < b;
1518-end;
1519-
1520-{ An arm of a match on an integer of type t: its labels, each a
1521- constant or a range, none overlapping another (report section 7.4),
1522- then its statements. No code tests the labels here; Dispatch does,
1523- after the last arm, for which each label notes where its arm starts. }
1524-procedure IntArm(t: PType; var ls: TLabels; var endL: longint);
1525-var lo, hi: TItem; first, i: longint; u: boolean; start: TPos;
1526-begin
1527- u := not t^.signed;
1528- first := ls.n;
1529- repeat
1530- start := TokPos;
1531- Expression(lo, t);
1532- Coerce(lo, t);
1533- ConstValue(lo);
1534- hi := lo;
1535- if tok = sUpto then begin
1536- Next;
1537- Expression(hi, t);
1538- Coerce(hi, t);
1539- ConstValue(hi);
1540- if Below(hi.val, lo.val, u) then MarkAt(SpanFrom(start), 'the range is empty');
1541- end;
1542- for i := 0 to ls.n - 1 do
1543- if not Below(hi.val, ls.lo[i], u) and not Below(ls.hi[i], lo.val, u) then
1544- if lo.val = hi.val then MarkAt(SpanFrom(start), Source(SpanFrom(start)) + ' is in another label too')
1545- else MarkAt(SpanFrom(start), Source(SpanFrom(start)) + ' overlaps another label');
1546- if ls.n > High(ls.lo) then MarkAt(SpanFrom(start), 'more than ' + IntStr(High(ls.lo) + 1) + ' labels in one match');
1547- ls.lo[ls.n] := lo.val; ls.hi[ls.n] := hi.val;
1548- inc(ls.n);
1549- if tok <> sComma then break;
1550- Next;
1551- until false;
1552- Expect(sColon);
1553- for i := first to ls.n - 1 do ls.at[i] := pc;
1554- Statements;
1555- Jump(endL);
1556-end;
1557-
1558-const
1559- MinTable = 4; { fewer labels are tested one by one }
1560- TableDensity = 8; { a table has at most this many entries to a label }
1561-
1562-{ The code that picks the arm, after the last one, which the match's
1563- start jumped to: label by label, as a chain of compares each to its
1564- arm; or, for four or more labels not far apart, a jump table (JumpTable),
1565- which takes the same few instructions for any of them. It is here and
1566- not before the arms, since a table can only be made once every arm's
1567- place is known; an arm is entered by a jump back to it. elseAt is where
1568- the else arm starts, or NoLabel. }
1569-procedure Dispatch(t: PType; p: int64; const ls: TLabels; elseAt: longint; var endL: longint);
1570-var
1571- lo, hi: int64; i, start: longint; v: int64; u: boolean; body: longint;
1572- entry: array[0..1023] of longint;
1573-begin
1574- u := (t^.form = fInt) and not t^.signed;
1575- lo := 0; hi := 0;
1576- if ls.n > 0 then begin
1577- lo := ls.lo[0]; hi := ls.hi[0];
1578- for i := 1 to ls.n - 1 do begin
1579- if Below(ls.lo[i], lo, u) then lo := ls.lo[i];
1580- if Below(hi, ls.hi[i], u) then hi := ls.hi[i];
1581- end;
1582- end;
1583- if (ls.n >= MinTable) and (lo >= low(longint)) and (lo <= high(longint))
1584- and (qword(hi - lo) < qword(TableDensity) * ls.n) and (hi - lo <= High(entry)) then begin
1585- start := JumpTable(p, lo, hi - lo + 1, elseAt, endL);
1586- for v := 0 to hi - lo do
1587- if elseAt <> NoLabel then entry[v] := elseAt else entry[v] := start;
1588- for i := 0 to ls.n - 1 do
1589- for v := ls.lo[i] - lo to ls.hi[i] - lo do entry[v] := ls.at[i];
1590- for v := 0 to hi - lo do TableEntry(start, entry[v]);
1591- exit;
1592- end;
1593- for i := 0 to ls.n - 1 do begin
1594- body := NoLabel;
1595- MatchRange(p, ls.lo[i], ls.hi[i], body);
1596- FixTo(body, ls.at[i]);
1597- end;
1598- if elseAt <> NoLabel then JumpBack(elseAt);
1599-end;
1600-
1601-procedure MatchStatement(const start: TPos; ind: longint);
1602-var
1603- x: TItem; t: PType; c, f, o: PObj; p: int64; L, endL, n, first, disp, elseAt: longint;
1604- seen: array[0..255] of boolean; hasElse, all, byValue: boolean; endAt: TPos; ls: TLabels;
1605-begin
1606- Next;
1607- Expression(x, nil);
1608- if x.typ^.form = fConst then Coerce(x, tI64);
1609- p := MatchBegin(x);
1610- t := x.typ;
1611- Expect(sOf);
1612- FillChar(seen, SizeOf(seen), 0);
1613- hasElse := false;
1614- all := true;
1615- endL := NoLabel;
1616- ls.n := 0;
1617- { an integer or an enumeration is matched by its value, and the arms
1618- are picked by Dispatch, after them; a variant by its tag, arm by arm }
1619- byValue := t^.form in [fInt, fEnum];
1620- disp := NoLabel;
1621- elseAt := NoLabel;
1622- if byValue then Jump(disp);
1623- while tok = sBar do begin
1624- Next;
1625- if hasElse then Mark('else must be the last arm');
1626- if tok = sElse then begin
1627- Next;
1628- Expect(sColon);
1629- elseAt := pc;
1630- Statements;
1631- if byValue then Jump(endL);
1632- hasElse := true;
1633- end else if t^.form = fInt then
1634- IntArm(t, ls, endL)
1635- else begin
1636- first := ls.n;
1637- L := NoLabel;
1638- repeat
1639- if tok <> sIdent then Expected('a case');
1640- c := t^.fields;
1641- while (c <> nil) and (c^.name <> id) do c := c^.next;
1642- if c = nil then Mark(NameOf(id) + ' isn''t a case of ' + TypeName(t));
1643- if (c^.val <= High(seen)) and seen[c^.val] then Mark(NameOf(c^.name) + ' has two arms');
1644- if c^.val <= High(seen) then seen[c^.val] := true;
1645- Next;
1646- if t^.form <> fEnum then begin MatchTag(p, c^.val, L); break end;
1647- { an enumeration's arm may name several, which share its place }
1648- ls.lo[ls.n] := c^.val; ls.hi[ls.n] := c^.val;
1649- inc(ls.n);
1650- if tok <> sComma then break;
1651- Next;
1652- until false;
1653- OpenScope(NewScope);
1654- if tok = sLparen then begin
1655- Next;
1656- f := c^.fields;
1657- n := 0;
1658- repeat
1659- if tok <> sIdent then Expected('a name');
1660- if f = nil then Mark('more names than ' + NameOf(c^.name) + ' has fields');
1661- o := NewObj(oVar, id, f^.typ);
1662- o^.lev := 1; o^.ind := true; o^.isVar := true;
1663- o^.val := p; o^.off := f^.val;
1664- Declare(o);
1665- f := f^.next;
1666- inc(n);
1667- Next;
1668- if tok <> sComma then break;
1669- Next;
1670- until false;
1671- if f <> nil then Mark('name all the fields of ' + NameOf(c^.name) + ', or none');
1672- Expect(sRparen);
1673- end;
1674- Expect(sColon);
1675- for n := first to ls.n - 1 do ls.at[n] := pc;
1676- Statements;
1677- CloseScope;
1678- Jump(endL);
1679- if t^.form <> fEnum then Fix(L);
1680- end;
1681- all := all and ends;
1682- end;
1683- endAt := TokPos;
1684- CloseEnd(start, ind);
1685- ends := all;
1686- if (t^.form = fInt) and not hasElse then
1687- MarkHelp(endAt, 'a match on an integer needs an else arm', 'it may be empty: | else:');
1688- if not hasElse then begin
1689- c := t^.fields;
1690- while c <> nil do begin
1691- if (c^.val > High(seen)) or not seen[c^.val] then MarkAt(endAt, 'no arm for ' + NameOf(c^.name));
1692- c := c^.next;
1693- end;
1694- end;
1695- if byValue then begin
1696- Fix(disp);
1697- Dispatch(t, p, ls, elseAt, endL);
1698- end;
1699- Fix(endL);
1700-end;
1701-
1702-{ What a message calls x: its name n when x is just that name, else what
1703- it is. }
1704-function Subject(const x: TItem; n: longint): shortstring;
1705-begin
1706- if x.pos.b - x.pos.a = length(NameOf(n)) then Subject := NameOf(n)
1707- else if x.mode = mConst then Subject := 'a constant'
1708- else Subject := 'a value';
1709-end;
1710-
1711-{ x, named first n, is a variable the program may assign: not an
1712- array constant, nor any part of one. }
1713-procedure Assignable(const x: TItem; n: longint);
1714-begin
1715- if (x.mode = mConst) and (Subject(x, n) = NameOf(n)) then
1716- MarkAt(x.pos, NameOf(n) + ' is a constant, and can''t be changed');
1717- if (x.mode = mVar) and (x.obj <> nil) and (x.obj^.cls = oConst) then
1718- MarkAt(x.pos, NameOf(x.obj^.name) + ' is a constant, and can''t be changed');
1719- if (x.mode <> mVar) or not x.isVar then MarkAt(x.pos, 'can''t assign to ' + Subject(x, n));
1720-end;
1721-
1722-{ The designator a statement starts with. A variable named whole
1723- before := is assigned, not read: naming it there leaves it as unread
1724- as it was. }
1725-procedure LeftSide(var x: TItem; var called: boolean);
1726-var o: PObj; wasRead: boolean; n: longint;
1727-begin
1728- n := id;
1729- o := Lookup(n);
1730- wasRead := (o <> nil) and o^.read;
1731- Designator(x, called);
1732- if (tok in [sBecomes, sComma]) and (x.pos.b - x.pos.a = length(NameOf(n))) then
1733- o^.read := wasRead;
1734-end;
1735-
1736-{ a, b := f(x): the variables first, left to right, then the call;
1737- then each result to its variable, in order. x is the first variable,
1738- first its name, blank whether it is _. }
1739-procedure MultiAssign(var x: TItem; first: longint; blank: boolean);
1740-var
1741- d: array[0..15] of TItem; dn: array[0..15] of longint; blanks: array[0..15] of boolean;
1742- y, z: TItem; n, i: longint; called: boolean; f: PObj;
1743-begin
1744- n := 0;
1745- d[0] := x;
1746- dn[0] := first;
1747- blanks[0] := blank;
1748- repeat
1749- if not blanks[n] then begin
1750- NotReadOnly(d[n]);
1751- Assignable(d[n], dn[n]);
1752- Pin(d[n]); { works out the address now, so that the call can't change it }
1753- end;
1754- inc(n);
1755- if tok <> sComma then break;
1756- if n > High(d) then Mark('more than ' + IntStr(High(d) + 1) + ' variables in one assignment');
1757- Next;
1758- blanks[n] := tok = sBlank;
1759- if blanks[n] then Next
1760- else begin
1761- dn[n] := id;
1762- LeftSide(d[n], called);
1763- end;
1764- until false;
1765- Expect(sBecomes);
1766- if tok = sTry then begin
1767- TryCall(y);
1768- called := true;
1769- end else Designator(y, called);
1770- if not called or not y.typ^.tuple or (y.typ^.len <> n) then begin
1771- MarkAt(y.pos, 'expected a call with ' + IntStr(n) + ' results');
1772- if y.mode = mWords then CopyToTemp(y);
1773- end;
1774- { two results on the stack: the first is brought to the top, and each
1775- is popped into its variable in turn, as one value; else each is
1776- read from the temporary they came back in }
1777- if y.mode = mWords then Swap;
1778- f := y.typ^.fields;
1779- for i := 0 to n - 1 do begin
1780- z := y;
1781- if y.mode = mWords then begin z.mode := mStack; z.typ := f^.typ end
1782- else Field(z, f);
1783- if blanks[i] then Discard(z)
1784- else begin
1785- CoerceExact(z, d[i].typ, 'several results go to variables of just their types');
1786- Assign(d[i], z);
1787- end;
1788- f := f^.next;
1789- end;
1790-end;
1791-
1792-{ return a, b; or return f(x); with f's several results passed on }
1793-procedure ReturnResults;
1794-var f: PObj; x: TItem;
1795-begin
1796- f := curResult^.fields;
1797- passOn := true;
1798- while f <> nil do begin
1799- Expression(x, f^.typ);
1800- if x.typ^.tuple then begin
1801- if not Same(x.typ, curResult) then
1802- MarkAt(x.pos, 'expected the results ' + TypeName(curResult) + ', found ' + TypeName(x.typ));
1803- ReturnAll(x);
1804- exit;
1805- end;
1806- ReturnField(f, x);
1807- f := f^.next;
1808- if f <> nil then Expect(sComma);
1809- end;
1810-end;
1811-
1812-{ defer s: s is compiled where it stands, as a little subroutine of the
1813- procedure, jumped over; each way out of the statement list calls it. }
1814-procedure Defer;
1815-var L, pos, saved: longint; oldLoop: PLoop; oldDeferring: boolean; start: TPos;
1816-begin
1817- start := TokPos;
1818- Next;
1819- if directDefer then MarkAt(SpanFrom(start), 'defer can''t be deferred');
1820- if numDefers > High(defers) then MarkAt(SpanFrom(start), 'more than ' + IntStr(High(defers) + 1) + ' deferred statements in one procedure');
1821- L := NoLabel;
1822- pos := DeferBegin(L, saved);
1823- oldLoop := curLoop; oldDeferring := deferring;
1824- curLoop := nil;
1825- deferring := true;
1826- directDefer := true;
1827- Statement;
1828- directDefer := false;
1829- curLoop := oldLoop; deferring := oldDeferring;
1830- DeferEnd(L, saved);
1831- defers[numDefers] := pos;
1832- inc(numDefers);
1833-end;
1834-
1835-{ Whether the expression of x := ..., which starts at the current
1836- symbol, is x changed by adding to it, taking from it or its bits:
1837- x + e, x - e, x | e or x xor e, with x nowhere in e, so that it can be
1838- worked out in x's own register, if x is in one (gen's inPlace). }
1839-function ChangesItself(const x: TItem): boolean;
1840-var st: TScanState; wasSkipping: boolean; d: longint;
1841-begin
1842- ChangesItself := false;
1843- if (x.mode <> mVar) or (x.base <> bReg) or (x.typ^.form = fSlice) or (tok <> sIdent) or (id <> x.obj^.name) then exit;
1844- SaveScan(st);
1845- wasSkipping := skipping;
1846- skipping := true; { its slips are told when it is compiled }
1847- Next;
1848- if tok in [sPlus, sMinus, sBar, sXor] then begin
1849- ChangesItself := true;
1850- d := 0;
1851- while not ((d = 0) and (tok in [sSemicolon, sEnd])) and (tok <> sEof) do begin
1852- if (tok = sIdent) and (id = x.obj^.name) then ChangesItself := false;
1853- if tok in [sLparen, sLbrak, sLbrace] then inc(d)
1854- else if tok in [sRparen, sRbrak, sRbrace] then dec(d);
1855- Next;
1856- end;
1857- end;
1858- RestoreScan(st);
1859- skipping := wasSkipping;
1860-end;
1861-
1862-procedure OneStatement;
1863-var x, y: TItem; called: boolean; m: int64; c: TCall; start: TPos; first, n, i: longint; k: TKind;
1864-begin
1865- start := TokPos;
1866- first := id;
1867- NoteLine(CurLine, CurCol);
1868- m := TempMark;
1869- ends := false;
1870- case tok of
1871- sIdent: begin
1872- LeftSide(x, called);
1873- if tok = sBecomes then begin
1874- NotReadOnly(x);
1875- Assignable(x, first);
1876- Next;
1877- if ChangesItself(x) then inPlace := x.chunk;
1878- Expression(y, x.typ);
1879- inPlace := -1;
1880- Assign(x, y);
1881- end else if tok = sComma then
1882- MultiAssign(x, first, false)
1883- else if not called then begin
1884- if (x.mode = mProc) or ((x.mode in [mVar, mStack]) and (x.typ^.form = fProc)) then begin
1885- BeginCall(c, x);
1886- EndCall(c, x);
1887- Discard(x);
1888- end else if tok = sEql then
1889- MarkHelp(x.pos, Subject(x, first) + ' isn''t a statement', 'assignment is written :=')
1890- else MarkAt(x.pos, Subject(x, first) + ' isn''t a statement');
1891- end else begin
1892- if (x.mode <> mNone) and (numDrops <= High(drops)) then begin
1893- drops[numDrops].at := x.pos;
1894- if x.typ^.tuple then drops[numDrops].n := x.typ^.len else drops[numDrops].n := 1;
1895- inc(numDrops);
1896- end;
1897- Discard(x);
1898- end;
1899- end;
1900- sBlank: begin
1901- Next;
1902- if tok = sComma then MultiAssign(x, 0, true)
1903- else begin
1904- Expect(sBecomes);
1905- Expression(x, nil);
1906- { evaluated and dropped: a single value is loaded, so that a
1907- volatile one is read }
1908- if (x.mode in [mType, mBuiltin, mNone, mCase]) or (x.mode <> mStr) and not IsAggregate(x.typ) then
1909- Value(x);
1910- Discard(x);
1911- end;
1912- end;
1913- sIf: IfStatement(start, Indent);
1914- sWhile: WhileStatement(start, Indent);
1915- sRepeat: RepeatStatement;
1916- sFor: ForStatement(start, Indent);
1917- sMatch: MatchStatement(start, Indent);
1918- sReturn: begin
1919- Next;
1920- if deferring then MarkAt(SpanFrom(start), 'return can''t leave a deferred statement');
1921- if tok = sSemicolon then begin
1922- RunDefers(0);
1923- ReturnNone;
1924- end else begin
1925- if (curResult <> nil) and curResult^.tuple then ReturnResults
1926- else begin
1927- Expression(x, curResult);
1928- ReturnValue(x);
1929- end;
1930- { the result, one value or two words on top, waits in the frame
1931- while the deferred statements run }
1932- if (numDefers > 0) and (curResult <> nil) and not BehindPointer(curResult) then begin
1933- n := 1; k := KindOf(curResult);
1934- if InTwoRegs(curResult) then begin n := 2; k := kWord end;
1935- if deferSlot = 0 then deferSlot := AllocPerm(16, 8);
1936- for i := n - 1 downto 0 do PopVar(FrameAdr(deferSlot + 8 * i), 8);
1937- RunDefers(0);
1938- for i := 0 to n - 1 do PushVar(FrameAdr(deferSlot + 8 * i), 8, false, k);
1939- end else RunDefers(0);
1940- ReturnJump;
1941- ends := true;
1942- end;
1943- end;
1944- sBreak: begin
1945- Next;
1946- if curLoop = nil then MarkAt(SpanFrom(start), 'break outside a loop');
1947- RunDefers(curLoop^.base);
1948- Jump(curLoop^.brk);
1949- end;
1950- sDefer: Defer;
1951- sTry: begin
1952- TryCall(x);
1953- if (x.mode <> mNone) and (numDrops <= High(drops)) then begin
1954- drops[numDrops].at := x.pos;
1955- if x.typ^.tuple then drops[numDrops].n := x.typ^.len else drops[numDrops].n := 1;
1956- inc(numDrops);
1957- end;
1958- Discard(x);
1959- end;
1960- sArrow: MarkHelp(TokPos, 'a statement starts with a name', 'convert into a pointer variable, then assign through that');
1961- else if AtLineStart then EndMissing(MissingPos, 'expected "end", found ' + Found)
1962- else Expected('a statement');
1963- end;
1964- ReleaseTemps(m);
1965-end;
1966-
1967-procedure Statement;
1968-var r: TRecover; m: int64;
1969-begin
1970- m := TempMark;
1971- Guard(r);
1972- if setjmp(r.jb) = 0 then begin
1973- OneStatement;
1974- skipped := false;
1975- end else begin
1976- Restore(r);
1977- { a statement never starts a line: this is the next declaration }
1978- if AtLineStart or not SkipConstruct then GiveUp(r);
1979- ReleaseTemps(m);
1980- skipped := true;
1981- end;
1982- Unguard(r);
1983-end;
1984-
1985-procedure Statements;
1986-var base: longint; old: boolean;
1987-begin
1988- base := numDefers;
1989- old := directDefer;
1990- directDefer := false;
1991- ends := false;
1992- while not (tok in [sEnd, sElse, sElsif, sUntil, sBar, sEof]) do begin
1993- Statement;
1994- if not skipped or (tok = sSemicolon) then Expect(sSemicolon);
1995- end;
1996- RunDefers(base);
1997- numDefers := base;
1998- directDefer := old;
1999-end;
2000-
2001-{ Declarations }
2002-
2003-{ In a file read for its interface only: skip a procedure's body, from
2004- its local declarations to the end that closes it. }
2005-procedure SkipBody;
2006-var d: longint; sawBegin: boolean;
2007-begin
2008- d := 0;
2009- sawBegin := false;
2010- repeat
2011- case tok of
2012- sBegin: begin if d = 0 then sawBegin := true; inc(d) end;
2013- sIf, sWhile, sFor, sMatch, sRecord, sVariant: inc(d);
2014- sEnd: begin
2015- dec(d);
2016- if (d = 0) and sawBegin then begin Next; exit end;
2017- end;
2018- sEof: Expected('"end"');
2019- end;
2020- Next;
2021- until false;
2022-end;
2023-
2024-procedure Declarations(top: boolean); forward;
2025-
2026-{ How Rt shows a variable of o's type in the trap report: 1 a signed
2027- integer, 2 an unsigned one, 3 a BOOL, 4 an address, 5 a real; plus
2028- its size times 16, and 256 if the frame holds its address, or 512
2029- times 1 + i if it is in register VarRegs[i]; 0 if it isn't shown. }
2030-function VarKind(o: PObj): longint;
2031-var k, i: longint;
2032-begin
2033- case o^.typ^.form of
2034- fInt: k := 2 - ord(o^.typ^.signed);
2035- fEnum, fSet: k := 2;
2036- fBool: k := 3;
2037- fPtr, fProc, fError: k := 4;
2038- fReal: k := 5;
2039- else exit(0);
2040- end;
2041- VarKind := k + o^.typ^.size * 16 + ord(o^.ind) * 256;
2042- for i := 0 to High(ShownRegs) do
2043- if o^.reg = ShownRegs[i] then VarKind := k + o^.typ^.size * 16 + (i + 1) * 512;
2044-end;
2045-
2046-{ Whether variable o could live in registers: a single value, a real
2047- in an xmm register, or a slice, in two, that isn't C's }
2048-function RegFit(o: PObj): boolean;
2049-begin
2050- RegFit := (o^.cls = oVar) and not o^.ind and not o^.ext
2051- and ((o^.typ^.form in [fInt, fBool, fEnum, fPtr, fProc, fError, fSlice, fReal])
2052- or (o^.typ^.form = fSet) and (o^.typ^.size <= 8));
2053-end;
2054-
2055-{ The first local of the procedure being compiled. Locals are chained
2056- by link in the order declared, the module's own first; before is the
2057- last one declared before the procedure's, or nil if there was none. }
2058-function FirstLocal(before: PObj): PObj;
2059-begin
2060- if before = nil then FirstLocal := curModule^.locals else FirstLocal := before^.link;
2061-end;
2062-
2063-{ Puts the busiest variables of the procedure, whose parameters are
2064- params and whose locals follow before, in registers: read ahead from
2065- its "begin" to its end, a use counts 1, in a loop 4, in two 16, in
2066- three or more 64, and a variable ADR is taken of can't have one. A register costs a save
2067- and a restore, so a variable used less than three times keeps its
2068- place in memory. A slice takes two, its pointer's and its length's;
2069- a real one of the xmm registers, stored and loaded again around each
2070- call, as System V keeps none through one. In a procedure that names no procedure, so calls nothing, the
2071- parameters that arrive in the registers no call needs stay there
2072- (KeepArrived), at no cost. }
2073-procedure ChooseRegs(params, before: PObj);
2074-var
2075- cand: array[0..63] of PObj; weight: array[0..63] of longint;
2076- isLoop: array[0..255] of boolean;
2077- n, i, k, kx, d, loops, best, need: longint; o, q, qual: PObj; st: TScanState;
2078- afterDot, wasSkipping, leaf: boolean;
2079-
2080- function Candidate(name: longint): longint;
2081- var j: longint;
2082- begin
2083- for j := 0 to n - 1 do if cand[j]^.name = name then exit(j);
2084- Candidate := -1;
2085- end;
2086-
2087- procedure Add(o: PObj);
2088- begin
2089- if RegFit(o) and (n <= High(cand)) then begin cand[n] := o; weight[n] := 0; inc(n) end;
2090- end;
2091-
2092- { Whether naming o may make a call: a procedure, a procedure variable,
2093- or NEW, SYSCALL or COPY, which use the registers a call would }
2094- function Calls(o: PObj): boolean;
2095- begin
2096- Calls := (o <> nil) and ((o^.cls = oProc) or (o^.cls = oVar) and (o^.typ^.form = fProc)
2097- or (o^.cls = oBuiltin) and ((o^.val = bNew) or (o^.val = bSyscall) or (o^.val = bCopy)));
2098- end;
2099-
2100-begin
2101- n := 0;
2102- o := params;
2103- while o <> nil do begin Add(o); o := o^.next end;
2104- o := FirstLocal(before);
2105- while o <> nil do begin Add(o); o := o^.link end;
2106- if n > 0 then begin
2107- SaveScan(st);
2108- wasSkipping := skipping;
2109- skipping := true; { its slips are told when it is compiled }
2110- d := 0; loops := 0; afterDot := false; leaf := true; qual := nil;
2111- repeat
2112- { a name, or a module's name and one of its exports, that calls }
2113- if (tok = sIdent) and not afterDot then begin
2114- q := Lookup(id);
2115- if Calls(q) then leaf := false;
2116- qual := nil;
2117- if (q <> nil) and (q^.cls = oModule) then qual := q;
2118- end else if (tok = sIdent) and (qual <> nil) then begin
2119- if (qual^.module = nil) or Calls(Find(qual^.module^.scope, id)) then leaf := false;
2120- qual := nil;
2121- end;
2122- case tok of
2123- sBegin, sIf, sMatch, sWhile, sFor, sRepeat:
2124- if d < High(isLoop) then begin
2125- inc(d);
2126- isLoop[d] := tok in [sWhile, sFor, sRepeat];
2127- if isLoop[d] then inc(loops);
2128- end;
2129- sEnd, sUntil: begin
2130- if isLoop[d] then dec(loops);
2131- dec(d);
2132- end;
2133- sIdent:
2134- if id = nameAdr then begin
2135- Next;
2136- if tok = sLparen then Next;
2137- { a hugely negative weight bars it from a register, whatever
2138- its uses add }
2139- if (tok = sIdent) and (Candidate(id) >= 0) then weight[Candidate(id)] := low(longint) div 2;
2140- end else if not afterDot and (Candidate(id) >= 0) then begin
2141- k := Candidate(id);
2142- if loops > 2 then inc(weight[k], 64) else inc(weight[k], 1 shl (2 * loops));
2143- end;
2144- end;
2145- afterDot := tok = sPeriod; { a name after a dot is a field, not a variable }
2146- if (d > 0) and (tok <> sEof) then Next;
2147- until (d = 0) or (tok = sEof);
2148- RestoreScan(st);
2149- skipping := wasSkipping;
2150- if leaf then begin
2151- o := params;
2152- while o <> nil do begin
2153- k := Candidate(o^.name);
2154- if (k >= 0) and (weight[k] >= 0) then KeepArrived(o); { a candidate whose ADR isn't taken }
2155- o := o^.next;
2156- end;
2157- end;
2158- { a slice's weight is shared by its two registers }
2159- for i := 0 to n - 1 do
2160- if cand[i]^.typ^.form = fSlice then weight[i] := weight[i] div 2;
2161- { the heaviest, each used at least three times a register, take the
2162- five registers in turn, while there are enough for each, and the
2163- reals the four xmm registers of XVarRegs }
2164- k := 0; kx := 0;
2165- repeat
2166- best := -1;
2167- for i := 0 to n - 1 do
2168- if (cand[i]^.reg = 0) and (weight[i] >= 3) and ((best < 0) or (weight[i] > weight[best])) then best := i;
2169- if best < 0 then break;
2170- need := 1 + ord(cand[best]^.typ^.form = fSlice);
2171- if cand[best]^.typ^.form = fReal then begin
2172- if kx < 4 then begin cand[best]^.reg := XVarRegs[kx]; inc(kx) end
2173- else weight[best] := 0;
2174- end else if k + need <= 5 then begin
2175- cand[best]^.reg := VarRegs[k];
2176- if need = 2 then cand[best]^.reg2 := VarRegs[k + 1];
2177- inc(k, need);
2178- end else weight[best] := 0; { too big for what is left }
2179- until false;
2180- end;
2181-end;
2182-
2183-{ The registers the variables of the procedure are in, as bits: bit i
2184- is VarRegs[i], bit XBit + i XVarRegs[i] }
2185-function RegsOf(params, before: PObj): longint;
2186-var o: PObj; m, k: longint;
2187-begin
2188- m := 0;
2189- o := params;
2190- while o <> nil do begin
2191- for k := 0 to 4 do if (o^.reg = VarRegs[k]) or (o^.reg2 = VarRegs[k]) then m := m or (1 shl k);
2192- for k := 0 to 3 do if o^.reg = XVarRegs[k] then m := m or (1 shl (XBit + k));
2193- o := o^.next;
2194- end;
2195- o := FirstLocal(before);
2196- while o <> nil do begin
2197- if o^.cls = oVar then begin
2198- for k := 0 to 4 do if (o^.reg = VarRegs[k]) or (o^.reg2 = VarRegs[k]) then m := m or (1 shl k);
2199- for k := 0 to 3 do if o^.reg = XVarRegs[k] then m := m or (1 shl (XBit + k));
2200- end;
2201- o := o^.link;
2202- end;
2203- RegsOf := m;
2204-end;
2205-
2206-{ Gives each local not in a register its slot in the frame, the slots
2207- the prologue zeroes, and then tells gen which registers the
2208- variables are in. A variable in a register has no slot: it starts at
2209- zero in its register, and the trap report finds it there. }
2210-procedure PlaceLocals(params, before: PObj);
2211-var o: PObj;
2212-begin
2213- ResetLocals;
2214- o := FirstLocal(before);
2215- while o <> nil do begin
2216- if (o^.cls = oVar) and (o^.reg = 0) then o^.val := AllocPerm(o^.typ^.size, o^.typ^.align)
2217- else if (o^.cls = oVar) and (o^.reg >= XmmVar) then begin
2218- o^.val := AllocPerm(8, 8);
2219- XHome(o^.reg, o^.val);
2220- end;
2221- o := o^.link;
2222- end;
2223- o := params;
2224- while o <> nil do begin
2225- if o^.reg >= XmmVar then XHome(o^.reg, o^.val);
2226- o := o^.next;
2227- end;
2228- UseRegs(RegsOf(params, before));
2229-end;
2230-
2231-procedure Body(p: PObj; sig: PType; line: longint);
2232-var
2233- q, params, last, o, before: PObj; old: PType; st: TScanState;
2234- mark: TCodeMark; drops0, errs: longint;
2235-begin
2236- OpenScope(NewScope);
2237- params := nil; last := nil;
2238- q := sig^.fields;
2239- while q <> nil do begin
2240- o := NewObj(oVar, q^.name, q^.typ);
2241- o^.pos := q^.pos;
2242- o^.lev := 1;
2243- o^.isVar := q^.isVar;
2244- o^.param := true;
2245- if last = nil then params := o else last^.next := o;
2246- last := o;
2247- q := q^.next;
2248- end;
2249- BeginProc(sig, params);
2250- deferSlot := 0;
2251- o := params;
2252- while o <> nil do begin
2253- q := o^.next;
2254- Declare(o);
2255- o := q;
2256- end;
2257- curProc := p;
2258- before := curModule^.lastLocal;
2259- Declarations(false);
2260- ChooseRegs(params, before);
2261- PlaceLocals(params, before);
2262- { the body, made again if a variable in a register must be in memory }
2263- SaveScan(st);
2264- MarkCode(mark); drops0 := numDrops; errs := errors;
2265- old := curResult;
2266- repeat
2267- demoted := false;
2268- Expect(sBegin);
2269- curResult := sig^.base;
2270- EnterBody(p^.chunk, line);
2271- stray := false; elseIf := false; deferSlot := 0;
2272- Statements;
2273- p^.openEnd := (curResult <> nil) and not ends;
2274- NoteLine(CurLine, CurCol);
2275- Expect(sEnd);
2276- if not (demoted or lost) or (errors <> errs) then break;
2277- { a parameter kept where it arrived goes to memory: a call or a copy
2278- wanted its register }
2279- if lost then begin
2280- o := params;
2281- while o <> nil do begin
2282- if KeptIn(o) then begin o^.reg := 0; o^.reg2 := 0 end;
2283- o := o^.next;
2284- end;
2285- end;
2286- numDrops := drops0;
2287- Redo(mark);
2288- PlaceLocals(params, before);
2289- RestoreScan(st);
2290- until false;
2291- EndProc(p^.chunk, p^.openEnd);
2292- { its parameters and variables, for the trap report }
2293- o := FirstLocal(before);
2294- q := params;
2295- while q <> nil do begin
2296- if VarKind(q) <> 0 then NoteVar(p^.chunk, q^.name, q^.val, VarKind(q));
2297- q := q^.next;
2298- end;
2299- while o <> nil do begin
2300- if (o^.cls = oVar) and (VarKind(o) <> 0) then NoteVar(p^.chunk, o^.name, o^.val, VarKind(o));
2301- o := o^.link;
2302- end;
2303- curResult := old;
2304- curProc := nil;
2305- CloseScope;
2306-end;
2307-
2308-{ An integer constant in a code procedure, for the assembler: a whole
2309- expression, or a single factor where an expression would read on
2310- too far }
2311-function AsmConst(whole: boolean): int64;
2312-var x: TItem;
2313-begin
2314- if whole then exit(ConstExpr);
2315- Factor(x, nil);
2316- if not IsInt(x.typ) then MarkAt(x.pos, 'expected an integer constant, found ' + What(x));
2317- AsmConst := ConstValue(x);
2318-end;
2319-
2320-procedure CodeBody(p: PObj; sig: PType; const at: TPos);
2321-var q: PObj; ni, nf: longint;
2322-begin
2323- ni := 0; nf := 0;
2324- q := sig^.fields;
2325- while q <> nil do begin
2326- if not q^.isVar and (q^.typ^.form = fSlice) then inc(ni, 2) { address, then length }
2327- else begin
2328- if not q^.isVar and not IsScalar(q^.typ) then
2329- MarkAt(at, 'a code procedure takes integers, BOOL, reals, pointers, procedures and slices');
2330- if (q^.typ^.form = fReal) and not q^.isVar then inc(nf) else inc(ni);
2331- end;
2332- q := q^.next;
2333- end;
2334- if (ni > 6) or (nf > 8) or sig^.variadic then MarkAt(at, 'too many parameters for a code procedure');
2335- if sig^.base <> nil then
2336- if sig^.base^.tuple then begin
2337- q := sig^.base^.fields;
2338- if (sig^.base^.len <> 2) or (q^.typ^.size <> 8) or (q^.next^.typ^.size <> 8)
2339- or not IsScalar(q^.typ) or not IsScalar(q^.next^.typ)
2340- or (q^.typ^.form = fReal) or (q^.next^.typ^.form = fReal) then
2341- MarkAt(at, 'a code procedure returns two results only in rax and rdx');
2342- end else if not IsScalar(sig^.base) and (sig^.base^.form <> fSlice) then
2343- MarkAt(at, 'a code procedure returns a single value');
2344- CodeProc(p^.chunk, @AsmConst);
2345- Expect(sEnd);
2346-end;
2347-
2348-procedure ProcDecl;
2349-var n, line: longint; exp: boolean; sig: PType; p: PObj; at: TPos;
2350-begin
2351- InstancesFor(false);
2352- line := CurLine;
2353- Next;
2354- IdentDef(n, exp, at);
2355- sig := Signature;
2356- Expect(sSemicolon);
2357- p := Find(TopScope, n);
2358- if (p <> nil) and (p^.cls = oProc) and p^.fwd then begin
2359- if not Same(p^.typ, sig) then begin
2360- Error(at, NameOf(n) + ' doesn''t have the signature it was declared forward with');
2361- Note(p^.pos, 'the signature is here');
2362- Fail;
2363- end;
2364- if tok = sForward then Mark(NameOf(n) + ' is declared forward twice');
2365- p^.exported := p^.exported or exp;
2366- end else begin
2367- p := NewObj(oProc, n, sig);
2368- p^.pos := at;
2369- p^.exported := exp;
2370- if (curModule^.name = nameRt) and not checkMode and (n = nameFail) then p^.chunk := rtFail
2371- else p^.chunk := NewChunk(secText, curModule^.sname, n);
2372- Declare(p);
2373- end;
2374- if tok = sForward then begin
2375- Next;
2376- p^.fwd := true;
2377- exit;
2378- end;
2379- p^.fwd := false;
2380- if tok = sCode then begin
2381- Next;
2382- p^.isCode := true;
2383- CodeBody(p, sig, at);
2384- end else if checkMode then SkipBody else Body(p, sig, line);
2385- if tok = sIdent then begin
2386- if id = curModule^.name then EndMissing(TokPos, NameOf(n) + ' has no "end": this one closes the module')
2387- else if id <> n then EndMissing(TokPos, 'expected ' + NameOf(n) + ', found ' + NameOf(id));
2388- Next;
2389- end;
2390-end;
2391-
2392-{ An extern procedure or variable: C's, reached through the quadword
2393- that holds its address. }
2394-procedure ExternDecl;
2395-var n: longint; exp: boolean; o, q: PObj; t: PType; at: TPos;
2396-begin
2397- Next;
2398- curModule^.usesC := true;
2399- if tok = sProc then begin
2400- Next;
2401- IdentDef(n, exp, at);
2402- WillDeclare(n);
2403- inExtern := true;
2404- t := Signature;
2405- inExtern := false;
2406- q := t^.fields;
2407- while q <> nil do begin
2408- if q^.isVar or not IsScalar(q^.typ) then
2409- MarkAt(at, 'C takes integers, BOOL, reals, pointers and procedures');
2410- q := q^.next;
2411- end;
2412- if (t^.base <> nil) and not IsScalar(t^.base) then MarkAt(at, 'C returns a single value');
2413- o := NewObj(oProc, n, t);
2414- end else begin
2415- if tok <> sVar then Expected('"proc" or "var"');
2416- Next;
2417- IdentDef(n, exp, at);
2418- WillDeclare(n);
2419- Expect(sColon);
2420- declExported := exp;
2421- t := ParseType;
2422- declExported := false;
2423- o := NewObj(oVar, n, t);
2424- end;
2425- o^.pos := at;
2426- o^.exported := exp;
2427- o^.ext := true;
2428- o^.chunk := ExternChunk(n);
2429- Declare(o);
2430-end;
2431-
2432-{ An array or record constant: a literal of constants, which become
2433- the bytes of a read-only chunk, as a string constant's do (report
2434- section 4). An address in it, of a string, an array constant, a
2435- procedure or an ERROR, waits in fixes until the chunk is made, then
2436- is a fixup the linker patches. The bytes are the compiler's own
2437- machine's, little-endian, as the target's are. }
2438-var
2439- constBytes: PBytes;
2440- fixes: array[0..4095] of record off: int64; chunk: longint; end;
2441- numFixes: longint;
2442-
2443-procedure ConstFix(off: int64; chunk: longint);
2444-begin
2445- if numFixes > High(fixes) then MarkAt(TokPos, 'more than ' + IntStr(High(fixes) + 1) + ' addresses in one constant');
2446- fixes[numFixes].off := off;
2447- fixes[numFixes].chunk := chunk;
2448- inc(numFixes);
2449-end;
2450-
2451-{ The part of type t at offset off of the constant }
2452-procedure ConstPart(t: PType; off: int64);
2453-var e: TItem; f: PObj; k: int64; r: single; start: TPos;
2454-begin
2455- start := TokPos;
2456- if (t^.form = fArray) and (tok = sLbrak) then begin
2457- Next;
2458- k := 0;
2459- if tok <> sRbrak then
2460- repeat
2461- if k < t^.len then ConstPart(t^.base, off + k * t^.base^.size)
2462- else ConstPart(t^.base, off);
2463- inc(k);
2464- if tok <> sComma then break;
2465- Next;
2466- until false;
2467- Expect(sRbrak);
2468- if k <> t^.len then MarkAt(SpanFrom(start), 'expected ' + IntStr(t^.len) + ' elements, found ' + IntStr(k));
2469- exit;
2470- end;
2471- if (t^.form = fRecord) and not t^.tuple and (tok = sLbrace) then begin
2472- Next;
2473- if tok <> sRbrace then
2474- repeat
2475- if tok <> sIdent then Expected('a field');
2476- f := FieldOf(t);
2477- Next;
2478- Expect(sColon);
2479- ConstPart(f^.typ, off + f^.val);
2480- if tok <> sComma then break;
2481- Next;
2482- until false;
2483- Expect(sRbrace);
2484- exit;
2485- end;
2486- Expression(e, t);
2487- if (e.mode = mStr) and ((t^.form = fSlice) or (t^.form = fArray)) and (t^.base = tU8) then begin
2488- if t^.form = fSlice then begin
2489- ConstFix(off, e.chunk);
2490- Move(e.val, constBytes^[off + 8], 8);
2491- end else if e.val > t^.len then MarkAt(e.pos, 'the string is longer than ' + TypeName(t))
2492- else Move(rodata^[chunks^[e.chunk].start], constBytes^[off], e.val);
2493- end else if t^.form = fSlice then begin
2494- if (e.mode <> mVar) or (e.obj = nil) or (e.obj^.cls <> oConst) or (e.typ^.form <> fArray)
2495- or (e.pos.b - e.pos.a <> length(NameOf(e.obj^.name))) or not Same(e.typ^.base, t^.base) then
2496- MarkAt(e.pos, 'a constant slice is a string or an array constant of its elements, found ' + What(e));
2497- ConstFix(off, e.chunk);
2498- Move(e.typ^.len, constBytes^[off + 8], 8);
2499- end else if t^.form = fVariant then MarkAt(e.pos, 'a constant holds no variant')
2500- else if t^.form in [fArray, fRecord] then MarkAt(e.pos, 'expected a literal of ' + TypeName(t))
2501- else begin
2502- Coerce(e, t);
2503- if (e.mode = mProc) and not e.obj^.ext then ConstFix(off, e.obj^.chunk)
2504- else if e.mode <> mConst then MarkAt(e.pos, 'expected a constant, found ' + What(e))
2505- else if (t^.form = fError) and (e.val > 0) then ConstFix(off, e.val - 1)
2506- else if (t^.form = fPtr) and (e.val <> 0) then MarkAt(e.pos, 'a constant pointer is nil')
2507- else if (t^.form = fReal) and (t^.size = 4) then begin
2508- r := RealOf(e);
2509- Move(r, constBytes^[off], 4);
2510- end else Move(e.val, constBytes^[off], t^.size);
2511- end;
2512-end;
2513-
2514-{ The chunk of n, a constant of type t whose literal is next }
2515-function AggregateConst(t: PType; n: longint): longint;
2516-var c, i: longint;
2517-begin
2518- constBytes := AllocMem(t^.size + 8);
2519- numFixes := 0;
2520- ConstPart(t, 0);
2521- c := NewChunk(secRodata, curModule^.sname, n);
2522- SetData(c, constBytes, t^.size, t^.align);
2523- for i := 0 to numFixes - 1 do AddDataFixup(c, fixes[i].off, fixes[i].chunk, 0);
2524- FreeMem(constBytes);
2525- AggregateConst := c;
2526-end;
2527-
2528-procedure ConstDecl(top: boolean);
2529-var n: longint; exp: boolean; x: TItem; o: PObj; t: PType; start, at: TPos;
2530-begin
2531- IdentDef(n, exp, at);
2532- WillDeclare(n);
2533- t := nil;
2534- if tok = sColon then begin
2535- Next;
2536- start := TokPos;
2537- t := ParseType;
2538- if (t <> tError) and not ((t^.form = fArray) or (t^.form = fRecord) and not t^.tuple) then
2539- MarkAt(SpanFrom(start), 'only an ERROR, an array or a record constant has a type');
2540- end;
2541- Expect(sEql);
2542- if (t <> nil) and (t^.form in [fArray, fRecord]) then begin
2543- o := NewObj(oConst, n, t);
2544- o^.chunk := AggregateConst(t, n);
2545- o^.pos := at;
2546- o^.exported := exp and top;
2547- Declare(o);
2548- Expect(sSemicolon);
2549- exit;
2550- end;
2551- Expression(x, nil);
2552- o := NewObj(oConst, n, x.typ);
2553- o^.pos := at;
2554- o^.exported := exp and top;
2555- if t = tError then begin
2556- o^.typ := tError;
2557- o^.val := ErrorChunk(x, curModule^.sname, n) + 1;
2558- end else if x.mode = mStr then begin o^.val := x.val; o^.chunk := x.chunk end
2559- else o^.val := ConstValue(x);
2560- Declare(o);
2561- Expect(sSemicolon);
2562-end;
2563-
2564-procedure TypeDecl(top: boolean);
2565-var n: longint; exp: boolean; o: PObj; t: PType; at: TPos;
2566-begin
2567- IdentDef(n, exp, at);
2568- WillDeclare(n);
2569- Expect(sEql);
2570- declExported := exp and top;
2571- inTypes := true;
2572- t := ParseType;
2573- o := NewObj(oType, n, t);
2574- o^.pos := at;
2575- o^.exported := exp and top;
2576- if t^.obj = nil then t^.obj := o;
2577- Declare(o);
2578- Expect(sSemicolon);
2579-end;
2580-
2581-procedure VarDecl(top: boolean);
2582-var
2583- i, k: longint; o: PObj; t: PType;
2584- names: array[0..63] of longint; exps: array[0..63] of boolean;
2585- poss: array[0..63] of TPos;
2586-begin
2587- k := 0;
2588- repeat
2589- if k > High(names) then Mark('more than ' + IntStr(High(names) + 1) + ' names in one declaration');
2590- IdentDef(names[k], exps[k], poss[k]);
2591- WillDeclare(names[k]);
2592- inc(k);
2593- if tok <> sComma then break;
2594- Next;
2595- until false;
2596- Expect(sColon);
2597- declExported := top and exps[0];
2598- t := ParseType;
2599- declExported := false;
2600- for i := 0 to k - 1 do begin
2601- o := NewObj(oVar, names[i], t);
2602- o^.pos := poss[i];
2603- o^.exported := exps[i] and top;
2604- o^.isVar := false;
2605- if top then begin
2606- o^.lev := 0;
2607- o^.chunk := NewChunk(secBss, curModule^.sname, names[i]);
2608- SetBss(o^.chunk, t^.size, t^.align);
2609- end else
2610- o^.lev := 1; { its slot comes from PlaceLocals, if it needs one }
2611- Declare(o);
2612- end;
2613- Expect(sSemicolon);
2614-end;
2615-
2616-{ After a procedure had an error: its name is poison if it wasn't
2617- declared, and reading goes on after the "end Name;" that closes it,
2618- or at the next procedure if that is missing }
2619-procedure SkipProc;
2620-var st: TScanState;
2621-begin
2622- Next;
2623- if (tok = sIdent) and (Find(TopScope, id) = nil) then Poison(id);
2624- repeat
2625- repeat Next until AtLineStart or (tok = sEof);
2626- if tok in [sProc, sExtern, sEof] then exit;
2627- if tok = sEnd then begin
2628- SaveScan(st);
2629- Next;
2630- if tok = sIdent then Next;
2631- if tok = sSemicolon then begin Next; exit end;
2632- RestoreScan(st);
2633- exit;
2634- end;
2635- until false;
2636-end;
2637-
2638-{ One declaration, of the kind k, as a recovery point }
2639-procedure Declaration(k: TSym; top: boolean);
2640-var r: TRecover;
2641-begin
2642- Guard(r);
2643- numDeclaring := 0;
2644- if setjmp(r.jb) = 0 then
2645- case k of
2646- sConst: ConstDecl(top);
2647- sType: TypeDecl(top);
2648- sVar: VarDecl(top);
2649- sProc: begin
2650- if not top then Mark('procedures don''t nest');
2651- ProcDecl;
2652- Expect(sSemicolon);
2653- end;
2654- sExtern: begin
2655- if not top then Mark('extern is only for the top of a module');
2656- ExternDecl;
2657- Expect(sSemicolon);
2658- end;
2659- end
2660- else begin
2661- Restore(r);
2662- if k = sProc then SkipProc else SkipDeclaration;
2663- end;
2664- Unguard(r);
2665-end;
2666-
2667-procedure Declarations(top: boolean);
2668-var i: longint; o: PObj; k: TSym;
2669-begin
2670- repeat
2671- k := tok;
2672- case k of
2673- sConst, sVar: begin
2674- Next;
2675- while tok = sIdent do Declaration(k, top);
2676- end;
2677- sType: begin
2678- Next;
2679- numFwd := 0;
2680- while tok = sIdent do Declaration(sType, top);
2681- inTypes := false;
2682- for i := 0 to numFwd - 1 do begin
2683- o := Lookup(fwdTypes[i]^.fwd);
2684- if (o = nil) or (o^.cls <> oType) then begin
2685- NotDeclared(fwdPos[i], fwdTypes[i]^.fwd);
2686- fwdTypes[i]^.base := tPoison;
2687- end else begin
2688- fwdTypes[i]^.base := o^.typ;
2689- Named(o);
2690- end;
2691- fwdTypes[i]^.fwd := -1;
2692- end;
2693- end;
2694- sProc, sExtern: Declaration(k, top);
2695- else exit;
2696- end;
2697- until false;
2698-end;
2699-
2700-{ Modules }
2701-
2702-{ Whether m is module n with these arguments. }
2703-function IsModule(m: PModule; n: longint; const args: TArgs): boolean;
2704-var i: longint;
2705-begin
2706- IsModule := false;
2707- if (m^.name <> n) or (m^.args.n <> args.n) then exit;
2708- for i := 0 to args.n - 1 do
2709- if (m^.args.o[i] <> args.o[i]) or not Same(m^.args.t[i], args.t[i]) then exit;
2710- IsModule := true;
2711-end;
2712-
2713-function FindModule(n: longint; const args: TArgs): PModule;
2714-var m: PModule;
2715-begin
2716- m := firstModule;
2717- while (m <> nil) and not IsModule(m, n, args) do m := m^.next;
2718- FindModule := m;
2719-end;
2720-
2721-{ The arguments of an instance: types, or procedures named. }
2722-procedure ParseArgs(var args: TArgs; const mname: shortstring);
2723-var o: PObj; start: TPos;
2724-begin
2725- Next;
2726- repeat
2727- if args.n > High(args.t) then Mark('too many type arguments for ' + mname);
2728- args.o[args.n] := nil;
2729- start := TokPos;
2730- if tok = sIdent then begin
2731- o := QualIdent;
2732- if o^.cls = oProc then args.o[args.n] := o
2733- else if o^.cls <> oType then MarkAt(SpanFrom(start), NameOf(o^.name) + ' isn''t a type or a procedure');
2734- args.t[args.n] := o^.typ;
2735- end else args.t[args.n] := ParseType;
2736- args.pos[args.n] := SpanFrom(start);
2737- inc(args.n);
2738- if tok <> sComma then break;
2739- Next;
2740- until false;
2741- Expect(sRparen);
2742-end;
2743-
2744-{ Past an instance's arguments, to be read when it is made }
2745-procedure SkipArgs;
2746-var p: longint;
2747-begin
2748- p := 0;
2749- repeat
2750- if tok = sLparen then inc(p)
2751- else if tok = sRparen then dec(p)
2752- else if tok in [sSemicolon, sEof] then Expected('")"');
2753- Next;
2754- until p = 0;
2755-end;
2756-
2757-{ A generic module's parameters, bound to the instance's arguments: a
2758- type parameter names its type, a procedure parameter its procedure. }
2759-procedure Params(m: PModule);
2760-var i: longint; o, a: PObj; sig: PType; s: shortstring; at: TPos;
2761-begin
2762- i := 0;
2763- s := NameOf(m^.name) + '(';
2764- Next;
2765- repeat
2766- if tok <> sIdent then Expected('a name');
2767- if i >= m^.args.n then MarkAt(m^.args.at, NameOf(m^.name) + ' needs a type for ' + NameOf(id));
2768- if m^.args.o[i] <> nil then MarkAt(m^.args.pos[i], NameOf(m^.name) + ' needs a type for ' + NameOf(id));
2769- o := NewObj(oType, id, m^.args.t[i]);
2770- o^.used := true; { a parameter of the module, not a declaration }
2771- Declare(o);
2772- s := s + TypeName(m^.args.t[i]) + ',';
2773- inc(i);
2774- Next;
2775- if tok <> sComma then break;
2776- Next;
2777- until false;
2778- while tok = sSemicolon do begin
2779- Next;
2780- if tok <> sIdent then Expected('a name');
2781- at := TokPos;
2782- o := NewObj(oProc, id, nil);
2783- Next;
2784- Expect(sColon);
2785- Expect(sProc);
2786- sig := Signature;
2787- if i >= m^.args.n then MarkAt(m^.args.at, NameOf(m^.name) + ' needs a procedure for ' + NameOf(o^.name));
2788- a := m^.args.o[i];
2789- if a = nil then MarkAt(m^.args.pos[i], NameOf(m^.name) + ' needs a procedure for ' + NameOf(o^.name));
2790- if not Same(a^.typ, sig) then begin
2791- Error(m^.args.pos[i], NameOf(a^.name) + ' doesn''t have the signature of ' + NameOf(o^.name));
2792- Note(at, 'the signature is here');
2793- Finish;
2794- end;
2795- o^.typ := a^.typ; o^.chunk := a^.chunk; o^.isCode := a^.isCode; o^.ext := a^.ext;
2796- o^.used := true;
2797- Declare(o);
2798- s := s + NameOf(a^.module^.name) + '.' + NameOf(a^.name) + ',';
2799- inc(i);
2800- end;
2801- Expect(sRparen);
2802- if i <> m^.args.n then MarkAt(m^.args.at, 'too many type arguments for ' + NameOf(m^.name));
2803- s[length(s)] := ')';
2804- m^.sname := Name(s);
2805-end;
2806-
2807-{ Warns of o if it is never used, or a variable only assigned. What
2808- is exported may be used elsewhere, and a name that starts with _ says
2809- it is meant to go unused. Writing a var parameter, a match's name for
2810- a field or C's variable is what it is for. }
2811-procedure Warn(o: PObj);
2812-var s: shortstring;
2813-begin
2814- s := NameOf(o^.name);
2815- if (o^.cls = oProc) and o^.openEnd then
2816- Warning(o^.pos, s + ' may reach its end without return, and then returns zero');
2817- if o^.exported or (s[1] = '_') then exit;
2818- if o^.used and (o^.read or (o^.cls <> oVar) or o^.isVar or o^.ext) then exit;
2819- case o^.cls of
2820- oConst: s := 'constant ' + s;
2821- oType: s := 'type ' + s;
2822- oVar: if o^.param then s := 'parameter ' + s else s := 'variable ' + s;
2823- oProc: s := 'procedure ' + s;
2824- oModule: s := 'module ' + s;
2825- else exit;
2826- end;
2827- if o^.used then Warning(o^.pos, s + ' is assigned but never read')
2828- else if o^.cls = oModule then Warning(o^.pos, s + ' is imported but never used')
2829- else Warning(o^.pos, s + ' is never used');
2830- if not o^.used and (o^.param or o^.ind) then
2831- Help('if it must be there, call it _' + NameOf(o^.name));
2832-end;
2833-
2834-{ Warns of the call at p, which drops its n results }
2835-procedure Dropped(const p: TPos; n: longint);
2836-var s, blanks: shortstring; i: longint;
2837-begin
2838- s := Source(p);
2839- i := Pos('(', s);
2840- if i > 0 then s := copy(s, 1, i - 1);
2841- blanks := '_';
2842- for i := 2 to n do blanks := blanks + ', _';
2843- if n = 1 then Warning(p, 'the result of ' + s + ' is dropped')
2844- else Warning(p, 'the results of ' + s + ' are dropped');
2845- Help('if that is meant, write ' + blanks + ' := ' + s + '(...)');
2846-end;
2847-
2848-{ The warnings of module m, by where each declaration is: its own
2849- declarations and its procedures' are two lists, each in order, and
2850- firstDrop on are the calls that drop results. The
2851- instances of a generic module share its text, and so its warnings:
2852- only the first is warned of. }
2853-procedure Warnings(m: PModule; firstDrop: longint);
2854-var a, b: PObj; n: PModule; i: longint;
2855-begin
2856- n := firstModule;
2857- while (n <> nil) and (n^.name <> m^.name) do n := n^.next;
2858- if n <> nil then exit;
2859- a := m^.first; b := m^.locals;
2860- i := firstDrop;
2861- while (a <> nil) or (b <> nil) or (i < numDrops) do
2862- if (i < numDrops) and ((a = nil) or (drops[i].at.a < a^.pos.a)) and ((b = nil) or (drops[i].at.a < b^.pos.a)) then begin
2863- Dropped(drops[i].at, drops[i].n);
2864- inc(i);
2865- end else if (b = nil) or (a <> nil) and (a^.pos.a < b^.pos.a) then begin
2866- Warn(a);
2867- a := a^.link;
2868- end else begin
2869- Warn(b);
2870- b := b^.link;
2871- end;
2872-end;
2873-
2874-{ Modules being compiled, not yet finished: for finding a cycle. }
2875-var
2876- pending: array[0..63] of PModule;
2877- numPending: longint;
2878-
2879-function Exists(const path: shortstring): boolean;
2880-var st: Stat; p: shortstring;
2881-begin
2882- p := path + #0;
2883- Exists := (FpStat(@p[1], st) = 0) and ((st.st_mode and S_IFMT) = S_IFREG);
2884-end;
2885-
2886-{ Compiles module n from path, an instance if args are given, or only
2887- reads its interface if checkOnly; returns it. An import calls this in
2888- the middle of reading another file, so it is re-entrant: it saves the
2889- scanner's state, the open scopes, the current module and file and
2890- whether checks are on, and puts them back at the end. }
2891-function CompileFile(const path: shortstring; n: longint; const args: TArgs; checkOnly: boolean): PModule;
2892-var
2893- st: TScanState; saved: array[0..MaxDepth - 1] of longint; d: longint;
2894- oldMod: PModule; oldCheck, oldChecks: boolean; m: PModule;
2895- lib: PLib; start: TPos; alias, mname, line, oldPath: longint; o: PObj; body: longint; iargs: TArgs;
2896- generic: boolean; argsAt: TScanState; why: shortstring; firstDrop: longint;
2897-begin
2898- firstDrop := numDrops;
2899- SaveScan(st);
2900- SaveScopes(d, saved);
2901- oldMod := curModule; oldCheck := checkMode; oldPath := curFile; oldChecks := checks;
2902- checks := true;
2903- curFile := Name(path);
2904- why := Open(path);
2905- if why <> '' then Fatal('can''t read ' + path + ': ' + why);
2906- New(m);
2907- FillChar(m^, SizeOf(TModule), 0);
2908- m^.name := n;
2909- m^.sname := n;
2910- m^.args := args;
2911- m^.scope := NewScope;
2912- m^.path := path;
2913- m^.body := -1;
2914- m^.checkOnly := checkOnly;
2915- curModule := m;
2916- checkMode := checkOnly;
2917- if not checkOnly then begin
2918- if numPending > High(pending) then Mark('imports nested more than ' + IntStr(High(pending) + 1) + ' deep');
2919- pending[numPending] := m;
2920- inc(numPending);
2921- end;
2922- OpenScope(m^.scope);
2923- Next;
2924- Expect(sModule);
2925- if (tok <> sIdent) or (id <> n) then Mark('expected module ' + NameOf(n) + ', found ' + Found);
2926- Next;
2927- { the module first pending is the one named on the command line,
2928- which nothing imports, so no arguments come with it }
2929- if (tok = sLparen) and not checkOnly and (numPending = 1) then
2930- Mark(NameOf(n) + ' is generic: it is compiled where a module imports it')
2931- else if tok = sLparen then Params(m)
2932- else if args.n > 0 then MarkAt(args.at, NameOf(n) + ' isn''t generic');
2933- Expect(sSemicolon);
2934- while tok = sImport do begin
2935- Next;
2936- repeat
2937- if tok <> sIdent then Expected('a module name');
2938- start := TokPos;
2939- alias := id;
2940- mname := id;
2941- iargs.n := 0;
2942- generic := false;
2943- Next;
2944- if tok = sBecomes then begin
2945- Next;
2946- if tok <> sIdent then Expected('a module name');
2947- mname := id;
2948- Next;
2949- if tok = sLparen then begin
2950- generic := true;
2951- SaveScan(argsAt);
2952- SkipArgs;
2953- end;
2954- end;
2955- iargs.at := SpanFrom(start);
2956- o := NewObj(oModule, alias, nil);
2957- o^.pos := start;
2958- Declare(o);
2959- if not generic then begin
2960- o^.module := ImportModule(mname, iargs);
2961- AddImport(m, o^.module);
2962- end else begin
2963- o^.module := nil; { until the instance is made, at its first use }
2964- if numDeferred > High(deferred) then Mark('more than ' + IntStr(High(deferred) + 1) + ' generic imports');
2965- deferred[numDeferred].o := o;
2966- deferred[numDeferred].m := m;
2967- deferred[numDeferred].mname := mname;
2968- deferred[numDeferred].args := argsAt;
2969- deferred[numDeferred].at := iargs.at;
2970- inc(numDeferred);
2971- end;
2972- if tok <> sComma then break;
2973- Next;
2974- until false;
2975- Expect(sSemicolon);
2976- end;
2977- while tok = sLink do begin
2978- Next;
2979- if (tok = sIdent) and (id = nameStatic) then m^.linkStatic := true
2980- else if tok = sString then begin
2981- New(lib);
2982- lib^.name := Intern(@sbuf, slen);
2983- lib^.next := m^.libs;
2984- m^.libs := lib;
2985- m^.usesC := true;
2986- end else Expected('a library or "static"');
2987- Next;
2988- Expect(sSemicolon);
2989- end;
2990- { check off;: the module's index and slice checks left out; neither
2991- word is reserved }
2992- if (tok = sIdent) and (id = nameCheck) then begin
2993- Next;
2994- if (tok <> sIdent) or (id <> nameOff) then Expected('"off"');
2995- Next;
2996- Expect(sSemicolon);
2997- checks := false;
2998- end;
2999- Declarations(true);
3000- if tok = sBegin then begin
3001- if checkMode then SkipBody
3002- else begin
3003- InstancesFor(true);
3004- line := CurLine;
3005- Next;
3006- body := NewChunk(secText, m^.sname, nameBody);
3007- m^.body := body;
3008- BeginProc(tBodySig, nil);
3009- deferSlot := 0;
3010- curResult := nil;
3011- EnterBody(body, line);
3012- stray := false; elseIf := false;
3013- Statements;
3014- NoteLine(CurLine, CurCol);
3015- Expect(sEnd);
3016- EndProc(body, false);
3017- end;
3018- end else Expect(sEnd);
3019- if (tok <> sIdent) or (id <> n) then EndMissing(MissingPos, 'expected ' + NameOf(n) + ', found ' + Found);
3020- Next;
3021- if tok <> sPeriod then Expected('"."');
3022- o := m^.first;
3023- while o <> nil do begin
3024- if (o^.cls = oProc) and o^.fwd then Error(TokPos, NameOf(o^.name) + ' is declared forward but never defined');
3025- o := o^.link;
3026- end;
3027- if (errors = 0) and not checkOnly then Warnings(m, firstDrop);
3028- numDrops := firstDrop;
3029- if errors > 0 then Finish; { a module with errors stops the compiler after it }
3030- CloseScope;
3031- m^.done := true;
3032- if not checkOnly then begin
3033- dec(numPending);
3034- if lastModule = nil then firstModule := m else lastModule^.next := m;
3035- lastModule := m;
3036- end;
3037- curModule := oldMod; checkMode := oldCheck; curFile := oldPath; checks := oldChecks;
3038- RestoreScopes(d, saved);
3039- RestoreScan(st);
3040- CompileFile := m;
3041-end;
3042-
3043-{ The interface check: b must export just what a does. }
3044-procedure CompareIface(a, b: PModule);
3045-var o, q: PObj;
3046-begin
3047- o := a^.first;
3048- while o <> nil do begin
3049- if o^.exported then begin
3050- q := Find(b^.scope, o^.name);
3051- if (q = nil) or not q^.exported or (Fingerprint(o) <> Fingerprint(q)) then
3052- Fatal(b^.path + ': ' + NameOf(o^.name) + ' isn''t exported as in ' + a^.path);
3053- end;
3054- o := o^.link;
3055- end;
3056- q := b^.first;
3057- while q <> nil do begin
3058- o := Find(a^.scope, q^.name);
3059- if q^.exported and ((o = nil) or not o^.exported) then
3060- Fatal(b^.path + ': ' + NameOf(q^.name) + ' isn''t exported by ' + a^.path);
3061- q := q^.link;
3062- end;
3063-end;
3064-
3065-{ Reads every other file of module n in dir, and checks its interface
3066- against m, compiled from the file named chosen. }
3067-procedure CheckSiblings(const dir, chosen: shortstring; n: longint; m: PModule; const args: TArgs);
3068-var
3069- dp: pDir; e: pDirent; f, prefix: shortstring; i: longint;
3070- others: array[0..31] of shortstring; numOthers: longint;
3071-begin
3072- prefix := NameOf(n) + '.';
3073- numOthers := 0;
3074- dp := FpOpenDir(dir);
3075- if dp = nil then exit;
3076- repeat
3077- e := FpReadDir(dp^);
3078- if e = nil then break;
3079- f := '';
3080- i := 0;
3081- while (e^.d_name[i] <> #0) and (i < 255) do begin
3082- f := f + e^.d_name[i];
3083- inc(i);
3084- end;
3085- if (copy(f, 1, length(prefix)) = prefix) and (length(f) > 4)
3086- and (copy(f, length(f) - 3, 4) = '.raz') and (f <> chosen)
3087- and (numOthers <= High(others)) then begin
3088- others[numOthers] := f;
3089- inc(numOthers);
3090- end;
3091- until false;
3092- FpCloseDir(dp^);
3093- for i := 0 to numOthers - 1 do
3094- CompareIface(m, CompileFile(dir + '/' + others[i], n, args, true));
3095-end;
3096-
3097-const Suffixes: array[0..3] of string[16] = ('.' + Target, '.' + TargetOS, '.' + TargetArch, '');
3098-
3099-{ The directories searched for modules, in order, from -1 to numInc }
3100-function SearchDir(i: longint): shortstring;
3101-begin
3102- if i = -1 then SearchDir := mainDir
3103- else if i = numInc then SearchDir := libDir
3104- else SearchDir := incDirs[i];
3105-end;
3106-
3107-function ModuleFile(n: longint; var dir, f: shortstring): boolean;
3108-var i, j: longint;
3109-begin
3110- for i := -1 to numInc do begin
3111- dir := SearchDir(i);
3112- for j := 0 to 3 do begin
3113- f := NameOf(n) + Suffixes[j] + '.raz';
3114- if Exists(dir + '/' + f) then exit(true);
3115- end;
3116- end;
3117- ModuleFile := false;
3118-end;
3119-
3120-{ A program has one module of each name: module n, found as dir/f,
3121- must have no files in a later directory, unless dir/f is a link to
3122- one of them, which chooses it (report, section 3) }
3123-procedure CheckOneModule(n: longint; const dir, f: shortstring; const at: TPos);
3124-var i, j: longint; past, chosen: boolean; g, files, others: shortstring;
3125- st, mine: Stat;
3126-begin
3127- g := dir + '/' + f + #0;
3128- FpStat(@g[1], mine);
3129- others := '';
3130- past := false;
3131- for i := -1 to numInc do begin
3132- if past then begin
3133- files := '';
3134- chosen := false;
3135- for j := 0 to 3 do begin
3136- g := SearchDir(i) + '/' + NameOf(n) + Suffixes[j] + '.raz';
3137- if Exists(g) then begin
3138- files := files + ' and ' + ShownPath(g);
3139- g := g + #0;
3140- FpStat(@g[1], st);
3141- chosen := chosen or ((st.st_dev = mine.st_dev) and (st.st_ino = mine.st_ino));
3142- end;
3143- end;
3144- if not chosen then others := others + files;
3145- end;
3146- past := past or (SearchDir(i) = dir);
3147- end;
3148- if others = '' then exit;
3149- Error(at, 'module ' + NameOf(n) + ' is in ' + ShownPath(dir + '/' + f) + others);
3150- Help('a program has one module of each name; a symbolic link to one of these files chooses it');
3151- Fail;
3152-end;
3153-
3154-function ImportModule(name: longint; const args: TArgs): PModule;
3155-var m: PModule; i: longint; dir, f: shortstring;
3156-begin
3157- m := FindModule(name, args);
3158- if m <> nil then exit(m);
3159- for i := 0 to numPending - 1 do
3160- if IsModule(pending[i], name, args) then MarkAt(args.at, NameOf(name) + ' imports itself');
3161- if not ModuleFile(name, dir, f) then begin
3162- Error(args.at, 'can''t find module ' + NameOf(name));
3163- dir := ShownPath(SearchDir(-1));
3164- for i := 0 to numInc do dir := dir + ', ' + ShownPath(SearchDir(i));
3165- Help('looked for ' + NameOf(name) + '.raz in ' + dir);
3166- Fail;
3167- end;
3168- CheckOneModule(name, dir, f, args.at);
3169- m := CompileFile(dir + '/' + f, name, args, false);
3170- CheckSiblings(dir, f, name, m, args);
3171- ImportModule := m;
3172-end;
3173-
3174-procedure AddImport(m, im: PModule);
3175-var imp: PImport;
3176-begin
3177- New(imp);
3178- imp^.module := im;
3179- imp^.next := m^.imports;
3180- m^.imports := imp;
3181-end;
3182-
3183-{ Makes the instance that deferred[i] imports: its arguments are read
3184- where the import wrote them, and must be declared by now. Compiling
3185- the instance comes in the middle of a declaration, so what that
3186- declaration has under way is kept aside meanwhile. }
3187-procedure MakeInstance(i: longint; const at: TPos);
3188-var
3189- d: TDeferred; st: TScanState; args: TArgs; types, exported, ext, wasQuiet: boolean; nf, nd: longint;
3190- ft: array[0..255] of PType; fp: array[0..255] of TPos; decl: array[0..63] of longint;
3191-begin
3192- d := deferred[i];
3193- dec(numDeferred);
3194- deferred[i] := deferred[numDeferred];
3195- SaveScan(st);
3196- RestoreScan(d.args);
3197- args.n := 0;
3198- making := true; useAt := at;
3199- ParseArgs(args, NameOf(d.mname));
3200- making := false;
3201- RestoreScan(st);
3202- args.at := d.at;
3203- types := inTypes; exported := declExported; ext := inExtern; wasQuiet := quiet;
3204- nf := numFwd; ft := fwdTypes; fp := fwdPos; nd := numDeclaring; decl := declaring;
3205- d.o^.module := ImportModule(d.mname, args);
3206- inTypes := types; declExported := exported; inExtern := ext; quiet := wasQuiet;
3207- numFwd := nf; fwdTypes := ft; fwdPos := fp; numDeclaring := nd; declaring := decl;
3208- AddImport(curModule, d.o^.module);
3209-end;
3210-
3211-procedure FirstUse(o: PObj; const at: TPos);
3212-var i: longint;
3213-begin
3214- for i := 0 to numDeferred - 1 do
3215- if deferred[i].o = o then begin MakeInstance(i, at); exit end;
3216- Fail; { its arguments had an error, already reported }
3217-end;
3218-
3219-{ An instance can't be compiled in the middle of another procedure's
3220- code, so before a procedure's code begins, from its "proc" on, or
3221- the module body's, from its "begin" to the end of the file, this
3222- reads ahead for the names of imports not yet made, and makes those. }
3223-procedure InstancesFor(wholeRest: boolean);
3224-var st: TScanState; d, i: longint; begun: boolean;
3225-begin
3226- if checkMode then exit;
3227- i := numDeferred - 1;
3228- while (i >= 0) and (deferred[i].m <> curModule) do dec(i);
3229- if i < 0 then exit;
3230- { The procedure ends at the "end" that closes its first "begin": d
3231- counts the words still open that "end" or "until" closes, and begun
3232- says that begin was met, so that a record's end in its declarations
3233- doesn't stop it. A forward or code procedure has no raz body to
3234- read, so it stops at that word. The body reads to the end of the
3235- file, as wholeRest says. }
3236- SaveScan(st);
3237- d := 0; begun := false;
3238- repeat
3239- case tok of
3240- sIdent: for i := numDeferred - 1 downto 0 do
3241- if (deferred[i].m = curModule) and (deferred[i].o^.name = id) then MakeInstance(i, TokPos);
3242- sBegin: begin begun := begun or (d = 0); inc(d) end;
3243- sIf, sWhile, sFor, sMatch, sRepeat, sRecord, sVariant: inc(d);
3244- sEnd, sUntil: dec(d);
3245- end;
3246- if not wholeRest and (d = 0) and (begun or (tok in [sForward, sCode])) then break;
3247- Next;
3248- until tok = sEof;
3249- RestoreScan(st);
3250-end;
3251-
3252-function CompileMain(const path: shortstring): PModule;
3253-var base: shortstring; i, n: longint; none: TArgs;
3254-begin
3255- none.n := 0;
3256- i := length(path);
3257- while (i > 0) and (path[i] <> '/') do dec(i);
3258- if i = 0 then mainDir := '.' else mainDir := copy(path, 1, i - 1);
3259- base := copy(path, i + 1, 255);
3260- i := pos('.', base);
3261- if i > 0 then base := copy(base, 1, i - 1);
3262- if base = '' then Fatal('no module in ' + path);
3263- n := Name(base);
3264- none.at := TokPos;
3265- if n <> nameRt then ImportModule(nameRt, none);
3266- if FindModule(n, none) <> nil then CompileMain := FindModule(n, none)
3267- else CompileMain := CompileFile(path, n, none, false);
3268-end;
3269-
3270-initialization
3271- nameRt := Name('Rt');
3272- nameFail := Name('fail');
3273- nameMain := Name('main');
3274- nameAdr := Name('ADR');
3275- nameBody := Name('body');
3276- nameStatic := Name('static');
3277- nameCheck := Name('check');
3278- nameOff := Name('off');
3279- tArgv := NewPtr(NewPtr(tU8, false), false);
3280- tBodySig := NewType(fProc, 8, 8);
3281- curLoop := nil;
3282- numPending := 0;
3283- firstModule := nil;
3284- lastModule := nil;
3285-end.

src/raz.pas deleted +0 -245

@@ -1,245 +0,0 @@
1-{ raz.pas: the command line.
2-
3- raz [-I dir]... [-o file] [-Werror] [-S] Main.raz
4- raz run [-I dir]... Main.raz [arg]...
5- raz --version
6-
7- Compiles the main module and every module it imports, writes the
8- entry point, links what it reaches, and writes the executable: by
9- default the main module's file without its .raz; with -S, it lists
10- the main module's code instead. raz run writes it to a memfd
11- instead, a file that lives only in memory, and executes it in raz's
12- place with the arguments after Main.raz, so its status is the
13- program's; its argv[0] is Main.raz.
14-
15- The program starts by saving argc and argv, runs every module's body
16- (those of the modules the program imports, imported modules first),
17- then the main module's main, and ends with Rt.exit and main's
18- status. A static program does this from its entry point. One that
19- uses C starts through the C library, __libc_start_main, which sets
20- C up and calls this as C's main; first it gives Rt C's exit, which
21- Rt.exit then ends the program with.
22-
23- Depends on: everything else.
24- Leaves out: the work itself; the other units compile, link and
25- write, and this only reads the command line and runs them in order. }
26-
27-program raz;
28-
29-{$mode objfpc}{$H-}
30-
31-uses math, BaseUnix, syscall, scan, diag, sym, chunk, x64, gen, parse, link, elf;
32-
33-const
34- { what git describe says, made by make: 0.3.0 at the tag v0.3.0,
35- 0.3.0-5-g38d29a8 five commits past it }
36- Version = {$I version.inc};
37- Report = '2026-10.21'; { the version of doc/raz.md it follows }
38- MemfdCreate = 319; { the system call; FPC 3.2.2 has no name for it }
39- MfdCloexec = 1; { an ELF still executes: the kernel opens it first }
40-
41-{ The modules the program uses: the main module, Rt, and every module
42- they import. A module read only for the interface check is not. }
43-procedure Use(m: PModule);
44-var i: PImport;
45-begin
46- if m^.used then exit;
47- m^.used := true;
48- i := m^.imports;
49- while i <> nil do begin
50- Use(i^.module);
51- i := i^.next;
52- end;
53-end;
54-
55-{ Whether the program uses C: if so, the libraries it needs go to
56- elf.pas, the C library first. }
57-function UsesC: boolean;
58-var m, st, c: PModule; l: PLib; i: longint; seen: boolean;
59-begin
60- st := nil; c := nil;
61- numNeeded := 1;
62- needed[0] := Intern(PChar('libc.so.6'), 9);
63- m := firstModule;
64- while m <> nil do begin
65- if m^.used and m^.linkStatic then st := m;
66- if m^.used and m^.usesC then c := m;
67- l := m^.libs;
68- while m^.used and (l <> nil) do begin
69- seen := false;
70- for i := 0 to numNeeded - 1 do seen := seen or (needed[i] = l^.name);
71- if not seen then begin
72- if numNeeded > High(needed) then Fatal('more than ' + IntStr(High(needed) + 1) + ' libraries');
73- needed[numNeeded] := l^.name;
74- inc(numNeeded);
75- end;
76- l := l^.next;
77- end;
78- m := m^.next;
79- end;
80- if (st <> nil) and (c <> nil) then
81- Fatal(NameOf(st^.name) + ' says link static, but ' + NameOf(c^.name) + ' uses C');
82- if c = nil then numNeeded := 0;
83- UsesC := c <> nil;
84-end;
85-
86-{ What raz -h says }
87-procedure Usage;
88-begin
89- writeln('usage: raz [option]... Main.raz compiles Main.raz and the modules it imports');
90- writeln(' raz run [option]... Main.raz [arg]... compiles it and runs it, with the args');
91- writeln('options:');
92- writeln(' -o file the program''s file, Main without .raz if left out');
93- writeln(' -I dir looks for imported modules in dir too, after Main.raz''s own');
94- writeln(' -Werror a warning counts as an error');
95- writeln(' -S lists the main module''s code, under each line of source');
96- writeln(' -s strips symbols, line numbers, the places a failure is told');
97- writeln(' by and the profiler: a failure says only its address');
98- writeln(' -noprofile leaves out the profiler, which RAZ_PROFILE turns on');
99- writeln(' -h, --help says this');
100- writeln(' --version says the version, and the report it follows');
101- writeln('see raz(1), and the report, doc/raz.md');
102-end;
103-
104-function RtObj(rt: PModule; const n: shortstring): PObj;
105-var o: PObj;
106-begin
107- o := Find(rt^.scope, Intern(@n[1], length(n)));
108- if o = nil then Fatal('Rt has no ' + n);
109- RtObj := o;
110-end;
111-
112-var
113- path, outPath, dir, s: shortstring;
114- i, first, entry, fd: longint;
115- m, rt: PModule;
116- main: PObj;
117- run, noProfile: boolean;
118- links: array[0..3] of TLink;
119- numLinks: longint;
120-
121-
122-{ Rt is given the address of chunk, in its variable v }
123-procedure AddLink(chunk: longint; v: PObj);
124-begin
125- links[numLinks].chunk := chunk;
126- links[numLinks].into := v^.chunk;
127- inc(numLinks);
128-end;
129-
130-begin
131- { constants fold as the machine computes: NaN and infinities, no traps }
132- SetExceptionMask([exInvalidOp, exDenormalized, exZeroDivide, exOverflow, exUnderflow, exPrecision]);
133- path := '';
134- outPath := '';
135- numInc := 0;
136- noProfile := false;
137- run := (ParamCount >= 1) and (ParamStr(1) = 'run');
138- i := 1 + ord(run);
139- while i <= ParamCount do begin
140- s := ParamStr(i);
141- if s = '-I' then begin
142- inc(i);
143- if numInc > High(incDirs) then Fatal('more than ' + IntStr(High(incDirs) + 1) + ' -I directories');
144- incDirs[numInc] := ParamStr(i);
145- inc(numInc);
146- end else if s = '-o' then begin
147- inc(i);
148- outPath := ParamStr(i);
149- end else if s = '-Werror' then
150- werror := true
151- else if s = '-S' then
152- listing := true
153- else if s = '-s' then
154- stripped := true
155- else if s = '-noprofile' then
156- noProfile := true
157- else if (s = '-h') or (s = '--help') then begin
158- Usage;
159- Halt(0);
160- end else if s = '--version' then begin
161- writeln('raz ', Version, ', report ', Report);
162- Halt(0);
163- end else if (s <> '') and (s[1] = '-') then
164- Fatal('unknown option ' + s)
165- else begin
166- path := s;
167- first := i;
168- if run then break; { the rest are the program's }
169- end;
170- inc(i);
171- end;
172- if path = '' then begin
173- Usage;
174- Halt(1);
175- end;
176- if run and (outPath <> '') then Fatal('raz run takes no -o');
177- dir := ParamStr(0);
178- i := length(dir);
179- while (i > 0) and (dir[i] <> '/') do dec(i);
180- if i = 0 then libDir := 'lib' else libDir := copy(dir, 1, i) + 'lib';
181- if outPath = '' then begin
182- outPath := path;
183- if copy(outPath, length(outPath) - 3, 4) = '.raz' then
184- outPath := copy(outPath, 1, length(outPath) - 4)
185- else outPath := outPath + '.out';
186- end;
187-
188- m := CompileMain(path);
189- if errors > 0 then Finish;
190-
191- Use(m);
192- rt := firstModule;
193- while (rt <> nil) and (NameOf(rt^.name) <> 'Rt') do rt := rt^.next;
194- if rt <> nil then Use(rt);
195-
196- main := Find(m^.scope, Intern('main', 4));
197- if main <> nil then begin
198- if (main^.cls <> oProc) or not main^.exported then Error(main^.pos, 'main must be an exported procedure')
199- else if (main^.typ^.len <> 0) or ((main^.typ^.base <> nil) and (main^.typ^.base <> tInt)) then
200- Error(main^.pos, 'main must be proc main* or proc main*: INT');
201- if errors > 0 then Finish;
202- end;
203- Finish;
204-
205- if rt = nil then Fatal('can''t find module Rt');
206- { what Rt is given: the places, which the linker makes, for Rt to say
207- where a failed check or a signal was (place), and the calls under
208- way then (calls); and the profiler, which needs them too. raz -s
209- gives none, -noprofile no profiler. }
210- numLinks := 0;
211- if not stripped then begin
212- placesChunk := NewChunk(secRodata, -1, -1);
213- SetData(placesChunk, nil, 0, 8);
214- AddLink(placesChunk, RtObj(rt, 'places'));
215- AddLink(RtObj(rt, 'calls')^.chunk, RtObj(rt, 'teller'));
216- AddLink(RtObj(rt, 'place')^.chunk, RtObj(rt, 'placer'));
217- if not noProfile then AddLink(RtObj(rt, 'startProfile')^.chunk, RtObj(rt, 'profiler'));
218- end;
219- entry := EntryPoint(UsesC, firstModule, main, RtObj(rt, 'cExit')^.chunk,
220- RtObj(rt, 'exit')^.chunk, links, numLinks);
221-
222- MarkLive(entry);
223- if not HasReals then
224- for i := 0 to numChunks - 1 do
225- if chunks^[i].live and chunks^[i].reals then
226- Error(chunks^[i].realsAt, 'this target has no reals');
227- if errors > 0 then Finish;
228- if listing then begin
229- List(m^.sname);
230- exit;
231- end;
232-
233- mainPath := path;
234- if run then begin
235- { argv from Main.raz on is the program's, ending in nil as it must }
236- fd := Do_SysCall(MemfdCreate, TSysParam(PChar('raz')), MfdCloexec);
237- if fd < 0 then Fatal('can''t create a memfd');
238- Str(fd, s);
239- outPath := '/proc/self/fd/' + s + #0;
240- WriteElf(outPath, entry);
241- FpExecve(@outPath[1], @argv[first], envp);
242- Fatal('can''t run ' + path);
243- end;
244- WriteElf(outPath, entry);
245-end.

src/scan.pas deleted +0 -886

@@ -1,886 +0,0 @@
1-{ scan.pas: the scanner.
2-
3- Reads a raz source file and hands the parser one symbol at a time:
4- reserved words, identifiers, numbers, characters, strings and
5- operators. Identifiers are interned, so that the rest of the compiler
6- compares names as small integers. The scanner also says where the
7- current symbol is, for messages.
8-
9- Depends on: BaseUnix, to read files; diag, to report errors.
10- Leaves out: recovery from errors in the text itself, such as a string
11- not closed: the first such error stops the compiler. The parser goes
12- on after its own errors, through recovery below. }
13-
14-unit scan;
15-
16-{$mode objfpc}{$H-}
17-
18-interface
19-
20-uses diag;
21-
22-type
23- TSym = (sNull, sIdent, sInt, sReal, sChar, sString,
24- sPlus, sMinus, sTimes, sSlash, sEql, sNeq, sLss, sLeq, sGtr, sGeq,
25- sBecomes, sColon, sSemicolon, sComma, sPeriod, sUpto, sEllipsis,
26- sLparen, sRparen, sLbrak, sRbrak, sLbrace, sRbrace, sArrow, sAmp, sTilde, sBar,
27- sBlank,
28- { the reserved words, in the order of Words below }
29- sAnd, sBegin, sBreak, sBy, sCode, sConst, sDefer, sDiv, sDo, sElse,
30- sElsif, sEnd, sExtern, sFor, sForward, sIf, sImport, sIn, sLink,
31- sMatch, sMod, sModule, sNot, sOf, sOr, sPacked, sProc, sRecord,
32- sRepeat, sReturn, sSet, sShl, sShr, sThen, sTo, sTry, sType, sUntil, sVar,
33- sVariant, sVolatile, sWhile, sXor,
34- sEof);
35-
36- PBytes = ^TBytes;
37- TBytes = array[0..MaxInt - 1] of byte;
38- PLongs = ^TLongs;
39- TLongs = array[0..MaxInt div 4 - 1] of longint;
40-
41- { Where the scanner is. Importing a module compiles it in the middle
42- of another, so the parser saves this and restores it afterwards. }
43- TScanState = record
44- buf: PChar;
45- len, pos, line, lineStart: longint;
46- tokPos, tokLine, tokLineStart: longint;
47- prevEnd: longint; { where the symbol before this one ends }
48- tok: TSym;
49- ival: int64;
50- rval: double;
51- id: longint;
52- f: longint; { the file, as diag knows it }
53- end;
54-
55-const
56- MaxIdent = 63;
57- MaxStr = 65536;
58-
59-var
60- tok: TSym; { the current symbol }
61- ival: int64; { sInt, sChar: its value }
62- rval: double; { sReal: its value }
63- id: longint; { sIdent: its name }
64- sbuf: array[0..MaxStr] of byte; { sString: its bytes, then a zero }
65- slen: longint; { sString: how many bytes }
66-
67-function Intern(p: PChar; n: longint): longint;
68-function NameOf(n: longint): shortstring;
69-function Reserved(n: longint): boolean;
70-function Open(const path: shortstring): shortstring;
71-procedure Next;
72-procedure Mark(const msg: shortstring);
73-procedure MarkAt(const p: TPos; const msg: shortstring);
74-procedure MarkHelp(const p: TPos; const msg, hint: shortstring);
75-procedure Fail;
76-function AtLineStart: boolean;
77-function Indent: longint;
78-function SymText(s: TSym): shortstring;
79-function Found: shortstring;
80-
81-var
82- { Where the parser goes on after an error: the innermost statement or
83- declaration being read. nil stops the compiler at the first error. }
84- recovery: ^jmp_buf;
85- { The parser is skipping what it has read once already, after an
86- error, so slips in it aren't reported again. }
87- skipping: boolean;
88-procedure SaveScan(var st: TScanState);
89-procedure RestoreScan(const st: TScanState);
90-function TokPos: TPos;
91-function AfterPrev: TPos;
92-function MissingPos: TPos;
93-function SpanFrom(const p: TPos): TPos;
94-function CurLine: longint;
95-function CurCol: longint;
96-procedure LineCol(a: longint; out line, col: longint);
97-
98-implementation
99-
100-uses BaseUnix;
101-
102-const
103- NumWords = ord(sXor) - ord(sAnd) + 1;
104- Words: array[0..NumWords - 1] of string[8] = (
105- 'and', 'begin', 'break', 'by', 'code', 'const', 'defer', 'div', 'do',
106- 'else', 'elsif', 'end', 'extern', 'for', 'forward', 'if', 'import',
107- 'in', 'link', 'match', 'mod', 'module', 'not', 'of', 'or', 'packed',
108- 'proc', 'record', 'repeat', 'return', 'set', 'shl', 'shr', 'then',
109- 'to', 'try', 'type', 'until', 'var', 'variant', 'VOLATILE', 'while', 'xor');
110- Ops: array[sPlus..sBlank] of string[3] = (
111- '+', '-', '*', '/', '=', '#', '<', '<=', '>', '>=',
112- ':=', ':', ';', ',', '.', '..', '...',
113- '(', ')', '[', ']', '{', '}', '^', '&', '~', '|', '_');
114-
115-var
116- cur: TScanState; { buf .. path; tok, ival, rval and id live above }
117-
118- { The name table: every distinct identifier once, in a pool of
119- characters, found through an open-addressed hash table. }
120- pool: PChar;
121- poolLen, poolCap: longint;
122- nameOff, nameLen, nameHash: PLongs;
123- numNames, nameCap: longint;
124- table: PLongs; { name + 1, or 0 for an empty slot }
125- tableMask: longint;
126-
127-{ Names }
128-
129-function Hash(p: PChar; n: longint): longint;
130-var h: longword; i: longint;
131-begin
132- h := 2166136261;
133- for i := 0 to n - 1 do h := (h xor byte(p[i])) * 16777619;
134- Hash := longint(h and $7FFFFFFF);
135-end;
136-
137-procedure Grow;
138-var i, j, n: longint;
139-begin
140- FreeMem(table);
141- tableMask := tableMask * 2 + 1;
142- table := GetMem((tableMask + 1) * 4);
143- FillChar(table^, (tableMask + 1) * 4, 0);
144- for n := 0 to numNames - 1 do begin
145- i := nameHash^[n] and tableMask;
146- while table^[i] <> 0 do i := (i + 1) and tableMask;
147- table^[i] := n + 1;
148- end;
149- j := nameCap * 2;
150- nameOff := ReAllocMem(nameOff, j * 4);
151- nameLen := ReAllocMem(nameLen, j * 4);
152- nameHash := ReAllocMem(nameHash, j * 4);
153- nameCap := j;
154-end;
155-
156-function Intern(p: PChar; n: longint): longint;
157-var h, i, k: longint;
158-begin
159- h := Hash(p, n);
160- i := h and tableMask;
161- while table^[i] <> 0 do begin
162- k := table^[i] - 1;
163- if (nameHash^[k] = h) and (nameLen^[k] = n)
164- and (CompareByte(pool[nameOff^[k]], p^, n) = 0) then exit(k);
165- i := (i + 1) and tableMask;
166- end;
167- if poolLen + n > poolCap then begin
168- poolCap := poolCap * 2 + n;
169- pool := ReAllocMem(pool, poolCap);
170- end;
171- Move(p^, pool[poolLen], n);
172- k := numNames;
173- nameOff^[k] := poolLen;
174- nameLen^[k] := n;
175- nameHash^[k] := h;
176- inc(poolLen, n);
177- inc(numNames);
178- table^[i] := k + 1;
179- if numNames * 2 > tableMask then Grow;
180- Intern := k;
181-end;
182-
183-function NameOf(n: longint): shortstring;
184-var s: shortstring;
185-begin
186- SetLength(s, nameLen^[n]);
187- Move(pool[nameOff^[n]], s[1], nameLen^[n]);
188- NameOf := s;
189-end;
190-
191-{ Errors }
192-
193-{ The current symbol }
194-function TokPos: TPos;
195-begin
196- TokPos.f := cur.f;
197- TokPos.a := cur.tokPos;
198- TokPos.b := cur.pos;
199-end;
200-
201-{ The place just after the symbol before the current one, where a
202- missing symbol belongs }
203-function AfterPrev: TPos;
204-begin
205- AfterPrev.f := cur.f;
206- AfterPrev.a := cur.prevEnd;
207- AfterPrev.b := cur.prevEnd;
208-end;
209-
210-{ Where to say a symbol is missing: at the current symbol, unless it
211- starts a later line than the symbol before it, which is more likely
212- where the missing one belongs }
213-function MissingPos: TPos;
214-var i: longint;
215-begin
216- MissingPos := TokPos;
217- for i := cur.prevEnd to cur.tokPos - 1 do
218- if cur.buf[i] = #10 then MissingPos := AfterPrev;
219-end;
220-
221-{ From the start of p to the end of the symbol before the current one:
222- the whole of a construct that has just been read }
223-function SpanFrom(const p: TPos): TPos;
224-begin
225- SpanFrom := p;
226- SpanFrom.b := cur.prevEnd;
227-end;
228-
229-function CurLine: longint;
230-begin
231- CurLine := cur.tokLine;
232-end;
233-
234-{ The line and column of byte a of the file, at or before the current
235- symbol: counted back from the symbol's line, so that it costs only
236- the distance. A column counts characters, as diag's do. }
237-procedure LineCol(a: longint; out line, col: longint);
238-var i, start: longint;
239-begin
240- line := cur.tokLine;
241- start := cur.tokLineStart;
242- while a < start do begin
243- dec(line);
244- dec(start);
245- while (start > 0) and (cur.buf[start - 1] <> #10) do dec(start);
246- end;
247- col := 1;
248- for i := start to a - 1 do
249- if (byte(cur.buf[i]) and $C0) <> $80 then inc(col);
250-end;
251-
252-function CurCol: longint;
253-var line: longint;
254-begin
255- LineCol(cur.tokPos, line, CurCol);
256-end;
257-
258-procedure Mark(const msg: shortstring);
259-begin
260- MarkAt(TokPos, msg);
261-end;
262-
263-{ After an error in the parser's construct, reported with its notes
264- and help: the parser goes on from the recovery point. }
265-procedure Fail;
266-begin
267- if recovery = nil then Finish;
268- longjmp(recovery^, 1);
269-end;
270-
271-procedure MarkAt(const p: TPos; const msg: shortstring);
272-begin
273- Error(p, msg);
274- Fail;
275-end;
276-
277-{ MarkAt, with a line of help after the message. }
278-procedure MarkHelp(const p: TPos; const msg, hint: shortstring);
279-begin
280- Error(p, msg);
281- Help(hint);
282- Fail;
283-end;
284-
285-{ An error in the text at bytes a to b of the file being read, which
286- stops the compiler: past it, the symbols can't be trusted. }
287-procedure MarkBytes(a, b: longint; const msg: shortstring);
288-var p: TPos;
289-begin
290- p.f := cur.f; p.a := a; p.b := b;
291- quiet := false;
292- Error(p, msg);
293- Finish;
294-end;
295-
296-procedure LexError(const msg: shortstring);
297-begin
298- MarkBytes(cur.tokPos, cur.pos, msg);
299-end;
300-
301-{ The n characters at the scanner are how another language writes t:
302- an error, but reading goes on as if t were written. }
303-procedure Slip(n: longint; t: TSym; const msg: shortstring);
304-var p: TPos;
305-begin
306- p.f := cur.f; p.a := cur.pos; p.b := cur.pos + n;
307- if not skipping then Error(p, msg);
308- inc(cur.pos, n);
309- tok := t;
310-end;
311-
312-{ How an operator or reserved word is written, quoted, for messages. }
313-function SymText(s: TSym): shortstring;
314-begin
315- if s in [sPlus..sBlank] then SymText := '"' + Ops[s] + '"'
316- else SymText := '"' + Words[ord(s) - ord(sAnd)] + '"';
317-end;
318-
319-{ The current symbol, for "expected ..., found ...": a name as it is,
320- a literal by its kind, an operator or reserved word quoted. }
321-function Found: shortstring;
322-begin
323- case tok of
324- sIdent: Found := NameOf(id);
325- sInt, sReal: Found := 'a number';
326- sChar: Found := 'a character';
327- sString: Found := 'a string';
328- sEof: Found := 'the end of the file';
329- else Found := SymText(tok);
330- end;
331-end;
332-
333-{ The current symbol is the first on its line: at the top level of a
334- module, by the usual layout, so where reading can start again. }
335-function AtLineStart: boolean;
336-begin
337- AtLineStart := cur.tokPos = cur.tokLineStart;
338-end;
339-
340-{ The column the current symbol's line is indented to }
341-function Indent: longint;
342-var i: longint;
343-begin
344- i := cur.tokLineStart;
345- while cur.buf[i] in [' ', #9] do inc(i);
346- Indent := i - cur.tokLineStart + 1;
347-end;
348-
349-{ Files }
350-
351-{ Name n is a reserved word }
352-function Reserved(n: longint): boolean;
353-begin
354- Reserved := n < NumWords;
355-end;
356-
357-{ Reads the file at path to scan it; '' if it can, else why not }
358-function Open(const path: shortstring): shortstring;
359-var fd: cint; st: Stat; n, got, r: longint; p: shortstring;
360-begin
361- p := path + #0;
362- fd := FpOpen(@p[1], O_RDONLY);
363- if fd < 0 then
364- case FpGetErrno of
365- ESysENOENT: exit('there is no such file');
366- ESysEACCES: exit('permission denied');
367- else exit('it can''t be opened');
368- end;
369- if FpFStat(fd, st) <> 0 then begin FpClose(fd); exit('it can''t be opened') end;
370- if (st.st_mode and S_IFMT) <> S_IFREG then begin FpClose(fd); exit('it isn''t a file') end;
371- n := st.st_size;
372- cur.buf := GetMem(n + 1);
373- got := 0;
374- while got < n do begin
375- r := FpRead(fd, cur.buf[got], n - got);
376- if r <= 0 then Fatal('can''t read ' + path);
377- got := got + r;
378- end;
379- FpClose(fd);
380- cur.buf[n] := #0; { the sentinel that ends every scan }
381- cur.len := n;
382- cur.pos := 0;
383- cur.line := 1;
384- cur.lineStart := 0;
385- cur.tokPos := 0;
386- cur.tokLine := 1;
387- cur.tokLineStart := 0;
388- cur.f := AddFile(path, cur.buf, n);
389- Open := '';
390-end;
391-
392-procedure SaveScan(var st: TScanState);
393-begin
394- st := cur;
395- st.tok := tok; st.ival := ival; st.rval := rval; st.id := id;
396-end;
397-
398-procedure RestoreScan(const st: TScanState);
399-begin
400- cur := st;
401- tok := st.tok; ival := st.ival; rval := st.rval; id := st.id;
402-end;
403-
404-{ UTF-8 }
405-
406-{ Decodes the character at buf[pos], which is not ASCII, checking that
407- it is well formed; returns its code point and moves pos past it. }
408-function Utf8(var pos: longint): longint;
409-var b0, b1, n, i, cp: longint; lo, hi: byte;
410-begin
411- b0 := byte(cur.buf[pos]);
412- lo := $80; hi := $BF;
413- case b0 of
414- $C2..$DF: begin n := 1; cp := b0 and $1F end;
415- $E0: begin n := 2; cp := 0; lo := $A0 end;
416- $E1..$EC, $EE, $EF: begin n := 2; cp := b0 and $0F end;
417- $ED: begin n := 2; cp := $0D; hi := $9F end; { no surrogates }
418- $F0: begin n := 3; cp := 0; lo := $90 end;
419- $F1..$F3: begin n := 3; cp := b0 and $07 end;
420- $F4: begin n := 3; cp := 4; hi := $8F end; { up to 10FFFFH }
421- else
422- cur.tokPos := pos;
423- LexError('invalid UTF-8');
424- end;
425- for i := 1 to n do begin
426- b1 := byte(cur.buf[pos + i]);
427- if (b1 < lo) or (b1 > hi) or (pos + i >= cur.len) then begin
428- cur.tokPos := pos;
429- LexError('bad UTF-8');
430- end;
431- cp := cp shl 6 or (b1 and $3F);
432- lo := $80; hi := $BF;
433- end;
434- pos := pos + n + 1;
435- Utf8 := cp;
436-end;
437-
438-procedure Put(b: longint);
439-begin
440- if slen >= MaxStr then LexError('a string holds at most ' + IntStr(MaxStr) + ' bytes');
441- sbuf[slen] := b;
442- inc(slen);
443-end;
444-
445-procedure PutUtf8(cp: longint);
446-begin
447- if cp < $80 then Put(cp)
448- else if cp < $800 then begin
449- Put($C0 or cp shr 6); Put($80 or cp and $3F)
450- end else if cp < $10000 then begin
451- Put($E0 or cp shr 12); Put($80 or cp shr 6 and $3F); Put($80 or cp and $3F)
452- end else begin
453- Put($F0 or cp shr 18); Put($80 or cp shr 12 and $3F);
454- Put($80 or cp shr 6 and $3F); Put($80 or cp and $3F)
455- end;
456-end;
457-
458-function HexVal(c: char): longint;
459-begin
460- case c of
461- '0'..'9': HexVal := ord(c) - ord('0');
462- 'A'..'F': HexVal := ord(c) - ord('A') + 10;
463- 'a'..'f': HexVal := ord(c) - ord('a') + 10;
464- else HexVal := -1;
465- end;
466-end;
467-
468-{ The text of the file from byte a up to but not including b }
469-function Text(a, b: longint): shortstring;
470-var p: TPos;
471-begin
472- p.f := cur.f; p.a := a; p.b := b;
473- Text := Source(p);
474-end;
475-
476-{ One character of a character or string literal, at buf[pos]: its code
477- point, or for \xHH, minus one minus the byte. }
478-function LitChar(inString: boolean): longint;
479-var c: char; v, d, n, esc, digits: longint;
480-begin
481- c := cur.buf[cur.pos];
482- esc := cur.pos;
483- if c = '\' then begin
484- inc(cur.pos);
485- c := cur.buf[cur.pos];
486- inc(cur.pos);
487- case c of
488- 'n': v := 10;
489- 't': v := 9;
490- 'r': v := 13;
491- '0': v := 0;
492- '\', '''', '"': v := ord(c);
493- 'x': begin
494- if not inString then MarkBytes(esc, cur.pos, '\x is only for strings');
495- d := HexVal(cur.buf[cur.pos]);
496- n := HexVal(cur.buf[cur.pos + 1]);
497- if (d < 0) or (n < 0) then MarkBytes(esc, cur.pos + 2, '\x needs two hex digits');
498- inc(cur.pos, 2);
499- v := -1 - (d * 16 + n);
500- end;
501- 'u': begin
502- if cur.buf[cur.pos] <> '{' then MarkBytes(esc, cur.pos, 'expected "{" after \u');
503- inc(cur.pos);
504- digits := cur.pos;
505- v := 0; n := 0;
506- while HexVal(cur.buf[cur.pos]) >= 0 do begin
507- v := v * 16 + HexVal(cur.buf[cur.pos]);
508- inc(n); inc(cur.pos);
509- if n > 6 then MarkBytes(esc, cur.pos, 'a code point has at most 6 hex digits');
510- end;
511- if (n = 0) or (cur.buf[cur.pos] <> '}') then MarkBytes(esc, cur.pos, 'expected hex digits and "}" after \u{');
512- inc(cur.pos);
513- if (v > $10FFFF) or ((v >= $D800) and (v <= $DFFF)) then
514- MarkBytes(esc, cur.pos, Text(digits, cur.pos - 1) + ' isn''t a code point');
515- end;
516- else MarkBytes(esc, cur.pos, 'unknown escape \' + c);
517- end;
518- end else if byte(c) >= $80 then
519- v := Utf8(cur.pos)
520- else if (c < ' ') or (c = #127) then
521- if inString then LexError('string not closed')
522- else LexError('character not closed')
523- else begin
524- v := ord(c);
525- inc(cur.pos);
526- end;
527- LitChar := v;
528-end;
529-
530-{ Symbols }
531-
532-procedure Comment;
533-var depth, open: longint; c: char;
534-begin
535- depth := 1;
536- open := cur.pos;
537- inc(cur.pos, 2);
538- repeat
539- c := cur.buf[cur.pos];
540- if c = #0 then begin
541- if cur.pos >= cur.len then MarkBytes(open, open + 2, 'comment not closed');
542- inc(cur.pos);
543- end else if (c = '(') and (cur.buf[cur.pos + 1] = '*') then begin
544- inc(depth); inc(cur.pos, 2)
545- end else if (c = '*') and (cur.buf[cur.pos + 1] = ')') then begin
546- dec(depth); inc(cur.pos, 2)
547- end else if c = #10 then begin
548- inc(cur.pos); inc(cur.line); cur.lineStart := cur.pos
549- end else if byte(c) >= $80 then
550- Utf8(cur.pos)
551- else
552- inc(cur.pos);
553- until depth = 0;
554-end;
555-
556-{ Reading a decimal real exactly: the F64 nearest to digits times 10 to
557- an exponent, ties to the even one, which a library's Val doesn't
558- promise. The number is a fraction of two big integers, num / den,
559- scaled by 2^e until its whole part has 53 or 54 bits; that part and
560- the remainder give the bits and the rounding. }
561-type
562- TBig = record
563- n: longint; { words in use; 0 is zero }
564- w: array[0..95] of longword; { least significant first }
565- end;
566- { 96 words, 3072 bits, are plenty: a shortstring holds at most 255
567- digits, so ReadReal's den is at most 10^(330 + 255), about 2^1944,
568- and num below 10^310; the shift that follows makes the larger one at
569- most 54 bits longer than den, about 2000 bits in all. }
570-
571-{ a := a * m + add }
572-procedure BigMul(var a: TBig; m, add: longword);
573-var i: longint; c: qword;
574-begin
575- c := add;
576- for i := 0 to a.n - 1 do begin
577- c := qword(a.w[i]) * m + c;
578- a.w[i] := longword(c);
579- c := c shr 32;
580- end;
581- if c <> 0 then begin a.w[a.n] := longword(c); inc(a.n) end;
582-end;
583-
584-procedure BigShl(var a: TBig; k: longint);
585-var i, words, bits: longint;
586-begin
587- if a.n = 0 then exit;
588- words := k div 32; bits := k mod 32;
589- a.w[a.n + words] := 0;
590- for i := a.n - 1 downto 0 do begin
591- if bits > 0 then a.w[i + words + 1] := a.w[i + words + 1] or (a.w[i] shr (32 - bits));
592- a.w[i + words] := a.w[i] shl bits;
593- end;
594- for i := 0 to words - 1 do a.w[i] := 0;
595- inc(a.n, words + 1);
596- while (a.n > 0) and (a.w[a.n - 1] = 0) do dec(a.n);
597-end;
598-
599-procedure BigShr1(var a: TBig);
600-var i: longint;
601-begin
602- for i := 0 to a.n - 1 do begin
603- a.w[i] := a.w[i] shr 1;
604- if i + 1 < a.n then a.w[i] := a.w[i] or (a.w[i + 1] shl 31);
605- end;
606- while (a.n > 0) and (a.w[a.n - 1] = 0) do dec(a.n);
607-end;
608-
609-function BigCmp(const a, b: TBig): longint;
610-var i: longint;
611-begin
612- if a.n <> b.n then exit(ord(a.n > b.n) * 2 - 1);
613- for i := a.n - 1 downto 0 do
614- if a.w[i] <> b.w[i] then exit(ord(a.w[i] > b.w[i]) * 2 - 1);
615- BigCmp := 0;
616-end;
617-
618-{ a := a - b, b not above a }
619-procedure BigSub(var a: TBig; const b: TBig);
620-var i: longint; d: int64;
621-begin
622- d := 0;
623- for i := 0 to a.n - 1 do begin
624- d := d + a.w[i];
625- if i < b.n then d := d - b.w[i];
626- a.w[i] := longword(d);
627- d := -ord(d < 0); { a borrow }
628- end;
629- while (a.n > 0) and (a.w[a.n - 1] = 0) do dec(a.n);
630-end;
631-
632-function BigBits(const a: TBig): longint;
633-var t: longword;
634-begin
635- if a.n = 0 then exit(0);
636- BigBits := (a.n - 1) * 32;
637- t := a.w[a.n - 1];
638- while t <> 0 do begin inc(BigBits); t := t shr 1 end;
639-end;
640-
641-{ s is digits, a point, digits, and maybe E, a sign and digits. False if
642- the value is past the largest F64; one below the smallest is 0. }
643-function ReadReal(const s: shortstring; out x: double): boolean;
644-var
645- num, den, d: TBig; i, digits, e, ex: longint; neg, half, sticky: boolean;
646- q, b: qword;
647-begin
648- num.n := 0; den.n := 1; den.w[0] := 1;
649- digits := 0; e := 0; i := 1;
650- while (i <= length(s)) and (s[i] <> 'E') do begin
651- if s[i] = '.' then e := 1
652- else begin
653- BigMul(num, 10, ord(s[i]) - ord('0'));
654- if num.n > 0 then inc(digits); { counted from the first that isn't 0 }
655- if e > 0 then inc(e);
656- end;
657- inc(i);
658- end;
659- if e > 0 then e := 1 - e; { minus the digits after the point }
660- ex := 0; neg := false;
661- if i <= length(s) then begin
662- inc(i);
663- neg := s[i] = '-';
664- if s[i] in ['+', '-'] then inc(i);
665- for i := i to length(s) do
666- if ex < 100000 then ex := ex * 10 + ord(s[i]) - ord('0');
667- end;
668- if neg then ex := -ex;
669- inc(e, ex);
670- x := 0.0;
671- if num.n = 0 then exit(true);
672- if digits + e > 310 then exit(false); { 10^310 is past every F64 }
673- if digits + e < -330 then exit(true); { and 10^-330 below half the least }
674- for i := 1 to e do BigMul(num, 10, 0);
675- for i := 1 to -e do BigMul(den, 10, 0);
676- { num / den 2^-e from 2^52 to 2^54, but not past the least exponent }
677- e := BigBits(num) - BigBits(den) - 53;
678- if e < -1074 then e := -1074;
679- if e < 0 then BigShl(num, -e) else BigShl(den, e);
680- { q, its whole part, by long division; num is left the remainder }
681- d := den; BigShl(d, 53);
682- q := 0;
683- for i := 53 downto 0 do begin
684- if BigCmp(num, d) >= 0 then begin BigSub(num, d); q := q or (qword(1) shl i) end;
685- BigShr1(d);
686- end;
687- if q >= qword(1) shl 53 then begin { a bit too many: it rounds }
688- half := odd(q); sticky := num.n > 0;
689- q := q shr 1; inc(e);
690- end else begin { the remainder against half of den }
691- BigShl(num, 1);
692- i := BigCmp(num, den);
693- half := i >= 0; sticky := i > 0;
694- end;
695- if half and (sticky or odd(q)) then begin
696- inc(q);
697- if q = qword(1) shl 53 then begin q := q shr 1; inc(e) end;
698- end;
699- if e > 971 then exit(false);
700- if q >= qword(1) shl 52 then b := qword(e + 1075) shl 52 or (q and (qword(1) shl 52 - 1))
701- else b := q; { below the least normal, e is -1074 }
702- Move(b, x, 8);
703- ReadReal := true;
704-end;
705-
706-procedure Number;
707-var start, i, d: longint; allDec: boolean; v: qword; s: shortstring;
708-begin
709- start := cur.pos;
710- allDec := true;
711- while cur.buf[cur.pos] in ['0'..'9', 'A'..'F'] do begin
712- if cur.buf[cur.pos] > '9' then allDec := false;
713- inc(cur.pos);
714- end;
715- if cur.buf[cur.pos] = 'H' then begin
716- v := 0;
717- for i := start to cur.pos - 1 do begin
718- if v shr 60 <> 0 then LexError(Text(start, cur.pos) + ' is too big for U64');
719- v := v * 16 + qword(HexVal(cur.buf[i]));
720- end;
721- inc(cur.pos);
722- tok := sInt;
723- ival := int64(v); { 16 digits are the bits of a 64-bit word }
724- end else if (cur.buf[cur.pos] = '.') and (cur.buf[cur.pos + 1] in ['0'..'9']) then begin
725- if not allDec then LexError('a decimal number has only the digits 0 to 9');
726- inc(cur.pos);
727- while cur.buf[cur.pos] in ['0'..'9'] do inc(cur.pos);
728- if cur.buf[cur.pos] = 'E' then begin
729- inc(cur.pos);
730- if cur.buf[cur.pos] in ['+', '-'] then inc(cur.pos);
731- if not (cur.buf[cur.pos] in ['0'..'9']) then LexError('expected a digit in the exponent');
732- while cur.buf[cur.pos] in ['0'..'9'] do inc(cur.pos);
733- end;
734- if cur.pos - start > 255 then LexError('a number has at most 255 characters');
735- SetLength(s, cur.pos - start);
736- Move(cur.buf[start], s[1], cur.pos - start);
737- if not ReadReal(s, rval) then LexError(Text(start, cur.pos) + ' is out of the range of F64');
738- tok := sReal;
739- end else begin
740- if not allDec then LexError('a hex number ends with H');
741- v := 0;
742- for i := start to cur.pos - 1 do begin
743- d := ord(cur.buf[i]) - ord('0');
744- if v > (qword(high(int64)) - qword(d)) div 10 then LexError(Text(start, cur.pos) + ' is too big for I64');
745- v := v * 10 + qword(d);
746- end;
747- tok := sInt;
748- ival := int64(v);
749- end;
750- if cur.buf[cur.pos] in ['A'..'Z', 'a'..'z', '_', '0'..'9'] then
751- LexError('a name can''t start with a digit');
752-end;
753-
754-procedure Next;
755-var c: char; start, h, v, i: longint;
756-begin
757- cur.prevEnd := cur.pos;
758- repeat
759- c := cur.buf[cur.pos];
760- while c in [' ', #9, #13, #10] do begin
761- if c = #10 then begin
762- inc(cur.line); cur.lineStart := cur.pos + 1
763- end;
764- inc(cur.pos);
765- c := cur.buf[cur.pos];
766- end;
767- if (c = '(') and (cur.buf[cur.pos + 1] = '*') then begin
768- Comment; c := ' '
769- end;
770- until c <> ' ';
771- cur.tokPos := cur.pos;
772- cur.tokLine := cur.line;
773- cur.tokLineStart := cur.lineStart;
774- case c of
775- 'A'..'Z', 'a'..'z', '_': begin
776- start := cur.pos;
777- repeat inc(cur.pos)
778- until not (cur.buf[cur.pos] in ['A'..'Z', 'a'..'z', '0'..'9', '_']);
779- if cur.pos - start > MaxIdent then LexError('a name has at most ' + IntStr(MaxIdent) + ' characters');
780- h := Intern(@cur.buf[start], cur.pos - start);
781- if (cur.pos - start = 1) and (c = '_') then tok := sBlank
782- else if h < NumWords then tok := TSym(ord(sAnd) + h)
783- else begin tok := sIdent; id := h end;
784- end;
785- '0'..'9': Number;
786- '''': begin
787- inc(cur.pos);
788- if cur.buf[cur.pos] = '''' then LexError('empty character');
789- v := LitChar(false);
790- if cur.buf[cur.pos] <> '''' then begin
791- { 'ab': several characters, as some languages write a string }
792- i := cur.pos;
793- while not (cur.buf[i] in ['''', #10, #0]) do inc(i);
794- if cur.buf[i] = '''' then MarkBytes(cur.tokPos, i + 1, 'a character is one character: the string is "' + Text(cur.tokPos + 1, i) + '"')
795- else LexError('character not closed');
796- end;
797- inc(cur.pos);
798- tok := sChar;
799- ival := v;
800- end;
801- '"': begin
802- inc(cur.pos);
803- slen := 0;
804- while cur.buf[cur.pos] <> '"' do begin
805- v := LitChar(true);
806- if v < 0 then Put(-1 - v) else PutUtf8(v);
807- end;
808- inc(cur.pos);
809- sbuf[slen] := 0;
810- tok := sString;
811- end;
812- '+': begin inc(cur.pos); tok := sPlus end;
813- '-': begin inc(cur.pos); tok := sMinus end;
814- '*': begin inc(cur.pos); tok := sTimes end;
815- '/': begin inc(cur.pos); tok := sSlash end;
816- '=':
817- if cur.buf[cur.pos + 1] = '=' then Slip(2, sEql, 'comparing is written =, not ==')
818- else begin inc(cur.pos); tok := sEql end;
819- '&':
820- if cur.buf[cur.pos + 1] = '&' then Slip(2, sAnd, '"and" is written and, not &&')
821- else begin inc(cur.pos); tok := sAmp end;
822- '#': begin inc(cur.pos); tok := sNeq end;
823- '<': begin
824- inc(cur.pos);
825- if cur.buf[cur.pos] = '=' then begin inc(cur.pos); tok := sLeq end
826- else tok := sLss;
827- end;
828- '>': begin
829- inc(cur.pos);
830- if cur.buf[cur.pos] = '=' then begin inc(cur.pos); tok := sGeq end
831- else tok := sGtr;
832- end;
833- ':': begin
834- inc(cur.pos);
835- if cur.buf[cur.pos] = '=' then begin inc(cur.pos); tok := sBecomes end
836- else tok := sColon;
837- end;
838- ';': begin inc(cur.pos); tok := sSemicolon end;
839- ',': begin inc(cur.pos); tok := sComma end;
840- '.': begin
841- inc(cur.pos);
842- if cur.buf[cur.pos] = '.' then begin
843- inc(cur.pos);
844- if cur.buf[cur.pos] = '.' then begin inc(cur.pos); tok := sEllipsis end
845- else tok := sUpto;
846- end else tok := sPeriod;
847- end;
848- '(': begin inc(cur.pos); tok := sLparen end;
849- ')': begin inc(cur.pos); tok := sRparen end;
850- '[': begin inc(cur.pos); tok := sLbrak end;
851- ']': begin inc(cur.pos); tok := sRbrak end;
852- '{': begin inc(cur.pos); tok := sLbrace end;
853- '}': begin inc(cur.pos); tok := sRbrace end;
854- '^': begin inc(cur.pos); tok := sArrow end;
855- '|':
856- if cur.buf[cur.pos + 1] = '|' then Slip(2, sOr, '"or" is written or, not ||')
857- else begin inc(cur.pos); tok := sBar end;
858- '~': begin inc(cur.pos); tok := sTilde end;
859- '!':
860- if cur.buf[cur.pos + 1] = '=' then Slip(2, sNeq, '"not equal" is written #, not !=')
861- else Slip(1, sNot, '"not" is written not, not !');
862- #0: begin
863- if cur.pos < cur.len then MarkBytes(cur.pos, cur.pos + 1, 'NUL byte in the text');
864- tok := sEof;
865- end;
866- else
867- if byte(c) >= $80 then
868- LexError('only ASCII outside strings, characters and comments');
869- MarkBytes(cur.pos, cur.pos + 1, 'unexpected character "' + c + '"');
870- end;
871-end;
872-
873-var i: longint;
874-
875-initialization
876- poolCap := 1 shl 16;
877- pool := GetMem(poolCap);
878- nameCap := 1 shl 12;
879- nameOff := GetMem(nameCap * 4);
880- nameLen := GetMem(nameCap * 4);
881- nameHash := GetMem(nameCap * 4);
882- tableMask := 2 * nameCap - 1;
883- table := GetMem((tableMask + 1) * 4);
884- FillChar(table^, (tableMask + 1) * 4, 0);
885- for i := 0 to NumWords - 1 do Intern(@Words[i][1], length(Words[i]));
886-end.

src/sym.pas deleted +0 -646

@@ -1,646 +0,0 @@
1-{ sym.pas: types, objects and scopes.
2-
3- Every name the program declares becomes an object (TObj): a constant,
4- type, variable, procedure, module, record field, variant case or
5- built-in. Every type is a TType. Objects are found through one hash
6- table keyed by scope and name, so a lookup costs the same however
7- big a module grows. A scope is just a number: the universe is 0,
8- and each module, procedure, record and match arm gets a fresh one.
9-
10- Depends on: scan, for names and errors.
11- Leaves out: code. Where a variable lives is decided here (frame
12- offsets, chunk numbers), but nothing is emitted. }
13-
14-unit sym;
15-
16-{$mode objfpc}{$H-}
17-
18-interface
19-
20-uses scan, diag;
21-
22-type
23- TForm = (fNone, fBool, fInt, fReal, fConst, fNil, fStr, fPtr, fArray,
24- fSlice, fRecord, fVariant, fProc, fEnum, fSet, fError);
25- { fConst is the type of an untyped integer constant; fStr of a string
26- literal, whose length the literal carries. F32 and F64 are fReal,
27- told apart by size, and so is tRConst, an untyped real constant. }
28-
29- TClass = (oConst, oType, oVar, oProc, oModule, oField, oCase, oBuiltin);
30-
31- PType = ^TType;
32- PObj = ^TObj;
33- PModule = ^TModule;
34- PImport = ^TImport;
35- PLib = ^TLib;
36-
37- TType = record
38- form: TForm;
39- size, align: int64;
40- signed: boolean; { fInt }
41- vol: boolean; { fPtr: ^VOLATILE }
42- packd: boolean; { fRecord }
43- variadic: boolean; { fProc: ends in ... }
44- tuple: boolean; { fRecord: the results of a procedure that has several }
45- base: PType; { fPtr, fArray, fSlice: what it holds; fProc: result }
46- len: int64; { fArray: elements; fProc: parameters; fVariant: cases; a tuple: results }
47- fields: PObj; { fRecord: fields; fVariant: cases; fProc: parameters }
48- scope: longint; { fRecord: the scope of its fields }
49- fwd: longint; { fPtr whose base isn't declared yet: its name, else -1 }
50- obj: PObj; { the declaration that names it, or nil }
51- module: PModule; { the module that built it }
52- end;
53-
54- TObj = record
55- cls: TClass;
56- name: longint;
57- exported: boolean;
58- typ: PType;
59- next: PObj; { the next in its list: scope, fields, parameters }
60- scope: longint; { where it is declared }
61- pos: TPos; { where its name is declared, for messages }
62- val: int64; { oConst: value; oBuiltin: which; oCase: tag;
63- oField: offset; oVar: frame offset }
64- chunk: longint; { global oVar, oProc, string oConst: its chunk }
65- lev: integer; { oVar: 0 for a module variable, 1 for a local }
66- ind: boolean; { oVar: the frame slot holds the variable's address }
67- off: int64; { oVar with ind: added to that address }
68- isVar: boolean; { a var parameter }
69- param: boolean; { oVar: a parameter }
70- used: boolean; { named somewhere but in its own body }
71- read: boolean; { oVar: named other than as what := assigns }
72- fwd: boolean; { oProc: declared forward, no body yet }
73- isCode: boolean; { oProc: a code procedure }
74- openEnd: boolean; { oProc: has results, and may reach its end }
75- reg: longint; { oVar: the register it lives in, or 0 if in memory;
76- for a slice, the one its pointer is in }
77- reg2: longint; { oVar: a slice in registers: the one its length is in }
78- ext: boolean; { oProc, oVar: C's, reached through its chunk, which
79- holds its address }
80- fields: PObj; { oCase: its fields }
81- module: PModule; { oModule: the module; others: where declared }
82- link: PObj; { the next declaration of its module, top-level or
83- local }
84- end;
85-
86- { The arguments of a generic module's instance: a type, or a
87- procedure (o) and its type. }
88- TArgs = record
89- n: longint;
90- t: array[0..7] of PType;
91- o: array[0..7] of PObj;
92- pos: array[0..7] of TPos; { where each argument is, for messages }
93- at: TPos; { where the import is }
94- end;
95-
96- TImport = record
97- module: PModule;
98- next: PImport;
99- end;
100-
101- { A library a module links, by its name, as interned }
102- TLib = record
103- name: longint;
104- next: PLib;
105- end;
106-
107- TModule = record
108- name: longint;
109- sname: longint; { the name of its symbols: List(I64) for an instance }
110- args: TArgs;
111- scope: longint;
112- path: shortstring;
113- first, last: PObj; { its top-level declarations, in order }
114- locals, lastLocal: PObj; { its procedures' declarations, in order }
115- imports: PImport;
116- body: longint; { the chunk of its body, or -1 }
117- done: boolean; { compiled to the end }
118- checkOnly: boolean; { read only to check another file's interface }
119- used: boolean; { imported, through others, by the main module }
120- usesC: boolean; { has an extern, or links a library }
121- linkStatic: boolean; { says link static }
122- libs: PLib; { the libraries it links }
123- next: PModule; { modules in the order they were finished }
124- end;
125-
126-const
127- { built-in procedures }
128- bSize = 0; bAdr = 1; bLen = 2; bNew = 3; bMsg = 4; bSyscall = 5;
129- bFence = 6; bCas = 7; bXchg = 8; bXadd = 9; bArgc = 10; bArgv = 11;
130- bInc = 12; bDec = 13; bCopy = 14;
131-
132- MaxDepth = 64; { scopes open at once }
133-
134-var
135- tI8, tI16, tI32, tI64, tU8, tU16, tU32, tU64: PType;
136- tInt, tUInt: PType; { INT and UINT, as big as an address: 8 bytes here }
137- tBool, tF32, tReal, tRConst, tError, tConst, tNil, tStr, tNone, tPtrU8, tBytes: PType;
138- tPoison: PType; { of a name reported as not declared }
139- curModule: PModule;
140-
141-function NewType(form: TForm; size, align: int64): PType;
142-function NewObj(cls: TClass; name: longint; typ: PType): PObj;
143-function NewScope: longint;
144-procedure OpenScope(s: longint);
145-procedure CloseScope;
146-function ScopeDepth: longint;
147-procedure CutScopes(d: longint);
148-function TopScope: longint;
149-procedure SaveScopes(var d: longint; var saved: array of longint);
150-procedure RestoreScopes(d: longint; const saved: array of longint);
151-procedure Insert(obj: PObj; s: longint);
152-function Find(s, name: longint): PObj;
153-function Lookup(name: longint): PObj;
154-function Closest(name, s: longint): PObj;
155-
156-function AlignUp(x, a: int64): int64;
157-function Same(a, b: PType): boolean;
158-function IsInt(t: PType): boolean;
159-function IsScalar(t: PType): boolean;
160-function IsAggregate(t: PType): boolean;
161-function InTwoRegs(t: PType): boolean;
162-function BehindPointer(t: PType): boolean;
163-function Fits(v: int64; t: PType): boolean;
164-function TypeName(t: PType): shortstring;
165-function Fingerprint(o: PObj): qword;
166-
167-implementation
168-
169-uses math;
170-
171-type
172- PObjTab = ^TObjTab;
173- TObjTab = array[0..MaxInt div 16] of PObj;
174-
175-var
176- scopes: array[0..MaxDepth - 1] of longint;
177- depth: longint;
178- nextScope: longint;
179- hashTab: PObjTab;
180- hashMask, hashCount: longint;
181-
182-function NewType(form: TForm; size, align: int64): PType;
183-var t: PType;
184-begin
185- New(t);
186- FillChar(t^, SizeOf(TType), 0);
187- t^.form := form;
188- t^.size := size;
189- t^.align := align;
190- t^.fwd := -1;
191- t^.module := curModule;
192- NewType := t;
193-end;
194-
195-function NewObj(cls: TClass; name: longint; typ: PType): PObj;
196-var o: PObj;
197-begin
198- New(o);
199- FillChar(o^, SizeOf(TObj), 0);
200- o^.cls := cls;
201- o^.name := name;
202- o^.typ := typ;
203- o^.chunk := -1;
204- o^.module := curModule;
205- o^.pos := TokPos;
206- NewObj := o;
207-end;
208-
209-{ Scopes }
210-
211-function NewScope: longint;
212-begin
213- inc(nextScope);
214- NewScope := nextScope;
215-end;
216-
217-procedure OpenScope(s: longint);
218-begin
219- if depth = MaxDepth then Mark('scopes nested more than ' + IntStr(MaxDepth) + ' deep');
220- scopes[depth] := s;
221- inc(depth);
222-end;
223-
224-procedure CloseScope;
225-begin
226- dec(depth);
227-end;
228-
229-{ An imported module is compiled in the middle of another, and must
230- see only the universe and itself. }
231-procedure SaveScopes(var d: longint; var saved: array of longint);
232-var i: longint;
233-begin
234- d := depth;
235- for i := 0 to depth - 1 do saved[i] := scopes[i];
236- depth := 1;
237-end;
238-
239-procedure RestoreScopes(d: longint; const saved: array of longint);
240-var i: longint;
241-begin
242- depth := d;
243- for i := 0 to depth - 1 do scopes[i] := saved[i];
244-end;
245-
246-function ScopeDepth: longint;
247-begin
248- ScopeDepth := depth;
249-end;
250-
251-{ Closes the scopes opened since there were d, after an error }
252-procedure CutScopes(d: longint);
253-begin
254- depth := d;
255-end;
256-
257-function TopScope: longint;
258-begin
259- TopScope := scopes[depth - 1];
260-end;
261-
262-{ Where the search for name in scope s starts in the hash table: each
263- number is multiplied by an odd constant near 2^32 or 2^16 over the
264- golden ratio (Knuth's multiplicative hashing), which spreads the low
265- bits the mask keeps. }
266-function Slot(s, name: longint): longint;
267-begin
268- Slot := longint((longword(s) * 2654435761 xor longword(name) * 40503) and longword(hashMask));
269-end;
270-
271-{ Doubles the table, which Insert keeps at most half full so that the
272- linear probing stays short, and puts every entry in its new slot. }
273-procedure Rehash;
274-var old: PObjTab; n, i, j: longint;
275-begin
276- old := hashTab;
277- n := hashMask + 1;
278- hashMask := n * 2 - 1;
279- hashTab := GetMem(n * 2 * SizeOf(PObj));
280- FillChar(hashTab^, n * 2 * SizeOf(PObj), 0);
281- for i := 0 to n - 1 do
282- if old^[i] <> nil then begin
283- j := Slot(old^[i]^.scope, old^[i]^.name);
284- while hashTab^[j] <> nil do j := (j + 1) and hashMask;
285- hashTab^[j] := old^[i];
286- end;
287- FreeMem(old);
288-end;
289-
290-procedure Insert(obj: PObj; s: longint);
291-var i: longint; o: PObj;
292-begin
293- i := Slot(s, obj^.name);
294- o := hashTab^[i];
295- while o <> nil do begin
296- if (o^.scope = s) and (o^.name = obj^.name) then begin
297- Error(obj^.pos, NameOf(obj^.name) + ' is declared twice');
298- Note(o^.pos, 'the first one is here');
299- Fail;
300- end;
301- i := (i + 1) and hashMask;
302- o := hashTab^[i];
303- end;
304- obj^.scope := s;
305- hashTab^[i] := obj;
306- inc(hashCount);
307- if hashCount * 2 > hashMask then Rehash;
308-end;
309-
310-function Find(s, name: longint): PObj;
311-var i: longint; o: PObj;
312-begin
313- i := Slot(s, name);
314- o := hashTab^[i];
315- while o <> nil do begin
316- if (o^.scope = s) and (o^.name = name) then exit(o);
317- i := (i + 1) and hashMask;
318- o := hashTab^[i];
319- end;
320- Find := nil;
321-end;
322-
323-function Lookup(name: longint): PObj;
324-var i: longint; o: PObj;
325-begin
326- for i := depth - 1 downto 0 do begin
327- o := Find(scopes[i], name);
328- if o <> nil then exit(o);
329- end;
330- Lookup := nil;
331-end;
332-
333-{ How far apart two names are: the edits, a character put in, taken out,
334- changed or swapped with the next, that make one the other, ignoring
335- case. }
336-function Distance(const a, b: shortstring): longint;
337-var d: array[0..MaxIdent + 1, 0..MaxIdent + 1] of longint; i, j, c: longint;
338-begin
339- for i := 0 to length(a) do d[i, 0] := i;
340- for j := 0 to length(b) do d[0, j] := j;
341- for i := 1 to length(a) do
342- for j := 1 to length(b) do begin
343- c := ord(UpCase(a[i]) <> UpCase(b[j]));
344- d[i, j] := Min(Min(d[i - 1, j] + 1, d[i, j - 1] + 1), d[i - 1, j - 1] + c);
345- if (i > 1) and (j > 1) and (UpCase(a[i]) = UpCase(b[j - 1]))
346- and (UpCase(a[i - 1]) = UpCase(b[j])) then
347- d[i, j] := Min(d[i, j], d[i - 2, j - 2] + 1);
348- end;
349- Distance := d[length(a), length(b)];
350-end;
351-
352-{ The name spelled most like name, for "did you mean": in scope s, if
353- it can be reached from here, or in the scopes in reach if s < 0; nil
354- if none is within an edit for every three characters. Only after an
355- error, so it looks at every object. }
356-function Closest(name, s: longint): PObj;
357-var i, j, d, best: longint; o: PObj; n: shortstring; reach: boolean;
358-begin
359- n := NameOf(name);
360- best := length(n) div 3 + 1;
361- Closest := nil;
362- for i := 0 to hashMask do begin
363- o := hashTab^[i];
364- if (o = nil) or (o^.name = name) or (o^.name < 0) or (o^.typ = tPoison) then continue;
365- if s >= 0 then reach := (o^.scope = s) and (o^.exported or (o^.module = curModule))
366- else begin
367- reach := false;
368- for j := 0 to depth - 1 do reach := reach or (o^.scope = scopes[j]);
369- end;
370- if reach then begin
371- d := Distance(n, NameOf(o^.name));
372- if d < best then begin best := d; Closest := o end;
373- end;
374- end;
375-end;
376-
377-{ Types }
378-
379-function AlignUp(x, a: int64): int64;
380-begin
381- AlignUp := (x + a - 1) div a * a;
382-end;
383-
384-function IsInt(t: PType): boolean;
385-begin
386- IsInt := t^.form in [fInt, fConst];
387-end;
388-
389-function IsScalar(t: PType): boolean;
390-begin
391- IsScalar := t^.form in [fBool, fInt, fReal, fConst, fNil, fPtr, fProc,
392- fEnum, fSet, fError];
393-end;
394-
395-function IsAggregate(t: PType): boolean;
396-begin
397- IsAggregate := t^.form in [fArray, fSlice, fRecord, fVariant];
398-end;
399-
400-{ Whether a procedure's result t is two words, which come back in rax
401- and rdx, as System V returns a struct of two integers: a slice (its
402- pointer, then its length), or two results that are each a single
403- value of 8 bytes at most and not a real. }
404-function InTwoRegs(t: PType): boolean;
405-
406- function OneWord(f: PObj): boolean;
407- begin
408- OneWord := IsScalar(f^.typ) and (f^.typ^.form <> fReal) and (f^.typ^.size <= 8);
409- end;
410-
411-begin
412- if t^.form = fSlice then exit(true);
413- InTwoRegs := t^.tuple and (t^.len = 2) and OneWord(t^.fields) and OneWord(t^.fields^.next);
414-end;
415-
416-{ Whether a procedure's result t comes back in memory the caller
417- provides, whose address the caller passes as a hidden first argument,
418- in rdi: any result that is neither one value, in rax or xmm0, nor two
419- words, in rax and rdx. }
420-function BehindPointer(t: PType): boolean;
421-begin
422- BehindPointer := IsAggregate(t) and not InTwoRegs(t);
423-end;
424-
425-function Fits(v: int64; t: PType): boolean;
426-begin
427- if t^.form <> fInt then exit(t^.form = fConst);
428- case t^.size of
429- 1: if t^.signed then Fits := (v >= -128) and (v <= 127)
430- else Fits := (v >= 0) and (v <= 255);
431- 2: if t^.signed then Fits := (v >= -32768) and (v <= 32767)
432- else Fits := (v >= 0) and (v <= 65535);
433- 4: if t^.signed then Fits := (v >= -2147483648) and (v <= 2147483647)
434- else Fits := (v >= 0) and (v <= 4294967295);
435- else Fits := t^.signed or (v >= 0);
436- end;
437-end;
438-
439-{ Structural sameness of two types. Named types are the same only if
440- they are one declaration; a type with no name is the same as another
441- built alike. }
442-function Alike(a, b: PType): boolean;
443-var p, q: PObj;
444-begin
445- if a = b then exit(true);
446- if a^.form <> b^.form then exit(false);
447- case a^.form of
448- fPtr: Alike := (a^.vol = b^.vol) and Same(a^.base, b^.base);
449- fArray: Alike := (a^.len = b^.len) and Same(a^.base, b^.base);
450- fSlice, fSet: Alike := Same(a^.base, b^.base);
451- fProc, fRecord: begin
452- { a record is the same only as itself, but for several results }
453- if (a^.form = fRecord) and not (a^.tuple and b^.tuple) then exit(false);
454- if (a^.len <> b^.len) or (a^.variadic <> b^.variadic) then exit(false);
455- if (a^.base = nil) <> (b^.base = nil) then exit(false);
456- if (a^.base <> nil) and not Same(a^.base, b^.base) then exit(false);
457- p := a^.fields; q := b^.fields;
458- while p <> nil do begin
459- if (p^.isVar <> q^.isVar) or not Same(p^.typ, q^.typ) then exit(false);
460- p := p^.next; q := q^.next;
461- end;
462- Alike := true;
463- end;
464- else Alike := false;
465- end;
466-end;
467-
468-function Same(a, b: PType): boolean;
469-begin
470- if a = b then exit(true);
471- if (a = nil) or (b = nil) then exit(false);
472- if (a^.obj <> nil) and (b^.obj <> nil) then exit(false);
473- Same := Alike(a, b);
474-end;
475-
476-function TypeName(t: PType): shortstring;
477-var s: shortstring; f: PObj;
478-begin
479- if t = nil then exit('nothing');
480- if t^.obj <> nil then begin
481- if (t^.obj^.module <> nil) and (t^.obj^.module <> curModule) then
482- exit(NameOf(t^.obj^.module^.sname) + '.' + NameOf(t^.obj^.name));
483- exit(NameOf(t^.obj^.name));
484- end;
485- case t^.form of
486- fConst: TypeName := 'an integer constant';
487- fReal: TypeName := 'a real constant';
488- fNil: TypeName := 'nil';
489- fStr: TypeName := 'a string';
490- fPtr: if t^.vol then TypeName := '^VOLATILE ' + TypeName(t^.base)
491- else TypeName := '^' + TypeName(t^.base);
492- fArray: begin Str(t^.len, s); TypeName := '[' + s + ']' + TypeName(t^.base) end;
493- fSlice: TypeName := '[]' + TypeName(t^.base);
494- fRecord: if not t^.tuple then TypeName := 'record'
495- else begin
496- s := '(';
497- f := t^.fields;
498- while f <> nil do begin
499- s := s + TypeName(f^.typ);
500- f := f^.next;
501- if f <> nil then s := s + ', ';
502- end;
503- TypeName := s + ')';
504- end;
505- fVariant: TypeName := 'variant';
506- fProc: begin
507- s := 'proc(';
508- f := t^.fields;
509- while f <> nil do begin
510- if f^.isVar then s := s + 'var ';
511- s := s + TypeName(f^.typ);
512- f := f^.next;
513- if f <> nil then s := s + ', ';
514- end;
515- s := s + ')';
516- if t^.base <> nil then s := s + ': ' + TypeName(t^.base);
517- TypeName := s;
518- end;
519- else TypeName := '?';
520- end;
521-end;
522-
523-{ A fingerprint of what a declaration exports, for the interface
524- check: two files of one module export the same thing when their
525- fingerprints agree. A named type counts by its name, so that a type
526- declared in each file stands for the other's. }
527-procedure Mix(var h: qword; v: int64);
528-begin
529- h := (h xor qword(v)) * 1099511628211; { FNV-1a's 64-bit prime }
530-end;
531-
532-procedure Shape(var h: qword; t: PType; top: boolean);
533-var f, g: PObj;
534-begin
535- if t = nil then begin Mix(h, -1); exit end;
536- if (t^.obj <> nil) and not top then begin
537- Mix(h, t^.obj^.name);
538- if t^.obj^.module <> nil then Mix(h, t^.obj^.module^.sname);
539- exit;
540- end;
541- Mix(h, ord(t^.form));
542- Mix(h, ord(t^.vol) + 2 * ord(t^.variadic));
543- Mix(h, t^.len);
544- if t^.form in [fPtr, fArray, fSlice, fProc, fSet] then Shape(h, t^.base, false);
545- f := t^.fields;
546- while f <> nil do begin
547- if (t^.form <> fRecord) or f^.exported then begin
548- Mix(h, f^.name);
549- Mix(h, ord(f^.isVar));
550- Shape(h, f^.typ, false);
551- g := f^.fields;
552- while g <> nil do begin Shape(h, g^.typ, false); g := g^.next end;
553- end;
554- f := f^.next;
555- end;
556-end;
557-
558-function Fingerprint(o: PObj): qword;
559-var h: qword; f: PObj;
560-begin
561- h := 14695981039346656037; { FNV-1a's 64-bit offset basis }
562- Mix(h, ord(o^.cls));
563- if o^.cls = oCase then begin
564- Mix(h, o^.val);
565- f := o^.fields;
566- while f <> nil do begin Shape(h, f^.typ, false); f := f^.next end;
567- end else Shape(h, o^.typ, o^.cls = oType);
568- Fingerprint := h;
569-end;
570-
571-{ The universe }
572-
573-function Basic(const name: shortstring; form: TForm; size: int64; signed: boolean): PType;
574-var t: PType; o: PObj;
575-begin
576- t := NewType(form, size, size);
577- t^.signed := signed;
578- o := NewObj(oType, Intern(@name[1], length(name)), t);
579- o^.exported := true;
580- t^.obj := o;
581- Insert(o, 0);
582- Basic := t;
583-end;
584-
585-procedure Enter(const name: shortstring; cls: TClass; t: PType; v: int64);
586-var o: PObj;
587-begin
588- o := NewObj(cls, Intern(@name[1], length(name)), t);
589- o^.val := v;
590- o^.exported := true;
591- Insert(o, 0);
592-end;
593-
594-initialization
595- hashMask := (1 shl 14) - 1;
596- hashTab := GetMem((hashMask + 1) * SizeOf(PObj));
597- FillChar(hashTab^, (hashMask + 1) * SizeOf(PObj), 0);
598- depth := 1;
599- scopes[0] := 0;
600- nextScope := 0;
601- curModule := nil;
602- tI8 := Basic('I8', fInt, 1, true);
603- tI16 := Basic('I16', fInt, 2, true);
604- tI32 := Basic('I32', fInt, 4, true);
605- tI64 := Basic('I64', fInt, 8, true);
606- tU8 := Basic('U8', fInt, 1, false);
607- tU16 := Basic('U16', fInt, 2, false);
608- tU32 := Basic('U32', fInt, 4, false);
609- tU64 := Basic('U64', fInt, 8, false);
610- tInt := Basic('INT', fInt, 8, true);
611- tUInt := Basic('UINT', fInt, 8, false);
612- tBool := Basic('BOOL', fBool, 1, false);
613- tF32 := Basic('F32', fReal, 4, false);
614- tReal := Basic('F64', fReal, 8, false);
615- tRConst := NewType(fReal, 8, 8);
616- tError := Basic('ERROR', fError, 8, false);
617- tConst := NewType(fConst, 8, 8);
618- tConst^.signed := true;
619- tNil := NewType(fNil, 8, 8);
620- tStr := NewType(fStr, 0, 1);
621- tNone := NewType(fNone, 0, 1);
622- tPtrU8 := NewType(fPtr, 8, 8);
623- tPtrU8^.base := tU8;
624- tBytes := NewType(fSlice, 16, 8);
625- tBytes^.base := tU8;
626- tPoison := NewType(fInt, 8, 8);
627- tPoison^.signed := true;
628- Enter('true', oConst, tBool, 1);
629- Enter('false', oConst, tBool, 0);
630- Enter('nil', oConst, tNil, 0);
631- Enter('SIZE', oBuiltin, nil, bSize);
632- Enter('ADR', oBuiltin, nil, bAdr);
633- Enter('LEN', oBuiltin, nil, bLen);
634- Enter('NEW', oBuiltin, nil, bNew);
635- Enter('MSG', oBuiltin, nil, bMsg);
636- Enter('SYSCALL', oBuiltin, nil, bSyscall);
637- Enter('FENCE', oBuiltin, nil, bFence);
638- Enter('CAS', oBuiltin, nil, bCas);
639- Enter('XCHG', oBuiltin, nil, bXchg);
640- Enter('XADD', oBuiltin, nil, bXadd);
641- Enter('ARGC', oBuiltin, nil, bArgc);
642- Enter('ARGV', oBuiltin, nil, bArgv);
643- Enter('INC', oBuiltin, nil, bInc);
644- Enter('DEC', oBuiltin, nil, bDec);
645- Enter('COPY', oBuiltin, nil, bCopy);
646-end.

src/test/AsmDump.pas added +46 -0

@@ -0,0 +1,46 @@
1+{ Assembles the instructions in the file of the argument, as the body of
2+ a code procedure that ends in end, and prints the bytes and the
3+ listing: the seed's side of a test of the assembler in src/X64.raz,
4+ whose AsmDump.raz does the same and prints the same. Constants are
5+ numbers, with a minus sign, and sums of them. }
6+program asmdump;
7+{$mode objfpc}{$H-}
8+uses diag, scan, chunk, x64;
9+var i: longint; path: string;
10+
11+function ConstVal(whole: boolean): int64;
12+var neg: boolean; v: int64;
13+begin
14+ neg := tok = sMinus;
15+ if neg then Next;
16+ if tok <> sInt then Mark('expected a number');
17+ v := ival;
18+ Next;
19+ if neg then v := -v;
20+ while whole and (tok in [sPlus, sMinus]) do begin
21+ neg := tok = sMinus;
22+ Next;
23+ if tok <> sInt then Mark('expected a number');
24+ if neg then v := v - ival else v := v + ival;
25+ Next;
26+ end;
27+ ConstVal := v;
28+end;
29+
30+begin
31+ if Open(ParamStr(1)) <> '' then Fatal('no file');
32+ path := 'lib/Rt.raz';
33+ curFile := Intern(@path[1], length(path));
34+ listing := true;
35+ NewChunk(secText, 0, 0);
36+ BeginChunk(0);
37+ NoteLine(1, 1);
38+ Next;
39+ Assemble(@ConstVal);
40+ EndChunk(0);
41+ chunks^[0].live := true;
42+ for i := 0 to pc - 1 do write(HexStr(code^[i], 2));
43+ writeln;
44+ List(0);
45+ Finish;
46+end.

src/test/AsmDump.raz added +55 -0

@@ -0,0 +1,55 @@
1+(* Assembles the instructions in the file of the argument, as the body of
2+ a code procedure that ends in end, and prints the bytes and the
3+ listing: src/X64.raz's assembler's side of a test against the seed's,
4+ AsmDump.pas, which prints the same. Constants are numbers, with a
5+ minus sign, and sums of them. *)
6+module AsmDump;
7+import Out, Files, Diag, Scan, Chunk, X64;
8+
9+proc number(neg: BOOL): (I64, ERROR);
10+var v: I64;
11+begin
12+ if Scan.tok # Scan.sInt then return 0, Scan.mark("expected a number"); end;
13+ v := Scan.ival;
14+ Scan.next;
15+ if neg then v := -v; end;
16+ return v, nil;
17+end;
18+
19+proc constant(whole: BOOL): (I64, ERROR);
20+var neg: BOOL; v, w: I64;
21+begin
22+ neg := Scan.tok = Scan.sMinus;
23+ if neg then Scan.next; end;
24+ v := try number(neg);
25+ while whole and ((Scan.tok = Scan.sPlus) or (Scan.tok = Scan.sMinus)) do
26+ neg := Scan.tok = Scan.sMinus;
27+ Scan.next;
28+ w := try number(neg);
29+ v := v + w;
30+ end;
31+ return v, nil;
32+end;
33+
34+proc main*;
35+var i: INT; path: []U8; err: ERROR;
36+begin
37+ if LEN(Scan.open(Files.arg(1))) # 0 then Diag.fatal("no file"); end;
38+ path := "lib/Rt.raz";
39+ Chunk.setCurFile(Scan.intern(ADR(path[0]), LEN(path)));
40+ X64.setListing(true);
41+ _ := Chunk.newChunk(Chunk.secText, 0, 0);
42+ Chunk.beginChunk(0);
43+ Chunk.noteLine(1, 1);
44+ Scan.next;
45+ err := X64.assemble(constant);
46+ if err # nil then Diag.finish; end;
47+ Chunk.endChunk(0);
48+ Chunk.setLive(0);
49+ for i := 0 to Chunk.pc - 1 do Out.hex(U64(Chunk.text[i]), 2); end;
50+ Out.ln;
51+ X64.list(0);
52+ Diag.finish;
53+end;
54+
55+end AsmDump.

src/test/ChunkDump.pas added +89 -0

@@ -0,0 +1,89 @@
1+{ Makes a program of chunks by a fixed pseudo-random script and prints
2+ all of it: the seed's side of a test of src/Chunk.raz, whose
3+ ChunkDump.raz does the same and prints the same. }
4+program chunkdump;
5+{$mode objfpc}{$H-}
6+uses diag, scan, chunk;
7+var
8+ seed: int64;
9+ names: array[0..7] of longint;
10+ i, k, n, op, c, sum, open, x, y, z: longint;
11+ b: array[0..63] of byte;
12+
13+function Rnd(n: longint): longint;
14+begin
15+ seed := (seed * 1103515245 + 12345) and $7FFFFFFF;
16+ Rnd := (seed shr 8) mod n;
17+end;
18+
19+begin
20+ seed := 7;
21+ for i := 0 to 7 do begin b[0] := 97 + i; names[i] := Intern(@b[0], 1) end;
22+ open := -1;
23+ sum := 0;
24+ for k := 1 to 30000 do begin
25+ op := Rnd(16);
26+ case op of
27+ 0..3: Put1(Rnd(256));
28+ 4: begin x := Rnd(1 shl 30); y := Rnd(1 shl 30); Put4(x - y) end;
29+ 5: begin x := Rnd(1 shl 30); y := Rnd(1 shl 30); Put8(int64(x) * 4096 - y) end;
30+ 6: begin
31+ if open >= 0 then EndChunk(open);
32+ x := Rnd(5); y := Rnd(9);
33+ open := NewChunk(secText, x - 1, y - 1);
34+ BeginChunk(open);
35+ end;
36+ 7: begin x := Rnd(8); curFile := names[x]; x := Rnd(300); y := Rnd(80); NoteLine(x, y) end;
37+ 8: if numChunks > 0 then begin x := Rnd(numChunks); y := Rnd(100); AddFixup(pc, x, y - 50) end;
38+ 9: if (open >= 0) and (pc - chunks^[open].start > 8) then begin x := Rnd(6); TakeBack(x) end;
39+ 10: begin
40+ x := Rnd(5); y := Rnd(9);
41+ c := NewChunk(secRodata, x - 1, y - 1);
42+ n := Rnd(64);
43+ for i := 0 to n - 1 do b[i] := Rnd(256);
44+ x := Rnd(4);
45+ SetData(c, @b[0], n, 1 shl x);
46+ n := Rnd(4);
47+ for i := 1 to n do begin x := Rnd(8); y := Rnd(numChunks); z := Rnd(10); AddDataFixup(c, x * 8, y, z) end;
48+ end;
49+ 11: begin
50+ x := Rnd(5); y := Rnd(9);
51+ c := NewChunk(secBss, x - 1, y - 1);
52+ x := Rnd(100); y := Rnd(4);
53+ SetBss(c, x, 1 shl y);
54+ end;
55+ 12: begin x := Rnd(8); c := ExternChunk(names[x]) end;
56+ 13: if numChunks > 0 then begin
57+ x := Rnd(numChunks); y := Rnd(8); z := Rnd(200); n := Rnd(5);
58+ NoteVar(x, names[y], z - 100, n);
59+ end;
60+ 14: if pc >= 8 then begin
61+ x := Rnd(1 shl 30); y := Rnd(1 shl 30);
62+ Put4At(pc - 8, x - y);
63+ sum := (sum + Get4At(pc - 8)) and $FFFFFF;
64+ end;
65+ 15: if numChunks > 0 then begin
66+ x := Rnd(numChunks); chunks^[x].live := true;
67+ x := Rnd(numChunks); y := Rnd(1 shl 30); chunks^[x].adr := y;
68+ end;
69+ end;
70+ end;
71+ if open >= 0 then EndChunk(open);
72+ writeln('sum ', sum, ' pc ', pc, ' rolen ', rolen);
73+ for i := 0 to numChunks - 1 do
74+ with chunks^[i] do
75+ writeln('C ', i, ' ', ord(sec), ' ', start, ' ', size, ' ', align, ' ', firstFix, ' ', numFix, ' ',
76+ module, ' ', name, ' ', adr, ' ', ord(live), ' ', ord(ext), ' ', ChunkName(i));
77+ for i := 0 to numFixups - 1 do
78+ writeln('F ', fixups^[i].at, ' ', fixups^[i].chunk, ' ', fixups^[i].addend);
79+ for i := 0 to numDataFixups - 1 do
80+ writeln('D ', dataFixups^[i].at, ' ', dataFixups^[i].chunk, ' ', dataFixups^[i].addend);
81+ for i := 0 to numLines - 1 do
82+ writeln('L ', lines^[i].at, ' ', lines^[i].chunk, ' ', lines^[i].path, ' ', lines^[i].line, ' ', lines^[i].col);
83+ for i := 0 to numVarNotes - 1 do
84+ writeln('V ', varNotes[i].chunk, ' ', varNotes[i].name, ' ', varNotes[i].off, ' ', varNotes[i].kind);
85+ for i := 0 to pc - 1 do write(HexStr(code^[i], 2));
86+ writeln;
87+ for i := 0 to rolen - 1 do write(HexStr(rodata^[i], 2));
88+ writeln;
89+end.

src/test/ChunkDump.raz added +118 -0

@@ -0,0 +1,118 @@
1+(* Makes a program of chunks by a fixed pseudo-random script and prints
2+ all of it: src/Chunk.raz's side of a test against the seed's,
3+ ChunkDump.pas, which prints the same. *)
4+module ChunkDump;
5+import Out, Fmt, Scan, Chunk;
6+
7+var seed: I64;
8+
9+proc rnd(n: INT): INT;
10+begin
11+ seed := (seed * 1103515245 + 12345) & 7FFFFFFFH;
12+ return INT((seed shr 8) mod I64(n));
13+end;
14+
15+(* a flag, as the number the seed's side prints for it *)
16+proc bit(f: BOOL): INT;
17+begin
18+ if f then return 1; end;
19+ return 0;
20+end;
21+
22+proc main*;
23+var
24+ names: [8]INT; b: [64]U8;
25+ i, k, n, op, c, sum, open, x, y, z: INT;
26+begin
27+ seed := 7;
28+ for i := 0 to 7 do b[0] := U8(97 + i); names[i] := Scan.intern(ADR(b[0]), 1); end;
29+ open := -1;
30+ sum := 0;
31+ for k := 1 to 30000 do
32+ op := rnd(16);
33+ match op of
34+ | 0..3: Chunk.put1(rnd(256));
35+ | 4: x := rnd(1 shl 30); y := rnd(1 shl 30); Chunk.put4(x - y);
36+ | 5: x := rnd(1 shl 30); y := rnd(1 shl 30); Chunk.put8(I64(x) * 4096 - I64(y));
37+ | 6:
38+ if open >= 0 then Chunk.endChunk(open); end;
39+ x := rnd(5); y := rnd(9);
40+ open := Chunk.newChunk(Chunk.secText, x - 1, y - 1);
41+ Chunk.beginChunk(open);
42+ | 7:
43+ x := rnd(8); Chunk.setCurFile(names[x]);
44+ x := rnd(300); y := rnd(80); Chunk.noteLine(x, y);
45+ | 8:
46+ if Chunk.numChunks > 0 then
47+ x := rnd(Chunk.numChunks); y := rnd(100); Chunk.addFixup(Chunk.pc, x, y - 50);
48+ end;
49+ | 9:
50+ if (open >= 0) and (Chunk.pc - Chunk.chunks[open].start > 8) then
51+ x := rnd(6); Chunk.takeBack(x);
52+ end;
53+ | 10:
54+ x := rnd(5); y := rnd(9);
55+ c := Chunk.newChunk(Chunk.secRodata, x - 1, y - 1);
56+ n := rnd(64);
57+ for i := 0 to n - 1 do b[i] := U8(rnd(256)); end;
58+ x := rnd(4);
59+ Chunk.setData(c, ADR(b[0]), n, 1 shl x);
60+ n := rnd(4);
61+ for i := 1 to n do
62+ x := rnd(8); y := rnd(Chunk.numChunks); z := rnd(10);
63+ Chunk.addDataFixup(c, x * 8, y, z);
64+ end;
65+ | 11:
66+ x := rnd(5); y := rnd(9);
67+ c := Chunk.newChunk(Chunk.secBss, x - 1, y - 1);
68+ x := rnd(100); y := rnd(4);
69+ Chunk.setBss(c, x, 1 shl y);
70+ | 12: x := rnd(8); c := Chunk.externChunk(names[x]);
71+ | 13:
72+ if Chunk.numChunks > 0 then
73+ x := rnd(Chunk.numChunks); y := rnd(8); z := rnd(200); n := rnd(5);
74+ Chunk.noteVar(x, names[y], z - 100, n);
75+ end;
76+ | 14:
77+ if Chunk.pc >= 8 then
78+ x := rnd(1 shl 30); y := rnd(1 shl 30);
79+ Chunk.put4At(Chunk.pc - 8, x - y);
80+ sum := (sum + Chunk.get4At(Chunk.pc - 8)) & 0FFFFFFH;
81+ end;
82+ | else:
83+ if Chunk.numChunks > 0 then
84+ x := rnd(Chunk.numChunks); Chunk.setLive(x);
85+ x := rnd(Chunk.numChunks); y := rnd(1 shl 30); Chunk.setAdr(x, y);
86+ end;
87+ end;
88+ end;
89+ if open >= 0 then Chunk.endChunk(open); end;
90+ Fmt.print("sum {} pc {} rolen {}\n", [Fmt.int(sum), Fmt.int(Chunk.pc), Fmt.int(Chunk.rolen)]);
91+ for i := 0 to Chunk.numChunks - 1 do
92+ Fmt.print("C {} {} {} {} {} {} {} {} {} {} {} {} {}\n", [Fmt.int(i), Fmt.int(INT(Chunk.chunks[i].sec)),
93+ Fmt.int(Chunk.chunks[i].start), Fmt.int(Chunk.chunks[i].size), Fmt.int(Chunk.chunks[i].align),
94+ Fmt.int(Chunk.chunks[i].firstFix), Fmt.int(Chunk.chunks[i].numFix), Fmt.int(Chunk.chunks[i].home),
95+ Fmt.int(Chunk.chunks[i].name), Fmt.int(Chunk.chunks[i].adr),
96+ Fmt.int(bit(Chunk.chunks[i].live)), Fmt.int(bit(Chunk.chunks[i].ext)), Fmt.str(Chunk.chunkName(i))]);
97+ end;
98+ for i := 0 to Chunk.numFixups - 1 do
99+ Fmt.print("F {} {} {}\n", [Fmt.int(Chunk.fixups[i].at), Fmt.int(Chunk.fixups[i].chunk), Fmt.int(Chunk.fixups[i].addend)]);
100+ end;
101+ for i := 0 to Chunk.numDataFixups - 1 do
102+ Fmt.print("D {} {} {}\n", [Fmt.int(Chunk.dataFixups[i].at), Fmt.int(Chunk.dataFixups[i].chunk), Fmt.int(Chunk.dataFixups[i].addend)]);
103+ end;
104+ for i := 0 to Chunk.numLines - 1 do
105+ Fmt.print("L {} {} {} {} {}\n", [Fmt.int(Chunk.lines[i].at), Fmt.int(Chunk.lines[i].chunk),
106+ Fmt.int(Chunk.lines[i].path), Fmt.int(Chunk.lines[i].line), Fmt.int(Chunk.lines[i].col)]);
107+ end;
108+ for i := 0 to Chunk.numVarNotes - 1 do
109+ Fmt.print("V {} {} {} {}\n", [Fmt.int(Chunk.varNotes[i].chunk), Fmt.int(Chunk.varNotes[i].name),
110+ Fmt.int(Chunk.varNotes[i].off), Fmt.int(Chunk.varNotes[i].kind)]);
111+ end;
112+ for i := 0 to Chunk.pc - 1 do Out.hex(U64(Chunk.text[i]), 2); end;
113+ Out.ln;
114+ for i := 0 to Chunk.rolen - 1 do Out.hex(U64(Chunk.rodata[i]), 2); end;
115+ Out.ln;
116+end;
117+
118+end ChunkDump.

src/test/GenDump.pas added +708 -0

@@ -0,0 +1,708 @@
1+{ Compiles procedures made by a fixed pseudo-random script of calls to
2+ Gen, valid by construction, then prints the bytes, the fixups and the
3+ listing (raz -S) of what it made: the seed's side of a test of
4+ src/Gen.raz, whose GenDump.raz makes and prints the same. With an
5+ argument, the entry point is the dynamic one. }
6+program gendump;
7+{$mode objfpc}{$H-}
8+uses diag, scan, sym, chunk, x64, gen;
9+
10+const
11+ FirstProc = 3;
12+ NumProcs = 80;
13+ FirstGlob = FirstProc + NumProcs;
14+ NumGlobs = 4;
15+ Arith: array[0..9] of TSym = (sPlus, sMinus, sTimes, sDiv, sMod, sAmp, sBar, sXor, sShl, sShr);
16+ Cmps: array[0..5] of TSym = (sEql, sNeq, sLss, sLeq, sGtr, sGeq);
17+ RealOps: array[0..3] of TSym = (sPlus, sMinus, sTimes, sSlash);
18+
19+var
20+ seed: int64;
21+ slots: array[0..5] of int64;
22+ regs: array[0..4] of longint;
23+ numRegs: longint;
24+ xregs: array[0..3] of longint;
25+ numX: longint;
26+ tuple2, tuple3, record3, sliceT: PType;
27+ results: array[0..8] of PType;
28+ curRes: longint;
29+
30+function Rnd(n: longint): longint;
31+begin
32+ seed := (seed * 1103515245 + 12345) and $7FFFFFFF;
33+ Rnd := (seed shr 8) mod n;
34+end;
35+
36+function Pos: TPos;
37+var p: TPos;
38+begin
39+ p.f := 0; p.a := Rnd(400); p.b := p.a + 1;
40+ Pos := p;
41+end;
42+
43+function Size: longint;
44+begin
45+ Size := 1 shl Rnd(4);
46+end;
47+
48+function Slot: int64;
49+begin
50+ Slot := slots[Rnd(6)];
51+end;
52+
53+function Bit(f: boolean): longint;
54+begin
55+ if f then Bit := 1 else Bit := 0;
56+end;
57+
58+function Flag: boolean;
59+begin
60+ Flag := Rnd(2) = 0;
61+end;
62+
63+function ConstVal: int64;
64+var x: longint; r: int64;
65+begin
66+ x := Rnd(1 shl 30);
67+ case Rnd(7) of
68+ 0: r := x mod 10;
69+ 1: r := -(x mod 100);
70+ 2: r := int64(1) shl (x mod 20);
71+ 3: r := x;
72+ 4: r := int64(x) * 4096 * 4096 * 9 - 7;
73+ 5: r := -int64(x) * 8;
74+ else r := x mod 1000 - 500;
75+ end;
76+ ConstVal := r;
77+end;
78+
79+function NewObjs(t: PType; n: longint): PObj;
80+var first, o, last: PObj; i: longint;
81+begin
82+ first := nil; last := nil;
83+ for i := 0 to n - 1 do begin
84+ o := NewObj(oVar, 0, t);
85+ o^.val := 8 * i;
86+ if last = nil then first := o else last^.next := o;
87+ last := o;
88+ end;
89+ NewObjs := first;
90+end;
91+
92+procedure MakeTypes;
93+begin
94+ tuple2 := NewType(fRecord, 16, 8);
95+ tuple2^.tuple := true; tuple2^.len := 2; tuple2^.fields := NewObjs(tInt, 2);
96+ tuple3 := NewType(fRecord, 24, 8);
97+ tuple3^.tuple := true; tuple3^.len := 3; tuple3^.fields := NewObjs(tInt, 3);
98+ record3 := NewType(fRecord, 24, 8);
99+ record3^.fields := NewObjs(tReal, 3);
100+ sliceT := NewType(fSlice, 16, 8);
101+ sliceT^.base := tU8;
102+ results[0] := nil;
103+ results[1] := tInt;
104+ results[2] := tReal;
105+ results[3] := sliceT;
106+ results[4] := tuple2;
107+ results[5] := tuple3;
108+ results[6] := tF32;
109+ results[7] := tI16;
110+ results[8] := record3;
111+end;
112+
113+function MemAdr: TAdr;
114+var a: TAdr; c: longint;
115+begin
116+ c := Rnd(3);
117+ if c = 0 then begin
118+ a.base := bFrame; a.chunk := 0; a.hi := 0; a.off := Slot; if Flag then a.off := a.off + 8;
119+ end else if c = 1 then begin
120+ a.base := bGlobal; a.chunk := FirstGlob + Rnd(NumGlobs); a.hi := 0; a.off := 8 * Rnd(3);
121+ end else begin
122+ a.base := bSlot; a.chunk := Slot; a.hi := 0; a.off := 8 * Rnd(3);
123+ end;
124+ MemAdr := a;
125+end;
126+
127+function PushableAdr: TAdr;
128+var a: TAdr;
129+begin
130+ a.chunk := 0; a.hi := 0;
131+ if Flag then begin
132+ a.base := bFrame; a.off := Slot; if Flag then a.off := a.off + 8;
133+ end else begin
134+ a.base := bGlobal; a.chunk := FirstGlob + Rnd(NumGlobs); a.off := 8 * Rnd(3);
135+ end;
136+ PushableAdr := a;
137+end;
138+
139+function RegAdr(r: longint): TAdr;
140+var a: TAdr;
141+begin
142+ a.base := bReg; a.chunk := r; a.hi := 0; a.off := 0;
143+ RegAdr := a;
144+end;
145+
146+function StackAdr: TAdr;
147+var a: TAdr;
148+begin
149+ a.base := bStack; a.chunk := 0; a.hi := 0; a.off := 8 * Rnd(3);
150+ StackAdr := a;
151+end;
152+
153+procedure PushIntVar;
154+var a: TAdr; sz, c: longint;
155+begin
156+ sz := Size;
157+ c := Rnd(5);
158+ if (c = 0) and (numRegs > 0) then begin
159+ if Flag then inPlace := regs[Rnd(numRegs)];
160+ PushVar(RegAdr(regs[Rnd(numRegs)]), 8, false, kWord);
161+ end else if c = 1 then begin
162+ PushAdr(PushableAdr);
163+ a := StackAdr;
164+ PushVar(a, sz, Flag, kWord);
165+ end else begin
166+ a := MemAdr;
167+ PushVar(a, sz, Flag, kWord);
168+ end;
169+end;
170+
171+procedure IntExpr(b: longint); forward;
172+procedure RealExpr(k: TKind; b: longint); forward;
173+procedure CallExpr(want, b: longint); forward;
174+
175+function RealKind: TKind;
176+begin
177+ if Flag then RealKind := kF64 else RealKind := kF32;
178+end;
179+
180+procedure IntExpr(b: longint);
181+var c, sz, n: longint; sg, f: boolean; k: TKind; sy: TSym; a: TAdr;
182+begin
183+ if b > 0 then c := Rnd(14) else c := Rnd(3);
184+ case c of
185+ 0: PushConst(kWord, ConstVal);
186+ 1: PushIntVar;
187+ 2: PushIntVar;
188+ 3, 4, 5: begin
189+ IntExpr(b - 1); IntExpr(b - 1);
190+ sy := Arith[Rnd(10)]; sz := Size; sg := Flag;
191+ Op(sy, kWord, sz, sg);
192+ end;
193+ 6:
194+ if Flag then begin
195+ IntExpr(b - 1); IntExpr(b - 1);
196+ sy := Cmps[Rnd(6)]; sg := Flag;
197+ Compare(sy, kWord, sg);
198+ end else begin
199+ k := RealKind;
200+ RealExpr(k, b - 1); RealExpr(k, b - 1);
201+ sy := Cmps[Rnd(6)];
202+ Compare(sy, k, false);
203+ end;
204+ 7: begin
205+ IntExpr(b - 1);
206+ n := Rnd(4); sz := Size; sg := Flag;
207+ if n = 0 then Neg(kWord, sz, sg)
208+ else if n = 1 then Complement(sz, sg)
209+ else if n = 2 then NotBool
210+ else Narrow(sz, sg);
211+ end;
212+ 8: begin
213+ IntExpr(b - 1);
214+ a := PushableAdr;
215+ sz := Size; sg := Flag;
216+ n := 10 + Rnd(100);
217+ CheckIndex(n, Pos);
218+ IndexArray(a, sz);
219+ a := StackAdr; a.off := 0;
220+ PushVar(a, sz, sg, kWord);
221+ end;
222+ 9: begin
223+ n := Rnd(3);
224+ sz := Size; sg := Flag;
225+ if n = 0 then begin
226+ a := MemAdr;
227+ if a.base = bGlobal then a.base := bFrame;
228+ IntExpr(b - 1);
229+ f := Flag;
230+ IndexSlice(a, sz, f, Pos);
231+ end else if n = 1 then begin
232+ PushAdr(PushableAdr);
233+ IntExpr(b - 1);
234+ a := StackAdr; a.off := 0;
235+ f := Flag;
236+ IndexSlice(a, sz, f, Pos);
237+ end else begin
238+ a.base := bReg; a.chunk := R13; a.hi := R14; a.off := 0;
239+ IntExpr(b - 1);
240+ f := Flag;
241+ IndexSlice(a, sz, f, Pos);
242+ end;
243+ a := StackAdr; a.off := 0;
244+ PushVar(a, sz, sg, kWord);
245+ end;
246+ 10: begin
247+ k := RealKind;
248+ RealExpr(k, b - 1);
249+ RealToInt(k);
250+ end;
251+ 11: CallExpr(1, b - 1);
252+ 12: begin
253+ IntExpr(b - 1);
254+ PushConst(kWord, Rnd(100) - 50);
255+ Op(sPlus, kWord, 8, false);
256+ end;
257+ else begin
258+ IntExpr(b - 1);
259+ PushConst(kWord, ConstVal);
260+ sy := Arith[Rnd(10)]; sz := Size; sg := Flag;
261+ Op(sy, kWord, sz, sg);
262+ end;
263+ end;
264+end;
265+
266+procedure RealExpr(k: TKind; b: longint);
267+var c, n: longint; sy: TSym; a: TAdr; k2: TKind; v: int64;
268+begin
269+ if b > 0 then c := Rnd(9) else c := Rnd(3);
270+ case c of
271+ 0: begin
272+ n := Rnd(4);
273+ if n = 0 then v := $3FF0000000000000
274+ else if n = 1 then v := $4000000000000000
275+ else if n = 2 then v := 0
276+ else v := $3FE0000000000000;
277+ PushConst(k, v);
278+ end;
279+ 1: begin
280+ a := MemAdr;
281+ if k = kF32 then PushVar(a, 4, false, k) else PushVar(a, 8, false, k);
282+ end;
283+ 2:
284+ if numX > 0 then begin
285+ if Flag then inPlace := xregs[Rnd(numX)];
286+ PushVar(RegAdr(xregs[Rnd(numX)]), 8, false, k);
287+ end else begin
288+ PushAdr(PushableAdr);
289+ a := StackAdr;
290+ PushVar(a, 8, false, k);
291+ end;
292+ 3, 4: begin
293+ RealExpr(k, b - 1); RealExpr(k, b - 1);
294+ sy := RealOps[Rnd(4)];
295+ Op(sy, k, 8, false);
296+ end;
297+ 5: begin
298+ IntExpr(b - 1);
299+ IntToReal(k, Flag);
300+ end;
301+ 6: begin
302+ RealExpr(k, b - 1);
303+ Neg(k, 8, false);
304+ end;
305+ 7: begin
306+ if k = kF32 then k2 := kF64 else k2 := kF32;
307+ RealExpr(k2, b - 1);
308+ RealToReal(k2);
309+ end;
310+ else CallExpr(2, b - 1);
311+ end;
312+end;
313+
314+procedure CallExpr(want, b: longint);
315+var
316+ c: TCall; sig: PType; i, n, kind, r, ni: longint; k: TKind;
317+begin
318+ sig := NewType(fProc, 8, 8);
319+ sig^.variadic := Rnd(5) = 0;
320+ if want = 1 then begin
321+ r := Rnd(5);
322+ if r = 0 then sig^.base := tBool
323+ else if r = 1 then sig^.base := tI8
324+ else if r = 2 then sig^.base := tU32
325+ else if r = 3 then sig^.base := tuple2
326+ else sig^.base := tInt;
327+ end else if want = 2 then begin
328+ if Flag then sig^.base := tReal else sig^.base := tF32;
329+ end else
330+ sig^.base := results[Rnd(9)];
331+ c.sig := sig; c.param := nil; c.obj := nil; c.ext := Rnd(4) = 0;
332+ c.n := 0; c.target := 0;
333+ c.chunk := FirstProc + Rnd(NumProcs);
334+ if Rnd(5) = 0 then begin c.chunk := -1; c.ext := false; c.target := Slot end;
335+ n := Rnd(8);
336+ for i := 0 to n - 1 do begin
337+ kind := Rnd(4);
338+ if kind = 0 then begin
339+ k := RealKind;
340+ RealExpr(k, b);
341+ c.isF[c.n] := true; c.pair[c.n] := false;
342+ inc(c.n);
343+ end else if kind = 1 then begin
344+ IntExpr(b); IntExpr(b);
345+ c.isF[c.n] := false; c.pair[c.n] := true;
346+ c.isF[c.n + 1] := false; c.pair[c.n + 1] := false;
347+ inc(c.n, 2);
348+ end else begin
349+ IntExpr(b);
350+ c.isF[c.n] := false; c.pair[c.n] := false;
351+ inc(c.n);
352+ end;
353+ end;
354+ Call(c);
355+ ni := 0;
356+ if sig^.base <> nil then begin
357+ if sig^.base^.form = fSlice then ni := 0
358+ else if sig^.base = tuple2 then ni := 2
359+ else if BehindPointer(sig^.base) then ni := 0
360+ else ni := 1;
361+ end;
362+ if want = 0 then begin
363+ for i := 1 to ni do Drop;
364+ end else if ni = 2 then
365+ Drop;
366+end;
367+
368+procedure BoolExpr(b: longint);
369+var sy: TSym; sg: boolean;
370+begin
371+ if Flag then begin
372+ IntExpr(b); IntExpr(b);
373+ sy := Cmps[Rnd(6)]; sg := Flag;
374+ Compare(sy, kWord, sg);
375+ end else
376+ IntExpr(b);
377+end;
378+
379+procedure Stmt(b: longint); forward;
380+
381+procedure Assign(b: longint);
382+var a: TAdr; c, sz: longint; k: TKind;
383+begin
384+ c := Rnd(6);
385+ sz := Size;
386+ if c = 0 then begin
387+ a := MemAdr;
388+ IntExpr(b);
389+ PopVar(a, sz);
390+ end else if c = 1 then begin
391+ PushAdr(PushableAdr);
392+ a := StackAdr;
393+ IntExpr(b);
394+ PopVar(a, sz);
395+ end else if (c = 2) and (numRegs > 0) then begin
396+ a := RegAdr(regs[Rnd(numRegs)]);
397+ inPlace := a.chunk;
398+ PushVar(a, 8, false, kWord);
399+ IntExpr(b);
400+ Op(Arith[Rnd(3)], kWord, 8, false);
401+ PopVar(a, 8);
402+ end else if (c = 3) and (numX > 0) then begin
403+ k := RealKind;
404+ a := RegAdr(xregs[Rnd(numX)]);
405+ RealExpr(k, b);
406+ PopVar(a, 8);
407+ end else if c = 4 then begin
408+ k := RealKind;
409+ a := MemAdr;
410+ RealExpr(k, b);
411+ if k = kF32 then PopVar(a, 4) else PopVar(a, 8);
412+ end else begin
413+ a := MemAdr;
414+ PushConst(kWord, ConstVal);
415+ PopVar(a, sz);
416+ end;
417+end;
418+
419+procedure RetStmt(b: longint);
420+var i: longint;
421+begin
422+ if curRes = 1 then IntExpr(b)
423+ else if curRes = 7 then IntExpr(b)
424+ else if curRes = 2 then RealExpr(kF64, b)
425+ else if curRes = 6 then RealExpr(kF32, b)
426+ else if (curRes = 3) or (curRes = 4) then begin IntExpr(b); IntExpr(b) end
427+ else if curRes = 5 then begin
428+ for i := 0 to 2 do begin IntExpr(b); ResultTo(8 * i, 8) end;
429+ end else if curRes = 8 then begin
430+ PushAdr(PushableAdr);
431+ CopyResult(0, 24);
432+ end;
433+ ReturnJump;
434+end;
435+
436+procedure Stmt(b: longint);
437+var
438+ c, n, lo, i, start, saved, sz, tmp: longint; L, E, S, fj, tj: longint; a, a2: TAdr; sy: TSym; sg: boolean;
439+ mk: int64; f: boolean;
440+begin
441+ mk := TempMark;
442+ if b <= 0 then c := Rnd(4) else c := Rnd(22);
443+ case c of
444+ 0, 1, 2, 3: Assign(b);
445+ 4: begin
446+ L := NoLabel;
447+ BoolExpr(b);
448+ JumpIf(L, false);
449+ Stmt(b - 1);
450+ Fix(L);
451+ end;
452+ 5: begin
453+ L := NoLabel;
454+ AlignLoop;
455+ start := pc;
456+ BoolExpr(b);
457+ JumpIf(L, false);
458+ Stmt(b - 1);
459+ JumpBack(start);
460+ Fix(L);
461+ end;
462+ 6: begin
463+ L := NoLabel;
464+ IntExpr(b); IntExpr(b);
465+ sy := Cmps[Rnd(6)]; sg := Flag;
466+ if Flag then JumpCmp(sy, sg, L) else JumpOut(sy, sg, L);
467+ Stmt(b - 1);
468+ Fix(L);
469+ end;
470+ 7: begin
471+ fj := NoLabel; tj := NoLabel;
472+ IntExpr(b); IntExpr(b);
473+ sy := Cmps[Rnd(6)]; sg := Flag;
474+ CondValue(sy, sg, fj, tj);
475+ a := MemAdr;
476+ PopVar(a, 1);
477+ end;
478+ 8: CallExpr(0, b);
479+ 9: begin
480+ a := MemAdr;
481+ if a.base = bSlot then begin a.base := bFrame; a.off := slots[0] end;
482+ IntExpr(b);
483+ PopVar(a, 8);
484+ E := NoLabel;
485+ n := 2 + Rnd(4); lo := Rnd(5) - 2;
486+ if Flag then S := NoLabel else S := pc;
487+ start := JumpTable(a.off, lo, n, S, E);
488+ for i := 0 to n - 1 do TableEntry(start, pc + 4 * (n - i));
489+ for i := 0 to n - 1 do
490+ Stmt(b - 1);
491+ Fix(E);
492+ end;
493+ 10: begin
494+ PushAdr(PushableAdr); PushAdr(PushableAdr);
495+ n := 1 + Rnd(150); lo := 8 * Rnd(3);
496+ CopyBlock(n, lo);
497+ end;
498+ 11: begin
499+ PushAdr(PushableAdr);
500+ a := MemAdr;
501+ if Flag and (numRegs > 1) then begin
502+ a.base := bReg; a.chunk := regs[0]; a.hi := regs[1]; a.off := 0;
503+ end;
504+ n := 1 + Rnd(150);
505+ CopyTo(a, n);
506+ end;
507+ 12: begin
508+ a := MemAdr;
509+ n := 1 + Rnd(100);
510+ ZeroVar(a, n);
511+ end;
512+ 13: begin
513+ tmp := AllocTemp(16, 8);
514+ n := Rnd(3);
515+ sz := Size; sg := Flag;
516+ if n = 0 then begin
517+ a := PushableAdr;
518+ PushAdr(a); IntExpr(b); IntExpr(b);
519+ a := StackAdr; a.off := 0;
520+ f := Flag; n := 10 + Rnd(50);
521+ Slice(a, f, n, sz, tmp, sg, Pos);
522+ end else if n = 1 then begin
523+ a := MemAdr;
524+ if a.base = bGlobal then a.base := bFrame;
525+ IntExpr(b); IntExpr(b);
526+ Slice(a, false, 0, sz, tmp, sg, Pos);
527+ end else begin
528+ IntExpr(b); IntExpr(b); IntExpr(b);
529+ SlicePtr(sz, tmp, sg, Pos);
530+ end;
531+ end;
532+ 14: begin
533+ a.off := Slot; a2.off := Slot; sz := Size; f := Flag;
534+ CopySlice(a.off, a2.off, sz, f, Pos);
535+ end;
536+ 15: begin
537+ n := Rnd(4); sz := Size; sg := Flag;
538+ if n = 0 then begin
539+ PushAdr(PushableAdr); IntExpr(b);
540+ f := Flag;
541+ IncDec(sz, sg, f);
542+ end else if (n = 1) and (numRegs > 0) then begin
543+ IntExpr(b);
544+ IncDecReg(regs[0], sz, sg, Flag);
545+ end else if n = 2 then begin
546+ IntExpr(b);
547+ n := 3 + Rnd(6); lo := FirstGlob + Rnd(NumGlobs);
548+ CheckEnum(n, lo, Pos);
549+ Drop;
550+ end else begin
551+ IntExpr(b);
552+ n := Rnd(8000);
553+ CheckNil(n, Pos);
554+ Drop;
555+ end;
556+ end;
557+ 16: begin
558+ n := Rnd(3);
559+ if n = 0 then begin
560+ a.off := Slot; a2.off := Slot; n := Rnd(4); f := Flag;
561+ CompareSeq(a.off, a2.off, n, f);
562+ Drop;
563+ end else if n = 1 then begin
564+ IntExpr(b);
565+ ErrorText(AllocTemp(16, 8));
566+ end else begin
567+ IntExpr(b);
568+ n := 1 + Rnd(200);
569+ ZeroNew(n);
570+ Drop;
571+ end;
572+ end;
573+ 17: begin
574+ n := Rnd(3);
575+ if n = 0 then begin
576+ IntExpr(b); IntExpr(b); IntExpr(b);
577+ Atomic(bCas);
578+ end else if n = 1 then begin
579+ IntExpr(b); IntExpr(b);
580+ Atomic(bXchg);
581+ end else begin
582+ IntExpr(b); IntExpr(b);
583+ Atomic(bXadd);
584+ end;
585+ Drop;
586+ end;
587+ 18: begin
588+ n := Rnd(7);
589+ for i := 1 to n do IntExpr(b);
590+ SysCall(n);
591+ Drop;
592+ if Flag then Fence;
593+ end;
594+ 19: begin
595+ L := NoLabel;
596+ start := DeferBegin(L, saved);
597+ Stmt(b - 1);
598+ DeferEnd(L, saved);
599+ RunDefer(start);
600+ end;
601+ 20: if curRes <> 0 then RetStmt(b) else Assign(b);
602+ else
603+ if curRes <> 0 then begin
604+ TryAlign;
605+ TryReturn(Slot);
606+ end else
607+ Assign(b);
608+ end;
609+ ReleaseTemps(mk);
610+end;
611+
612+procedure GenProc(c: longint);
613+var
614+ sig: PType; params, p, last: PObj; i, n, kind, mask, j, ns, line: longint; t: PType;
615+ mk: TCodeMark; open: boolean;
616+begin
617+ sig := NewType(fProc, 8, 8);
618+ curRes := Rnd(9);
619+ sig^.base := results[curRes];
620+ params := nil; last := nil;
621+ n := Rnd(8);
622+ for i := 0 to n - 1 do begin
623+ kind := Rnd(5);
624+ if kind = 0 then t := tReal
625+ else if kind = 1 then t := sliceT
626+ else if kind = 2 then t := tI32
627+ else t := tInt;
628+ p := NewObj(oVar, 0, t);
629+ p^.param := true;
630+ p^.isVar := kind = 4;
631+ if last = nil then params := p else last^.next := p;
632+ last := p;
633+ end;
634+ BeginProc(sig, params);
635+ for i := 0 to 5 do slots[i] := AllocPerm(8, 8);
636+ mask := Rnd(32);
637+ j := Rnd(16);
638+ mask := mask or (j shl XBit);
639+ if Rnd(3) = 0 then mask := 0;
640+ numRegs := 0; numX := 0;
641+ for j := 0 to 4 do
642+ if mask and (1 shl j) <> 0 then begin regs[numRegs] := VarRegs[j]; inc(numRegs) end;
643+ for j := 0 to 3 do
644+ if mask and (1 shl (XBit + j)) <> 0 then begin
645+ xregs[numX] := XVarRegs[j]; inc(numX);
646+ XHome(XVarRegs[j], AllocPerm(8, 8));
647+ end;
648+ j := 0;
649+ p := params;
650+ while p <> nil do begin
651+ if (p^.typ = tInt) and (not p^.isVar) and (j < numRegs) and Flag then begin
652+ p^.reg := regs[j]; inc(j);
653+ end else if (p^.typ = tReal) and (numX > 0) and Flag then begin
654+ p^.reg := xregs[0];
655+ end else if Flag then
656+ KeepArrived(p);
657+ p := p^.next;
658+ end;
659+ UseRegs(mask);
660+ line := 1 + Rnd(40);
661+ EnterBody(c, line);
662+ MarkCode(mk);
663+ if Flag then begin
664+ Stmt(2);
665+ Rewind(mk);
666+ Redo(mk);
667+ end;
668+ ns := 2 + Rnd(8);
669+ for i := 1 to ns do Stmt(3);
670+ open := Flag and (sig^.base <> nil);
671+ if (sig^.base <> nil) and (not open) then RetStmt(2);
672+ EndProc(c, open);
673+ writeln('proc ', c, ' lost ', Bit(lost), ' regs ', mask, ' saves ', chunks^[c].saveMask, ' at ', chunks^[c].saveAt);
674+end;
675+
676+function ChunkNameOf(i: longint): longint;
677+var s: string;
678+begin
679+ s := 'p' + chr(48 + i div 10) + chr(48 + i mod 10);
680+ ChunkNameOf := Intern(@s[1], 3);
681+end;
682+
683+var
684+ i, c, entry: longint; path: string; links: array[0..1] of TLink; dyn: boolean;
685+begin
686+ seed := 5;
687+ path := 'lib/Rt.raz';
688+ if Open(path) <> '' then Fatal('no file');
689+ dyn := ParamCount >= 1;
690+ listing := true;
691+ curFile := Intern(@path[1], length(path));
692+ for i := 0 to NumProcs - 1 do begin c := NewChunk(secText, -1, ChunkNameOf(i)); chunks^[c].live := true end;
693+ for i := 0 to NumGlobs - 1 do begin
694+ c := NewChunk(secBss, -1, ChunkNameOf(NumProcs + i));
695+ SetBss(c, 64, 8);
696+ end;
697+ MakeTypes;
698+ for i := 0 to NumProcs - 1 do GenProc(FirstProc + i);
699+ links[0].chunk := FirstProc; links[0].into := FirstGlob;
700+ links[1].chunk := FirstProc + 1; links[1].into := FirstGlob + 1;
701+ entry := EntryPoint(dyn, nil, nil, FirstProc + 2, FirstProc + 3, links, 2);
702+ writeln('entry ', entry, ' pc ', pc, ' fixups ', numFixups, ' lines ', numLines, ' said ', SaidCount);
703+ for i := 0 to pc - 1 do write(HexStr(code^[i], 2));
704+ writeln;
705+ for i := 0 to numFixups - 1 do writeln('F ', fixups^[i].at, ' ', fixups^[i].chunk, ' ', fixups^[i].addend);
706+ for i := 0 to numLines - 1 do writeln('L ', lines^[i].at, ' ', lines^[i].chunk, ' ', lines^[i].line, ' ', lines^[i].col);
707+ List(-1);
708+end.

src/test/GenDump.raz added +732 -0

@@ -0,0 +1,732 @@
1+(* Compiles procedures made by a fixed pseudo-random script of calls to
2+ Gen, valid by construction (an expression pushes its operands, then
3+ operates on them; a statement leaves the stack as it found it), then
4+ prints the bytes, the fixups, the line notes and the listing (raz -S)
5+ of what it made: src/Gen.raz's side of a test against the seed's,
6+ GenDump.pas, which makes and prints the same. With the argument dyn,
7+ the entry point is the dynamic one. *)
8+module GenDump;
9+import Out, Fmt, Diag, Scan, Sym, Chunk, X := X64, Gen;
10+
11+const
12+ FirstProc = 3; (* chunks 0 to 2 are Gen's own *)
13+ NumProcs = 80;
14+ FirstGlob = FirstProc + NumProcs;
15+ NumGlobs = 4;
16+ Arith: [10]Scan.Sym = [Scan.sPlus, Scan.sMinus, Scan.sTimes, Scan.sDiv, Scan.sMod,
17+ Scan.sAmp, Scan.sBar, Scan.sXor, Scan.sShl, Scan.sShr];
18+ Cmps: [6]Scan.Sym = [Scan.sEql, Scan.sNeq, Scan.sLss, Scan.sLeq, Scan.sGtr, Scan.sGeq];
19+ RealOps: [4]Scan.Sym = [Scan.sPlus, Scan.sMinus, Scan.sTimes, Scan.sSlash];
20+
21+var
22+ seed: I64;
23+ slots: [6]I64; (* frame slots of the procedure *)
24+ regs: [5]INT; (* the registers of variables it keeps *)
25+ numRegs: INT;
26+ xregs: [4]INT; (* ... of reals, as numbered from XmmVar *)
27+ numX: INT;
28+ tuple2, tuple3, record3, sliceT: ^Sym.Type;
29+ results: [9]^Sym.Type;
30+ curRes: INT; (* the procedure's result: an index of results *)
31+
32+proc rnd(n: INT): INT;
33+begin
34+ seed := (seed * 1103515245 + 12345) & 7FFFFFFFH;
35+ return INT((seed shr 8) mod I64(n));
36+end;
37+
38+proc pos: Diag.Pos;
39+var p: Diag.Pos;
40+begin
41+ p.f := 0; p.a := rnd(400); p.b := p.a + 1;
42+ return p;
43+end;
44+
45+(* a size of 1, 2, 4 or 8 bytes *)
46+proc size: INT;
47+begin
48+ return 1 shl rnd(4);
49+end;
50+
51+(* a slot of the procedure's frame *)
52+proc slot: I64;
53+begin
54+ return slots[rnd(6)];
55+end;
56+
57+proc bit(f: BOOL): INT;
58+begin
59+ if f then return 1; end;
60+ return 0;
61+end;
62+
63+proc flag: BOOL;
64+begin
65+ return rnd(2) = 0;
66+end;
67+
68+proc constVal: I64;
69+var x: INT; r: I64;
70+begin
71+ x := rnd(1 shl 30);
72+ match rnd(7) of
73+ | 0: r := x mod 10;
74+ | 1: r := -(x mod 100);
75+ | 2: r := I64(1) shl (x mod 20);
76+ | 3: r := x;
77+ | 4: r := I64(x) * 4096 * 4096 * 9 - 7;
78+ | 5: r := -I64(x) * 8;
79+ | else: r := x mod 1000 - 500;
80+ end;
81+ return r;
82+end;
83+
84+proc newObjs(t: ^Sym.Type; n: INT): ^Sym.Obj;
85+var first, o, last: ^Sym.Obj; i: INT;
86+begin
87+ first := nil; last := nil;
88+ for i := 0 to n - 1 do
89+ o := Sym.newObj(Sym.oVar, 0, t);
90+ o^.val := 8 * i;
91+ if last = nil then first := o; else last^.next := o; end;
92+ last := o;
93+ end;
94+ return first;
95+end;
96+
97+proc makeTypes;
98+begin
99+ tuple2 := Sym.newType(Sym.fRecord, 16, 8);
100+ tuple2^.tuple := true; tuple2^.len := 2; tuple2^.fields := newObjs(Sym.tInt, 2);
101+ tuple3 := Sym.newType(Sym.fRecord, 24, 8);
102+ tuple3^.tuple := true; tuple3^.len := 3; tuple3^.fields := newObjs(Sym.tInt, 3);
103+ record3 := Sym.newType(Sym.fRecord, 24, 8);
104+ record3^.fields := newObjs(Sym.tReal, 3);
105+ sliceT := Sym.newType(Sym.fSlice, 16, 8);
106+ sliceT^.base := Sym.tU8;
107+ results[0] := nil;
108+ results[1] := Sym.tInt;
109+ results[2] := Sym.tReal;
110+ results[3] := sliceT;
111+ results[4] := tuple2;
112+ results[5] := tuple3;
113+ results[6] := Sym.tF32;
114+ results[7] := Sym.tI16;
115+ results[8] := record3;
116+end;
117+
118+(* Variables *)
119+
120+(* the address of a variable of the procedure that has one: in the frame,
121+ a chunk, or a slot holding its address *)
122+proc memAdr: Gen.Adr;
123+var a: Gen.Adr; c: INT;
124+begin
125+ c := rnd(3);
126+ if c = 0 then
127+ a.base := Gen.bFrame; a.chunk := 0; a.hi := 0; a.off := slot(); if flag() then a.off := a.off + 8; end;
128+ elsif c = 1 then
129+ a.base := Gen.bGlobal; a.chunk := FirstGlob + rnd(NumGlobs); a.hi := 0; a.off := 8 * rnd(3);
130+ else
131+ a.base := Gen.bSlot; a.chunk := INT(slot()); a.hi := 0; a.off := 8 * rnd(3);
132+ end;
133+ return a;
134+end;
135+
136+(* an address that can go on the stack: frame or chunk *)
137+proc pushableAdr: Gen.Adr;
138+var a: Gen.Adr;
139+begin
140+ a.chunk := 0; a.hi := 0;
141+ if flag() then
142+ a.base := Gen.bFrame; a.off := slot(); if flag() then a.off := a.off + 8; end;
143+ else
144+ a.base := Gen.bGlobal; a.chunk := FirstGlob + rnd(NumGlobs); a.off := 8 * rnd(3);
145+ end;
146+ return a;
147+end;
148+
149+proc regAdr(r: INT): Gen.Adr;
150+var a: Gen.Adr;
151+begin
152+ a.base := Gen.bReg; a.chunk := r; a.hi := 0; a.off := 0;
153+ return a;
154+end;
155+
156+proc stackAdr: Gen.Adr;
157+var a: Gen.Adr;
158+begin
159+ a.base := Gen.bStack; a.chunk := 0; a.hi := 0; a.off := 8 * rnd(3);
160+ return a;
161+end;
162+
163+proc pushIntVar;
164+var a: Gen.Adr; sz: INT; c: INT;
165+begin
166+ sz := size();
167+ c := rnd(5);
168+ if (c = 0) and (numRegs > 0) then
169+ if flag() then Gen.setInPlace(regs[rnd(numRegs)]); end;
170+ Gen.pushVar(regAdr(regs[rnd(numRegs)]), 8, false, Gen.kWord);
171+ elsif c = 1 then
172+ Gen.pushAdr(pushableAdr());
173+ a := stackAdr();
174+ Gen.pushVar(a, sz, flag(), Gen.kWord);
175+ else
176+ a := memAdr();
177+ Gen.pushVar(a, sz, flag(), Gen.kWord);
178+ end;
179+end;
180+
181+proc intExpr(b: INT); forward;
182+proc realExpr(k: Gen.Kind; b: INT); forward;
183+proc callExpr(want, b: INT); forward;
184+
185+proc realKind: Gen.Kind;
186+begin
187+ if flag() then return Gen.kF64; end;
188+ return Gen.kF32;
189+end;
190+
191+proc intExpr(b: INT);
192+var c, sz, n: INT; sg, f: BOOL; k: Gen.Kind; sy: Scan.Sym; a: Gen.Adr;
193+begin
194+ if b > 0 then c := rnd(14); else c := rnd(3); end;
195+ match c of
196+ | 0: Gen.pushConst(Gen.kWord, constVal());
197+ | 1: pushIntVar();
198+ | 2: pushIntVar();
199+ | 3, 4, 5:
200+ intExpr(b - 1); intExpr(b - 1);
201+ sy := Arith[rnd(10)]; sz := size(); sg := flag();
202+ Gen.op(sy, Gen.kWord, sz, sg);
203+ | 6:
204+ if flag() then
205+ intExpr(b - 1); intExpr(b - 1);
206+ sy := Cmps[rnd(6)]; sg := flag();
207+ Gen.compare(sy, Gen.kWord, sg);
208+ else
209+ k := realKind();
210+ realExpr(k, b - 1); realExpr(k, b - 1);
211+ sy := Cmps[rnd(6)];
212+ Gen.compare(sy, k, false);
213+ end;
214+ | 7:
215+ intExpr(b - 1);
216+ n := rnd(4); sz := size(); sg := flag();
217+ if n = 0 then Gen.neg(Gen.kWord, sz, sg);
218+ elsif n = 1 then Gen.complement(sz, sg);
219+ elsif n = 2 then Gen.notBool();
220+ else Gen.narrow(sz, sg); end;
221+ | 8:
222+ (* an element of an array in the frame or a chunk *)
223+ intExpr(b - 1);
224+ a := pushableAdr();
225+ sz := size(); sg := flag();
226+ n := 10 + rnd(100);
227+ Gen.checkIndex(n, pos());
228+ Gen.indexArray(a, sz);
229+ a := stackAdr(); a.off := 0;
230+ Gen.pushVar(a, sz, sg, Gen.kWord);
231+ | 9:
232+ (* an element of a slice, in a frame slot or on the stack, or in registers *)
233+ n := rnd(3);
234+ sz := size(); sg := flag();
235+ if n = 0 then
236+ a := memAdr();
237+ if a.base = Gen.bGlobal then a.base := Gen.bFrame; end;
238+ intExpr(b - 1);
239+ f := flag();
240+ Gen.indexSlice(a, sz, f, pos());
241+ elsif n = 1 then
242+ Gen.pushAdr(pushableAdr());
243+ intExpr(b - 1);
244+ a := stackAdr(); a.off := 0;
245+ f := flag();
246+ Gen.indexSlice(a, sz, f, pos());
247+ else
248+ a.base := Gen.bReg; a.chunk := X.R13; a.hi := X.R14; a.off := 0;
249+ intExpr(b - 1);
250+ f := flag();
251+ Gen.indexSlice(a, sz, f, pos());
252+ end;
253+ a := stackAdr(); a.off := 0;
254+ Gen.pushVar(a, sz, sg, Gen.kWord);
255+ | 10:
256+ k := realKind();
257+ realExpr(k, b - 1);
258+ Gen.realToInt(k);
259+ | 11: callExpr(1, b - 1);
260+ | 12:
261+ (* x + 1, and the offset noted on a word *)
262+ intExpr(b - 1);
263+ Gen.pushConst(Gen.kWord, rnd(100) - 50);
264+ Gen.op(Scan.sPlus, Gen.kWord, 8, false);
265+ | else:
266+ intExpr(b - 1);
267+ Gen.pushConst(Gen.kWord, constVal());
268+ sy := Arith[rnd(10)]; sz := size(); sg := flag();
269+ Gen.op(sy, Gen.kWord, sz, sg);
270+ end;
271+end;
272+
273+proc realExpr(k: Gen.Kind; b: INT);
274+var c, n: INT; sy: Scan.Sym; a: Gen.Adr; k2: Gen.Kind; v: I64;
275+begin
276+ if b > 0 then c := rnd(9); else c := rnd(3); end;
277+ match c of
278+ | 0:
279+ n := rnd(4);
280+ if n = 0 then v := 3FF0000000000000H;
281+ elsif n = 1 then v := 4000000000000000H;
282+ elsif n = 2 then v := 0;
283+ else v := 3FE0000000000000H; end;
284+ Gen.pushConst(k, v);
285+ | 1:
286+ a := memAdr();
287+ if k = Gen.kF32 then Gen.pushVar(a, 4, false, k); else Gen.pushVar(a, 8, false, k); end;
288+ | 2:
289+ if numX > 0 then
290+ if flag() then Gen.setInPlace(xregs[rnd(numX)]); end;
291+ Gen.pushVar(regAdr(xregs[rnd(numX)]), 8, false, k);
292+ else
293+ Gen.pushAdr(pushableAdr());
294+ a := stackAdr();
295+ Gen.pushVar(a, 8, false, k);
296+ end;
297+ | 3, 4:
298+ realExpr(k, b - 1); realExpr(k, b - 1);
299+ sy := RealOps[rnd(4)];
300+ Gen.op(sy, k, 8, false);
301+ | 5:
302+ intExpr(b - 1);
303+ Gen.intToReal(k, flag());
304+ | 6:
305+ realExpr(k, b - 1);
306+ Gen.neg(k, 8, false);
307+ | 7:
308+ if k = Gen.kF32 then k2 := Gen.kF64; else k2 := Gen.kF32; end;
309+ realExpr(k2, b - 1);
310+ Gen.realToReal(k2);
311+ | else: callExpr(2, b - 1);
312+ end;
313+end;
314+
315+(* A call of one of the procedures, with arguments of all kinds. want: 0
316+ for a statement, any result; 1 an integer is left on the stack, 2 a
317+ real. *)
318+proc callExpr(want, b: INT);
319+var
320+ c: Gen.CallInfo; sig: ^Sym.Type; i, n, kind, r, ni: INT; k: Gen.Kind;
321+begin
322+ sig := Sym.newType(Sym.fProc, 8, 8);
323+ sig^.variadic := rnd(5) = 0;
324+ if want = 1 then
325+ r := rnd(5);
326+ if r = 0 then sig^.base := Sym.tBool;
327+ elsif r = 1 then sig^.base := Sym.tI8;
328+ elsif r = 2 then sig^.base := Sym.tU32;
329+ elsif r = 3 then sig^.base := tuple2;
330+ else sig^.base := Sym.tInt; end;
331+ elsif want = 2 then
332+ if flag() then sig^.base := Sym.tReal; else sig^.base := Sym.tF32; end;
333+ else
334+ sig^.base := results[rnd(9)];
335+ end;
336+ c.sig := sig; c.param := nil; c.obj := nil; c.ext := rnd(4) = 0;
337+ c.n := 0; c.target := 0;
338+ c.chunk := FirstProc + rnd(NumProcs);
339+ if rnd(5) = 0 then c.chunk := -1; c.ext := false; c.target := slot(); end;
340+ n := rnd(8);
341+ for i := 0 to n - 1 do
342+ kind := rnd(4);
343+ if kind = 0 then
344+ k := realKind();
345+ realExpr(k, b);
346+ c.isF[c.n] := true; c.pair[c.n] := false;
347+ INC(c.n);
348+ elsif kind = 1 then
349+ intExpr(b); intExpr(b);
350+ c.isF[c.n] := false; c.pair[c.n] := true;
351+ c.isF[c.n + 1] := false; c.pair[c.n + 1] := false;
352+ INC(c.n, 2);
353+ else
354+ intExpr(b);
355+ c.isF[c.n] := false; c.pair[c.n] := false;
356+ INC(c.n);
357+ end;
358+ end;
359+ Gen.call(c);
360+ (* what comes back: a value or two, or nothing, or a temporary *)
361+ ni := 0;
362+ if sig^.base # nil then
363+ if sig^.base^.form = Sym.fSlice then ni := 0;
364+ elsif sig^.base = tuple2 then ni := 2;
365+ elsif Sym.behindPointer(sig^.base) then ni := 0;
366+ else ni := 1; end;
367+ end;
368+ if want = 0 then
369+ for i := 1 to ni do Gen.drop(); end;
370+ elsif ni = 2 then
371+ Gen.drop(); (* the second; the first is the value *)
372+ end;
373+end;
374+
375+(* A condition, left as a BOOL on the stack *)
376+proc boolExpr(b: INT);
377+var sy: Scan.Sym; sg: BOOL;
378+begin
379+ if flag() then
380+ intExpr(b); intExpr(b);
381+ sy := Cmps[rnd(6)]; sg := flag();
382+ Gen.compare(sy, Gen.kWord, sg);
383+ else
384+ intExpr(b);
385+ end;
386+end;
387+
388+proc stmt(b: INT); forward;
389+
390+(* a variable assigned the value on top: its address, if on the stack,
391+ having been pushed first *)
392+proc assign(b: INT);
393+var a: Gen.Adr; c, sz: INT; k: Gen.Kind;
394+begin
395+ c := rnd(6);
396+ sz := size();
397+ if c = 0 then
398+ a := memAdr();
399+ intExpr(b);
400+ Gen.popVar(a, sz);
401+ elsif c = 1 then
402+ Gen.pushAdr(pushableAdr());
403+ a := stackAdr();
404+ intExpr(b);
405+ Gen.popVar(a, sz);
406+ elsif (c = 2) and (numRegs > 0) then
407+ a := regAdr(regs[rnd(numRegs)]);
408+ Gen.setInPlace(a.chunk);
409+ Gen.pushVar(a, 8, false, Gen.kWord);
410+ intExpr(b);
411+ Gen.op(Arith[rnd(3)], Gen.kWord, 8, false);
412+ Gen.popVar(a, 8);
413+ elsif (c = 3) and (numX > 0) then
414+ k := realKind();
415+ a := regAdr(xregs[rnd(numX)]);
416+ realExpr(k, b);
417+ Gen.popVar(a, 8);
418+ elsif c = 4 then
419+ k := realKind();
420+ a := memAdr();
421+ realExpr(k, b);
422+ if k = Gen.kF32 then Gen.popVar(a, 4); else Gen.popVar(a, 8); end;
423+ else
424+ a := memAdr();
425+ Gen.pushConst(Gen.kWord, constVal());
426+ Gen.popVar(a, sz);
427+ end;
428+end;
429+
430+proc retStmt(b: INT);
431+var i: INT;
432+begin
433+ if curRes = 1 then intExpr(b);
434+ elsif curRes = 7 then intExpr(b);
435+ elsif curRes = 2 then realExpr(Gen.kF64, b);
436+ elsif curRes = 6 then realExpr(Gen.kF32, b);
437+ elsif (curRes = 3) or (curRes = 4) then intExpr(b); intExpr(b);
438+ elsif curRes = 5 then
439+ for i := 0 to 2 do intExpr(b); Gen.resultTo(8 * i, 8); end;
440+ elsif curRes = 8 then
441+ Gen.pushAdr(pushableAdr());
442+ Gen.copyResult(0, 24);
443+ end;
444+ Gen.returnJump();
445+end;
446+
447+proc stmt(b: INT);
448+var
449+ c, n, lo, i, start, saved, sz, tmp: INT; L, E, S, fj, tj: INT; a, a2: Gen.Adr; sy: Scan.Sym; sg: BOOL;
450+ mk: I64; f: BOOL;
451+begin
452+ mk := Gen.tempMark();
453+ if b <= 0 then c := rnd(4); else c := rnd(22); end;
454+ match c of
455+ | 0, 1, 2, 3: assign(b);
456+ | 4:
457+ (* if cond then s end *)
458+ L := Gen.NoLabel;
459+ boolExpr(b);
460+ Gen.jumpIf(L, false);
461+ stmt(b - 1);
462+ Gen.fix(L);
463+ | 5:
464+ (* while cond do s end *)
465+ L := Gen.NoLabel;
466+ Gen.alignLoop();
467+ start := Chunk.pc;
468+ boolExpr(b);
469+ Gen.jumpIf(L, false);
470+ stmt(b - 1);
471+ Gen.jumpBack(start);
472+ Gen.fix(L);
473+ | 6:
474+ (* if a < b then s end, with a jump on the comparison *)
475+ L := Gen.NoLabel;
476+ intExpr(b); intExpr(b);
477+ sy := Cmps[rnd(6)]; sg := flag();
478+ if flag() then Gen.jumpCmp(sy, sg, L); else Gen.jumpOut(sy, sg, L); end;
479+ stmt(b - 1);
480+ Gen.fix(L);
481+ | 7:
482+ (* v := a < b and c, a condition worked out into a BOOL *)
483+ fj := Gen.NoLabel; tj := Gen.NoLabel;
484+ intExpr(b); intExpr(b);
485+ sy := Cmps[rnd(6)]; sg := flag();
486+ Gen.condValue(sy, sg, fj, tj);
487+ a := memAdr();
488+ Gen.popVar(a, 1);
489+ | 8: callExpr(0, b);
490+ | 9:
491+ (* a match through a jump table *)
492+ a := memAdr();
493+ if a.base = Gen.bSlot then a.base := Gen.bFrame; a.off := slots[0]; end;
494+ intExpr(b);
495+ Gen.popVar(a, 8);
496+ E := Gen.NoLabel;
497+ n := 2 + rnd(4); lo := rnd(5) - 2;
498+ if flag() then S := Gen.NoLabel; else S := Chunk.pc; end;
499+ start := Gen.jumpTable(a.off, lo, n, S, E);
500+ for i := 0 to n - 1 do Gen.tableEntry(start, Chunk.pc + 4 * (n - i)); end;
501+ for i := 0 to n - 1 do
502+ stmt(b - 1);
503+ end;
504+ Gen.fix(E);
505+ | 10:
506+ Gen.pushAdr(pushableAdr()); Gen.pushAdr(pushableAdr());
507+ n := 1 + rnd(150); lo := 8 * rnd(3);
508+ Gen.copyBlock(n, lo);
509+ | 11:
510+ Gen.pushAdr(pushableAdr());
511+ a := memAdr();
512+ if flag() and (numRegs > 1) then
513+ a.base := Gen.bReg; a.chunk := regs[0]; a.hi := regs[1]; a.off := 0;
514+ end;
515+ n := 1 + rnd(150);
516+ Gen.copyTo(a, n);
517+ | 12:
518+ a := memAdr();
519+ n := 1 + rnd(100);
520+ Gen.zeroVar(a, n);
521+ | 13:
522+ (* a slice of an array, of a slice, of a pointer *)
523+ tmp := INT(Gen.allocTemp(16, 8));
524+ n := rnd(3);
525+ sz := size(); sg := flag();
526+ if n = 0 then
527+ a := pushableAdr();
528+ Gen.pushAdr(a); intExpr(b); intExpr(b);
529+ a := stackAdr(); a.off := 0;
530+ f := flag(); n := 10 + rnd(50);
531+ Gen.slice(a, f, n, sz, tmp, sg, pos());
532+ elsif n = 1 then
533+ a := memAdr();
534+ if a.base = Gen.bGlobal then a.base := Gen.bFrame; end;
535+ intExpr(b); intExpr(b);
536+ Gen.slice(a, false, 0, sz, tmp, sg, pos());
537+ else
538+ intExpr(b); intExpr(b); intExpr(b);
539+ Gen.slicePtr(sz, tmp, sg, pos());
540+ end;
541+ | 14:
542+ a.off := slot(); a2.off := slot(); sz := size(); f := flag();
543+ Gen.copySlice(a.off, a2.off, sz, f, pos());
544+ | 15:
545+ n := rnd(4); sz := size(); sg := flag();
546+ if n = 0 then
547+ Gen.pushAdr(pushableAdr()); intExpr(b);
548+ f := flag();
549+ Gen.incDec(sz, sg, f);
550+ elsif (n = 1) and (numRegs > 0) then
551+ intExpr(b);
552+ Gen.incDecReg(regs[0], sz, sg, flag());
553+ elsif n = 2 then
554+ intExpr(b);
555+ n := 3 + rnd(6); lo := FirstGlob + rnd(NumGlobs);
556+ Gen.checkEnum(n, lo, pos());
557+ Gen.drop();
558+ else
559+ intExpr(b);
560+ n := rnd(8000);
561+ Gen.checkNil(n, pos());
562+ Gen.drop();
563+ end;
564+ | 16:
565+ n := rnd(3);
566+ if n = 0 then
567+ a.off := slot(); a2.off := slot(); n := rnd(4); f := flag();
568+ Gen.compareSeq(a.off, a2.off, n, f);
569+ Gen.drop();
570+ elsif n = 1 then
571+ intExpr(b);
572+ Gen.errorText(Gen.allocTemp(16, 8));
573+ else
574+ intExpr(b);
575+ n := 1 + rnd(200);
576+ Gen.zeroNew(n);
577+ Gen.drop();
578+ end;
579+ | 17:
580+ n := rnd(3);
581+ if n = 0 then
582+ intExpr(b); intExpr(b); intExpr(b);
583+ Gen.atomic(Sym.bCas);
584+ elsif n = 1 then
585+ intExpr(b); intExpr(b);
586+ Gen.atomic(Sym.bXchg);
587+ else
588+ intExpr(b); intExpr(b);
589+ Gen.atomic(Sym.bXadd);
590+ end;
591+ Gen.drop();
592+ | 18:
593+ n := rnd(7);
594+ for i := 1 to n do intExpr(b); end;
595+ Gen.sysCall(n);
596+ Gen.drop();
597+ if flag() then Gen.fence(); end;
598+ | 19:
599+ (* defer s *)
600+ L := Gen.NoLabel;
601+ start, saved := Gen.deferBegin(L);
602+ stmt(b - 1);
603+ Gen.deferEnd(L, saved);
604+ Gen.runDefer(start);
605+ | 20:
606+ if curRes # 0 then retStmt(b); else assign(b); end;
607+ | else:
608+ if curRes # 0 then
609+ Gen.tryAlign();
610+ Gen.tryReturn(slot());
611+ else
612+ assign(b);
613+ end;
614+ end;
615+ Gen.releaseTemps(mk);
616+end;
617+
618+(* Each statement may be preceded by a few that are made and taken back,
619+ as the parser does when it compiles a body a second time *)
620+proc genProc(c: INT);
621+var
622+ sig: ^Sym.Type; params, p, last: ^Sym.Obj; i, n, kind, mask, j, ns, line: INT; t: ^Sym.Type;
623+ mk: Gen.CodeMark; open: BOOL;
624+begin
625+ sig := Sym.newType(Sym.fProc, 8, 8);
626+ curRes := rnd(9);
627+ sig^.base := results[curRes];
628+ params := nil; last := nil;
629+ n := rnd(8);
630+ for i := 0 to n - 1 do
631+ kind := rnd(5);
632+ if kind = 0 then t := Sym.tReal;
633+ elsif kind = 1 then t := sliceT;
634+ elsif kind = 2 then t := Sym.tI32;
635+ else t := Sym.tInt; end;
636+ p := Sym.newObj(Sym.oVar, 0, t);
637+ p^.param := true;
638+ p^.isVar := kind = 4;
639+ if last = nil then params := p; else last^.next := p; end;
640+ last := p;
641+ end;
642+ Gen.beginProc(sig, params);
643+ for i := 0 to 5 do slots[i] := Gen.allocPerm(8, 8); end;
644+ mask := rnd(32);
645+ j := rnd(16);
646+ mask := mask | (j shl Gen.XBit);
647+ if rnd(3) = 0 then mask := 0; end;
648+ numRegs := 0; numX := 0;
649+ for j := 0 to 4 do
650+ if (mask & (1 shl j)) # 0 then regs[numRegs] := Gen.VarRegs[j]; INC(numRegs); end;
651+ end;
652+ for j := 0 to 3 do
653+ if (mask & (1 shl (Gen.XBit + j))) # 0 then
654+ xregs[numX] := Gen.XVarRegs[j]; INC(numX);
655+ Gen.xHome(Gen.XVarRegs[j], Gen.allocPerm(8, 8));
656+ end;
657+ end;
658+ (* some parameters live in registers: a register variable's, or kept
659+ where they arrived *)
660+ j := 0;
661+ p := params;
662+ while p # nil do
663+ if (p^.typ = Sym.tInt) and (not p^.isVar) and (j < numRegs) and flag() then
664+ p^.reg := regs[j]; INC(j);
665+ elsif (p^.typ = Sym.tReal) and (numX > 0) and flag() then
666+ p^.reg := xregs[0];
667+ elsif flag() then
668+ Gen.keepArrived(p);
669+ end;
670+ p := p^.next;
671+ end;
672+ Gen.useRegs(mask);
673+ line := 1 + rnd(40);
674+ Gen.enterBody(c, line);
675+ Gen.markCode(mk);
676+ (* a body made and taken back *)
677+ if flag() then
678+ stmt(2);
679+ Gen.rewind(mk);
680+ Gen.redo(mk); (* the jumps to the exit went with the code *)
681+ end;
682+ ns := 2 + rnd(8);
683+ for i := 1 to ns do stmt(3); end;
684+ open := flag() and (sig^.base # nil);
685+ if (sig^.base # nil) and (not open) then retStmt(2); end;
686+ _ := Gen.endProc(c, open);
687+ Fmt.print("proc {} lost {} regs {} saves {} at {}\n", [Fmt.int(c), Fmt.int(bit(Gen.lost)), Fmt.int(mask),
688+ Fmt.int(Chunk.chunks[c].saveMask), Fmt.int(Chunk.chunks[c].saveAt)]);
689+end;
690+
691+(* The name p0, p1, ... of chunk i, interned *)
692+proc chunkNameOf(i: INT): INT;
693+var s: [3]U8;
694+begin
695+ s[0] := 'p'; s[1] := U8(48 + i div 10); s[2] := U8(48 + i mod 10);
696+ return Scan.intern(ADR(s[0]), 3);
697+end;
698+
699+proc main*;
700+var i, c: INT; path: []U8; links: [2]Gen.Link; entry: INT; dyn: BOOL;
701+begin
702+ seed := 5;
703+ path := "lib/Rt.raz";
704+ if LEN(Scan.open(path)) # 0 then Diag.fatal("no file"); end;
705+ dyn := ARGC > 1;
706+ X.setListing(true);
707+ Chunk.setCurFile(Scan.intern(ADR(path[0]), LEN(path)));
708+ for i := 0 to NumProcs - 1 do c := Chunk.newChunk(Chunk.secText, -1, chunkNameOf(i)); Chunk.setLive(c); end;
709+ for i := 0 to NumGlobs - 1 do
710+ c := Chunk.newChunk(Chunk.secBss, -1, chunkNameOf(NumProcs + i));
711+ Chunk.setBss(c, 64, 8);
712+ end;
713+ makeTypes();
714+ for i := 0 to NumProcs - 1 do genProc(FirstProc + i); end;
715+ links[0].chunk := FirstProc; links[0].into := FirstGlob;
716+ links[1].chunk := FirstProc + 1; links[1].into := FirstGlob + 1;
717+ entry := Gen.entryPoint(dyn, nil, nil, FirstProc + 2, FirstProc + 3, links, 2);
718+ Fmt.print("entry {} pc {} fixups {} lines {} said {}\n", [Fmt.int(entry), Fmt.int(Chunk.pc),
719+ Fmt.int(Chunk.numFixups), Fmt.int(Chunk.numLines), Fmt.int(X.saidCount())]);
720+ for i := 0 to Chunk.pc - 1 do Out.hex(U64(Chunk.text[i]), 2); end;
721+ Out.ln;
722+ for i := 0 to Chunk.numFixups - 1 do
723+ Fmt.print("F {} {} {}\n", [Fmt.int(Chunk.fixups[i].at), Fmt.int(Chunk.fixups[i].chunk), Fmt.int(Chunk.fixups[i].addend)]);
724+ end;
725+ for i := 0 to Chunk.numLines - 1 do
726+ Fmt.print("L {} {} {} {}\n", [Fmt.int(Chunk.lines[i].at), Fmt.int(Chunk.lines[i].chunk),
727+ Fmt.int(Chunk.lines[i].line), Fmt.int(Chunk.lines[i].col)]);
728+ end;
729+ X.list(-1);
730+end;
731+
732+end GenDump.

src/test/ItemDump.pas added +665 -0

@@ -0,0 +1,665 @@
1+{ Drives item with a fixed pseudo-random script of operands and
2+ operations, with mistakes among them, and prints what each step gave
3+ (the item, or that it failed, whose message goes to standard error),
4+ then the bytes, fixups, line notes and listing (raz -S) of the code
5+ it made: the seed's side of a test of src/Item.raz, whose
6+ ItemDump.raz does and prints the same. The argument, a number,
7+ changes the script. A run ends at the 20th error, as a compile does,
8+ so several scripts are run. }
9+program itemdump;
10+{$mode objfpc}{$H-}
11+uses diag, scan, sym, chunk, x64, gen, item;
12+
13+const
14+ FirstProc = 3;
15+ NumProcs = 30;
16+ FirstGlob = FirstProc + NumProcs;
17+ NumGlobs = 4;
18+ Steps = 14;
19+ YInt = 0; YI64 = 1; YI32 = 2; YU8 = 3; YU16 = 4; YU32 = 5; YU64 = 6; YBool = 7;
20+ YReal = 8; YF32 = 9; YI8 = 10; YEnum = 11; YSet = 12; YPtr = 13; YVptr = 14;
21+ YPtrArr = 15; YArr = 16; YArrU8 = 17; YSlice = 18; YBytes = 19; YRec = 20;
22+ YPacked = 21; YVariant = 22; YProc0 = 23; YProc1 = 24; YProc2 = 25;
23+ YPtrRec = 26; YErr = 27; YVrec = 28; YVarr = 29;
24+ NumT = 30;
25+ IntTypes: array[0..7] of longint = (YInt, YI64, YI32, YU8, YU16, YU32, YU64, YI8);
26+ Ops: array[0..19] of TSym = (sPlus, sMinus, sTimes, sDiv, sMod,
27+ sAmp, sBar, sXor, sShl, sShr,
28+ sEql, sNeq, sLss, sLeq, sGtr, sGeq,
29+ sSlash, sIn, sPlus, sMinus);
30+ Cmps: array[0..5] of TSym = (sEql, sNeq, sLss, sLeq, sGtr, sGeq);
31+
32+var
33+ Letters: string[9];
34+ seed: int64;
35+ ty: array[0..NumT - 1] of PType;
36+ vars: array[0..NumT - 1] of PObj;
37+ procs: array[0..5] of PObj;
38+ strs: array[0..2] of PObj;
39+ arrConst, typeObj, builtinObj, caseObj: PObj;
40+ mod0, mod1: PModule;
41+ tuple2, record3, packedR, variantT: PType;
42+ results: array[0..8] of PType;
43+ curRes: longint;
44+ call: TCall;
45+ jb: jmp_buf;
46+ gK: longint;
47+ gX: TItem;
48+ gOk: boolean;
49+
50+function Rnd(n: longint): longint;
51+begin
52+ seed := (seed * 1103515245 + 12345) and $7FFFFFFF;
53+ Rnd := (seed shr 8) mod n;
54+end;
55+
56+function Flag: boolean;
57+begin
58+ Flag := Rnd(2) = 0;
59+end;
60+
61+function Bit(f: boolean): longint;
62+begin
63+ if f then Bit := 1 else Bit := 0;
64+end;
65+
66+function Pos: TPos;
67+var p: TPos;
68+begin
69+ p.f := 0; p.a := Rnd(400); p.b := p.a + 1 + Rnd(12);
70+ Pos := p;
71+end;
72+
73+function ConstVal: int64;
74+var x: longint; r: int64;
75+begin
76+ x := Rnd(1 shl 30);
77+ case Rnd(7) of
78+ 0: r := x mod 10;
79+ 1: r := -(x mod 100);
80+ 2: r := int64(1) shl (x mod 20);
81+ 3: r := x;
82+ 4: r := int64(x) * 4096 * 4096 * 9 - 7;
83+ 5: r := -int64(x) * 8;
84+ else r := x mod 1000 - 500;
85+ end;
86+ ConstVal := r;
87+end;
88+
89+function InternStr(const s: shortstring): longint;
90+begin
91+ InternStr := Intern(@s[1], length(s));
92+end;
93+
94+{ A name v00, v01, ... , interned }
95+function NameOf(i: longint): longint;
96+var s: string[3];
97+begin
98+ s := 'v' + chr(48 + i div 10) + chr(48 + i mod 10);
99+ NameOf := Intern(@s[1], 3);
100+end;
101+
102+function NewObjs(cls: TClass; t: PType; n: longint; step: int64; at: longint): PObj;
103+var first, o, last: PObj; i: longint;
104+begin
105+ first := nil; last := nil;
106+ for i := 0 to n - 1 do begin
107+ o := NewObj(cls, NameOf(at + i), t);
108+ o^.val := step * i;
109+ if last = nil then first := o else last^.next := o;
110+ last := o;
111+ end;
112+ NewObjs := first;
113+end;
114+
115+function ProcType(res: PType; params: PObj; n: longint): PType;
116+var t: PType;
117+begin
118+ t := NewType(fProc, 8, 8);
119+ t^.base := res;
120+ t^.fields := params;
121+ t^.len := n;
122+ ProcType := t;
123+end;
124+
125+function Param(t: PType; isVar: boolean; at: longint): PObj;
126+var o: PObj;
127+begin
128+ o := NewObj(oVar, NameOf(at), t);
129+ o^.param := true;
130+ o^.isVar := isVar;
131+ Param := o;
132+end;
133+
134+procedure MakeTypes;
135+var t: PType; p, q, r: PObj; i: longint;
136+begin
137+ ty[YInt] := tInt; ty[YI64] := tI64; ty[YI32] := tI32; ty[YU8] := tU8;
138+ ty[YU16] := tU16; ty[YU32] := tU32; ty[YU64] := tU64; ty[YBool] := tBool;
139+ ty[YReal] := tReal; ty[YF32] := tF32; ty[YI8] := tI8; ty[YErr] := tError;
140+ ty[YBytes] := tBytes;
141+ t := NewType(fEnum, 1, 1); t^.len := 5; ty[YEnum] := t;
142+ t := NewType(fSet, 8, 8); t^.len := 5; t^.base := ty[YEnum]; ty[YSet] := t;
143+ t := NewType(fPtr, 8, 8); t^.base := tI64; ty[YPtr] := t;
144+ t := NewType(fPtr, 8, 8); t^.base := tI64; t^.vol := true; ty[YVptr] := t;
145+ t := NewType(fArray, 48, 8); t^.base := tI64; t^.len := 6; ty[YArr] := t;
146+ t := NewType(fPtr, 8, 8); t^.base := ty[YArr]; ty[YPtrArr] := t;
147+ t := NewType(fPtr, 8, 8); t^.base := ty[YArr]; t^.vol := true; ty[YVarr] := t;
148+ t := NewType(fArray, 8, 1); t^.base := tU8; t^.len := 8; ty[YArrU8] := t;
149+ t := NewType(fSlice, 16, 8); t^.base := tI64; ty[YSlice] := t;
150+ record3 := NewType(fRecord, 24, 8);
151+ p := NewObj(oField, NameOf(40), tI64); p^.val := 0;
152+ q := NewObj(oField, NameOf(41), tReal); q^.val := 8; p^.next := q;
153+ r := NewObj(oField, NameOf(42), tI32); r^.val := 16; q^.next := r;
154+ record3^.fields := p;
155+ ty[YRec] := record3;
156+ t := NewType(fPtr, 8, 8); t^.base := record3; ty[YPtrRec] := t;
157+ t := NewType(fPtr, 8, 8); t^.base := record3; t^.vol := true; ty[YVrec] := t;
158+ packedR := NewType(fRecord, 53, 1);
159+ packedR^.packd := true;
160+ p := NewObj(oField, NameOf(43), tU8); p^.val := 0;
161+ q := NewObj(oField, NameOf(44), tI32); q^.val := 1; p^.next := q;
162+ r := NewObj(oField, NameOf(46), ty[YArr]); r^.val := 5; q^.next := r;
163+ packedR^.fields := p;
164+ ty[YPacked] := packedR;
165+ variantT := NewType(fVariant, 16, 8);
166+ ty[YVariant] := variantT;
167+ tuple2 := NewType(fRecord, 16, 8);
168+ tuple2^.tuple := true; tuple2^.len := 2; tuple2^.fields := NewObjs(oVar, tInt, 2, 8, 45);
169+ p := Param(tInt, false, 46); p^.next := Param(tReal, false, 47);
170+ ty[YProc0] := ProcType(tInt, p, 2);
171+ ty[YProc1] := ProcType(nil, nil, 0);
172+ p := Param(tI64, true, 48); p^.next := Param(ty[YSlice], false, 49);
173+ ty[YProc2] := ProcType(tuple2, p, 2);
174+ results[0] := nil; results[1] := tInt; results[2] := tReal; results[3] := ty[YSlice];
175+ results[4] := tuple2; results[5] := record3; results[6] := tF32; results[7] := tI16;
176+ results[8] := ty[YBytes];
177+ for i := 0 to NumT - 1 do
178+ if ty[i] = nil then Fatal('a type is missing');
179+end;
180+
181+procedure MakeObjs;
182+var i, c: longint; o: PObj;
183+begin
184+ New(mod0); mod0^.name := InternStr('Zero');
185+ New(mod1); mod1^.name := InternStr('Other');
186+ curModule := mod0;
187+ for i := 0 to 5 do begin
188+ o := NewObj(oProc, NameOf(50 + i), ty[YProc0 + i mod 3]);
189+ o^.chunk := FirstProc + Rnd(NumProcs);
190+ o^.ext := i >= 4;
191+ o^.isCode := i = 3;
192+ procs[i] := o;
193+ end;
194+ for i := 0 to 2 do begin
195+ o := NewObj(oConst, NameOf(60 + i), tStr);
196+ o^.val := 2 + 3 * i;
197+ c := NewChunk(secRodata, -1, -1);
198+ SetData(c, @Letters[1], o^.val + 1, 1);
199+ o^.chunk := c;
200+ strs[i] := o;
201+ end;
202+ arrConst := NewObj(oConst, NameOf(63), ty[YArr]);
203+ arrConst^.chunk := NewChunk(secRodata, -1, -1);
204+ SetData(arrConst^.chunk, @Letters[1], 8, 8);
205+ typeObj := NewObj(oType, NameOf(64), ty[YRec]);
206+ builtinObj := NewObj(oBuiltin, NameOf(65), tNone);
207+ caseObj := NewObj(oCase, NameOf(66), variantT);
208+ caseObj^.val := 3;
209+ caseObj^.fields := NewObjs(oField, tInt, 2, 8, 67);
210+ caseObj^.fields^.val := 8;
211+end;
212+
213+procedure MakeVars;
214+var i, k: longint; o: PObj; t: PType;
215+begin
216+ for i := 0 to NumT - 1 do begin
217+ t := ty[i];
218+ o := NewObj(oVar, NameOf(i), t);
219+ o^.lev := 1;
220+ k := Rnd(9);
221+ if k = 2 then begin
222+ o^.lev := 0; o^.chunk := FirstGlob + Rnd(NumGlobs);
223+ end else if k = 3 then begin
224+ o^.ind := true; o^.val := AllocPerm(8, 8); o^.off := 8 * Rnd(3);
225+ end else if k = 4 then begin
226+ if (t^.form in [fInt, fPtr]) and (t^.size = 8) then
227+ o^.reg := VarRegs[Rnd(5)]
228+ else if t^.form = fReal then
229+ o^.reg := XVarRegs[Rnd(4)]
230+ else if t^.form = fSlice then begin
231+ o^.reg := VarRegs[Rnd(3)]; o^.reg2 := VarRegs[3 + Rnd(2)];
232+ end;
233+ if o^.reg = 0 then o^.val := AllocPerm(t^.size, 8);
234+ end else if k = 5 then begin
235+ o^.lev := 0; o^.chunk := FirstGlob + Rnd(NumGlobs); o^.module := mod1;
236+ end else if k = 6 then begin
237+ o^.lev := 0; o^.chunk := FirstGlob + Rnd(NumGlobs); o^.ext := true;
238+ end else
239+ o^.val := AllocPerm(t^.size + 8, 8);
240+ vars[i] := o;
241+ end;
242+end;
243+
244+{ Operands }
245+
246+function IntType: PType;
247+begin
248+ IntType := ty[IntTypes[Rnd(8)]];
249+end;
250+
251+procedure VarItem(var x: TItem; t: PType);
252+var i, k: longint;
253+begin
254+ k := Rnd(NumT);
255+ for i := 0 to NumT - 1 do
256+ if ty[i] = t then k := i;
257+ FillChar(x, SizeOf(x), 0);
258+ x.pos := Pos;
259+ MakeItem(x, vars[k]);
260+end;
261+
262+procedure Operand(var x: TItem; t: PType);
263+var k: longint; r: double; v: int64;
264+begin
265+ FillChar(x, SizeOf(x), 0);
266+ x.pos := Pos;
267+ if t = nil then begin
268+ case Rnd(14) of
269+ 0: MakeConst(x, tConst, ConstVal);
270+ 1: MakeConst(x, tConst, ConstVal mod 200);
271+ 2: begin t := IntType; v := ConstVal mod 100; MakeConst(x, t, v) end;
272+ 3: begin r := (ConstVal mod 1000) / 8.0; MakeReal(x, r) end;
273+ 4: MakeConst(x, tBool, Rnd(2));
274+ 5: MakeItem(x, strs[Rnd(3)]);
275+ 6: MakeConst(x, tNil, 0);
276+ 7: MakeItem(x, procs[Rnd(6)]);
277+ 8: begin
278+ if Rnd(4) = 0 then begin
279+ case Rnd(3) of
280+ 0: MakeItem(x, typeObj);
281+ 1: MakeItem(x, builtinObj);
282+ else MakeItem(x, caseObj);
283+ end;
284+ end else
285+ MakeItem(x, arrConst);
286+ end;
287+ 13: begin MakeItem(x, vars[Rnd(NumT)]); Value(x) end;
288+ else VarItem(x, ty[Rnd(NumT)]);
289+ end;
290+ exit;
291+ end;
292+ k := Rnd(10);
293+ if IsInt(t) then begin
294+ if k < 3 then begin MakeConst(x, tConst, ConstVal mod 100); exit end;
295+ if k = 3 then begin MakeConst(x, t, ConstVal mod 100); exit end;
296+ end else if t^.form = fReal then begin
297+ if k < 3 then begin r := (ConstVal mod 1000) / 8.0; MakeReal(x, r); exit end;
298+ end else if t^.form = fBool then begin
299+ if k < 3 then begin MakeConst(x, tBool, Rnd(2)); exit end;
300+ end else if t^.form = fPtr then begin
301+ if k < 2 then begin MakeConst(x, tNil, 0); exit end;
302+ end else if (t^.form = fSlice) and (t^.base = tU8) then begin
303+ if k < 3 then begin MakeItem(x, strs[Rnd(3)]); exit end;
304+ end;
305+ VarItem(x, t);
306+end;
307+
308+procedure CondItem(var x: TItem);
309+var y: TItem; L: longint; op: TSym; t: PType;
310+begin
311+ t := IntType;
312+ op := Cmps[Rnd(6)];
313+ Operand(x, t);
314+ Op1(op, x, L);
315+ Operand(y, t);
316+ Op2(op, x, y, L);
317+end;
318+
319+procedure Place(var x: TItem);
320+var i, k: longint; f: PObj; y, lo, hi: TItem;
321+begin
322+ VarItem(x, ty[Rnd(NumT)]);
323+ for i := 1 to 3 do begin
324+ if Rnd(3) <> 0 then begin
325+ k := Rnd(6);
326+ if (k = 0) or (x.typ^.form = fPtr) then
327+ Deref(x)
328+ else if x.typ^.form = fRecord then begin
329+ f := x.typ^.fields;
330+ k := Rnd(3);
331+ while (k > 0) and (f^.next <> nil) do begin f := f^.next; dec(k) end;
332+ Field(x, f);
333+ end else if x.typ^.form in [fArray, fSlice, fStr] then begin
334+ IndexPrep(x);
335+ if k < 4 then begin
336+ Operand(y, IntType);
337+ Index(x, y);
338+ end else begin
339+ Operand(lo, IntType);
340+ SliceLo(lo);
341+ Operand(hi, IntType);
342+ Slice(x, lo, hi);
343+ end;
344+ end;
345+ end;
346+ end;
347+end;
348+
349+procedure Dump(var x: TItem);
350+var name: shortstring; flags: longint;
351+begin
352+ name := '-';
353+ if x.typ <> nil then name := TypeName(x.typ);
354+ flags := Bit(x.vol) + 2 * Bit(x.isVar) + 4 * Bit(x.odd) + 8 * Bit(x.ro) + 16 * Bit(x.deref);
355+ write('I ', ord(x.mode), ' ', name, ' ', ord(x.rel), ' ', Bit(x.relSigned), ' ', x.fj, ' ', x.tj, ' ', x.val);
356+ writeln(' ', ord(x.base), ' ', x.chunk, ' ', x.off, ' ', flags, ' depth ', depth, ' pushed ', pushed);
357+end;
358+
359+procedure DoCall(var x: TItem);
360+var f, a: TItem; p: PObj; n: longint;
361+begin
362+ FillChar(f, SizeOf(f), 0);
363+ f.pos := Pos;
364+ if Rnd(5) = 0 then MakeItem(f, vars[YProc0 + Rnd(3)])
365+ else MakeItem(f, procs[Rnd(6)]);
366+ BeginCall(call, f);
367+ p := call.param;
368+ n := Rnd(4) - 1;
369+ while (p <> nil) or (n > 0) do begin
370+ if p <> nil then begin
371+ if p^.isVar and (Rnd(2) = 0) then begin
372+ VarItem(a, ty[YVptr]);
373+ Deref(a);
374+ end else if Rnd(6) = 0 then Operand(a, nil)
375+ else Operand(a, p^.typ);
376+ p := p^.next;
377+ end else begin
378+ Operand(a, nil);
379+ n := n - 1;
380+ end;
381+ PassArg(call, a);
382+ if (p = nil) and (n < 0) then n := 0;
383+ if (p <> nil) and (n < 0) and (Rnd(4) = 0) then begin p := nil; n := 0 end;
384+ end;
385+ EndCall(call, x);
386+end;
387+
388+procedure Binary(var x: TItem);
389+var y: TItem; L, M: longint; op: TSym; t: PType;
390+begin
391+ L := NoLabel;
392+ M := NoLabel;
393+ op := Ops[Rnd(20)];
394+ case Rnd(8) of
395+ 0, 1: t := IntType;
396+ 2: t := ty[YReal + Rnd(2)];
397+ 3: t := ty[YBool];
398+ 4: t := ty[YEnum + Rnd(2)];
399+ else t := ty[Rnd(NumT)];
400+ end;
401+ if Rnd(6) = 0 then begin
402+ if Flag then op := sAnd else op := sOr;
403+ CondItem(x);
404+ Op1(op, x, L);
405+ CondItem(y);
406+ end else if op = sIn then begin
407+ Operand(x, ty[YEnum]);
408+ Op1(op, x, L);
409+ Operand(y, ty[YSet]);
410+ end else begin
411+ Operand(x, t);
412+ Op1(op, x, L);
413+ if Rnd(5) = 0 then Operand(y, nil) else Operand(y, t);
414+ end;
415+ Op2(op, x, y, L);
416+ if (x.mode = mCond) and (Rnd(3) <> 0) then begin
417+ if Flag then CondJump(x, M) else CondJumpTrue(x, M);
418+ Fix(M);
419+ x.mode := mNone;
420+ end;
421+end;
422+
423+procedure Unary(var x: TItem);
424+begin
425+ Operand(x, nil);
426+ case Rnd(3) of
427+ 0: Neg(x);
428+ 1: NotOp(x);
429+ else Complement(x);
430+ end;
431+end;
432+
433+procedure DoMatch(var x: TItem);
434+var p, lo, hi: int64; L: longint;
435+begin
436+ L := NoLabel;
437+ case Rnd(3) of
438+ 0: VarItem(x, ty[YVariant]);
439+ 1: VarItem(x, ty[YEnum]);
440+ else Operand(x, nil);
441+ end;
442+ p := MatchBegin(x);
443+ MatchTag(p, ConstVal mod 10, L);
444+ lo := ConstVal mod 10;
445+ hi := ConstVal mod 10 + 10;
446+ MatchRange(p, lo, hi, L);
447+ MatchRange(p, 3, 3, L);
448+ Fix(L);
449+end;
450+
451+procedure DoFor(var x: TItem);
452+var o: PObj; lim: TItem; step: int64; exitL: longint;
453+begin
454+ o := vars[IntTypes[Rnd(8)]];
455+ step := ConstVal mod 5;
456+ if step = 0 then step := 1;
457+ if Rnd(2) = 0 then step := -step;
458+ FillChar(lim, SizeOf(lim), 0);
459+ lim.pos := Pos;
460+ MakeConst(lim, o^.typ, ConstVal mod 50);
461+ exitL := NoLabel;
462+ ForStep(o, step);
463+ ForNext(o, lim, step, exitL, pc, pc);
464+ Fix(exitL);
465+ x := lim;
466+end;
467+
468+procedure DoMisc(var x: TItem);
469+var y: TItem;
470+begin
471+ case Rnd(5) of
472+ 0: begin
473+ Place(x);
474+ Address(x);
475+ Operand(y, x.typ);
476+ IncDec(x, y, Flag);
477+ end;
478+ 1: begin
479+ Place(x);
480+ Pin(x);
481+ end;
482+ 2: begin
483+ Place(x);
484+ CopyDest(x);
485+ Place(y);
486+ CopyFrom(x, y);
487+ end;
488+ 3: begin
489+ Operand(x, nil);
490+ MakeStr(y);
491+ Coerce(y, ty[YBytes]);
492+ end;
493+ else begin
494+ Operand(x, nil);
495+ NilTest(x);
496+ UsesReals(x.pos);
497+ Discard(x);
498+ end;
499+ end;
500+end;
501+
502+procedure DoTemp(var x: TItem);
503+var a: TItem; c, h, n: longint; f: PObj;
504+begin
505+ FillChar(x, SizeOf(x), 0);
506+ x.pos := Pos;
507+ case Rnd(5) of
508+ 0: ZeroTemp(x, ty[YVariant]);
509+ 1: begin
510+ Construct(x, caseObj);
511+ f := caseObj^.fields;
512+ Operand(a, f^.typ);
513+ SetField(x, f, a);
514+ end;
515+ 2: begin
516+ ZeroTemp(x, ty[YRec]);
517+ f := ty[YRec]^.fields;
518+ if Flag then f := f^.next;
519+ Operand(a, f^.typ);
520+ SetField(x, f, a);
521+ end;
522+ 3: begin
523+ Operand(a, nil);
524+ h := Rnd(3) - 1;
525+ n := Rnd(3) - 1;
526+ c := ErrorChunk(a, h, n);
527+ MakeConst(x, tError, int64(c) + 1);
528+ end;
529+ else begin
530+ Operand(x, ty[YErr]);
531+ Msg(x);
532+ end;
533+ end;
534+end;
535+
536+procedure DoReturn(var x: TItem);
537+var f: PObj;
538+begin
539+ if (curRes = 4) and Flag then begin
540+ f := tuple2^.fields;
541+ if Flag then f := f^.next;
542+ if Flag then begin
543+ Operand(x, f^.typ);
544+ ReturnField(f, x);
545+ exit;
546+ end;
547+ DoCall(x);
548+ ReturnAll(x);
549+ exit;
550+ end;
551+ if Rnd(4) = 0 then begin ReturnNone; exit end;
552+ Operand(x, results[curRes]);
553+ ReturnValue(x);
554+end;
555+
556+procedure Step(k: longint; var x: TItem);
557+var y: TItem;
558+begin
559+ FillChar(x, SizeOf(x), 0);
560+ case k of
561+ 0: begin Operand(x, nil); Value(x) end;
562+ 1: begin Operand(x, nil); Address(x) end;
563+ 2: begin Operand(x, nil); Coerce(x, ty[Rnd(NumT)]) end;
564+ 3: begin Operand(x, nil); CoerceExact(x, IntType, '') end;
565+ 4: begin
566+ Place(x);
567+ Operand(y, x.typ);
568+ Assign(x, y);
569+ end;
570+ 5: Unary(x);
571+ 6: Binary(x);
572+ 7: begin Operand(x, nil); Convert(x, ty[Rnd(NumT)]) end;
573+ 8: Place(x);
574+ 9: DoCall(x);
575+ 10: DoMatch(x);
576+ 11: DoFor(x);
577+ 12: DoMisc(x);
578+ 13: DoTemp(x);
579+ 14: DoReturn(x);
580+ else Binary(x);
581+ end;
582+end;
583+
584+{ A step, and what it leaves, each a recovery point as the parser's
585+ statements are }
586+procedure RunStep;
587+begin
588+ gOk := false;
589+ recovery := @jb;
590+ if setjmp(jb) = 0 then begin
591+ Step(gK, gX);
592+ gOk := true;
593+ end;
594+ recovery := nil;
595+end;
596+
597+procedure RunDiscard;
598+begin
599+ recovery := @jb;
600+ if setjmp(jb) = 0 then Discard(gX);
601+ recovery := nil;
602+end;
603+
604+procedure GenProc(c: longint);
605+var sig: PType; i, line: longint;
606+begin
607+ curRes := Rnd(9);
608+ sig := ProcType(results[curRes], nil, 0);
609+ BeginProc(sig, nil);
610+ for i := 0 to 5 do AllocPerm(8, 8);
611+ MakeVars;
612+ checks := Flag;
613+ line := 1 + Rnd(40);
614+ EnterBody(c, line);
615+ for i := 1 to Steps do begin
616+ if errors >= 19 then break;
617+ gK := Rnd(17);
618+ demoted := false;
619+ RunStep;
620+ if not gOk then
621+ writeln('S ', c, ' ', gK, ' failed')
622+ else begin
623+ writeln('S ', c, ' ', gK, ' ok');
624+ Dump(gX);
625+ if (gK < 4) or ((gK >= 5) and (gK <= 9)) then RunDiscard;
626+ end;
627+ writeln('demoted ', Bit(demoted));
628+ ResetStack(0, 0);
629+ end;
630+ EndProc(c, sig^.base <> nil);
631+end;
632+
633+function ChunkNameOf(i: longint): longint;
634+var s: string;
635+begin
636+ s := 'p' + chr(48 + i div 10) + chr(48 + i mod 10);
637+ ChunkNameOf := Intern(@s[1], 3);
638+end;
639+
640+var
641+ i, c: longint; path: string;
642+begin
643+ seed := 5;
644+ for i := 1 to length(ParamStr(1)) do seed := seed * 10 + ord(ParamStr(1)[i]) - 48;
645+ Letters := 'abcdefgh' + #0;
646+ path := 'src/test/ItemDump.txt';
647+ if Open(path) <> '' then Fatal('no file');
648+ Next;
649+ listing := true;
650+ curFile := Intern(@path[1], length(path));
651+ for i := 0 to NumProcs - 1 do begin c := NewChunk(secText, -1, ChunkNameOf(i)); chunks^[c].live := true end;
652+ for i := 0 to NumGlobs - 1 do begin
653+ c := NewChunk(secBss, -1, ChunkNameOf(NumProcs + i));
654+ SetBss(c, 64, 8);
655+ end;
656+ MakeTypes;
657+ MakeObjs;
658+ for i := 0 to NumProcs - 1 do GenProc(FirstProc + i);
659+ writeln('pc ', pc, ' fixups ', numFixups, ' lines ', numLines, ' said ', SaidCount);
660+ for i := 0 to pc - 1 do write(HexStr(code^[i], 2));
661+ writeln;
662+ for i := 0 to numFixups - 1 do writeln('F ', fixups^[i].at, ' ', fixups^[i].chunk, ' ', fixups^[i].addend);
663+ for i := 0 to numLines - 1 do writeln('L ', lines^[i].at, ' ', lines^[i].chunk, ' ', lines^[i].line, ' ', lines^[i].col);
664+ List(-1);
665+end.

src/test/ItemDump.raz added +679 -0

@@ -0,0 +1,679 @@
1+(* Drives Item with a fixed pseudo-random script of operands and
2+ operations, with mistakes among them, and prints what each step gave
3+ (the item, or that it failed, whose message goes to standard error),
4+ then the bytes, fixups, line notes and listing (raz -S) of the code
5+ it made: src/Item.raz's side of a test against the seed's,
6+ ItemDump.pas, which does and prints the same. The argument, a digit,
7+ changes the script. A run ends at the 20th error, as a compile does,
8+ so several scripts are run. *)
9+module ItemDump;
10+import Out, Fmt, Files, Heap, Diag, Scan, Sym, Chunk, X := X64, Gen, Item;
11+
12+const
13+ FirstProc = 3; (* chunks 0 to 2 are Gen's own *)
14+ NumProcs = 30;
15+ FirstGlob = FirstProc + NumProcs;
16+ NumGlobs = 4;
17+ Steps = 14;
18+ (* the types of the script, by number *)
19+ YInt = 0; YI64 = 1; YI32 = 2; YU8 = 3; YU16 = 4; YU32 = 5; YU64 = 6; YBool = 7;
20+ YReal = 8; YF32 = 9; YI8 = 10; YEnum = 11; YSet = 12; YPtr = 13; YVptr = 14;
21+ YPtrArr = 15; YArr = 16; YArrU8 = 17; YSlice = 18; YBytes = 19; YRec = 20;
22+ YPacked = 21; YVariant = 22; YProc0 = 23; YProc1 = 24; YProc2 = 25;
23+ YPtrRec = 26; YErr = 27; YVrec = 28; YVarr = 29;
24+ NumT = 30;
25+ IntTypes: [8]INT = [YInt, YI64, YI32, YU8, YU16, YU32, YU64, YI8];
26+ Ops: [20]Scan.Sym = [Scan.sPlus, Scan.sMinus, Scan.sTimes, Scan.sDiv, Scan.sMod,
27+ Scan.sAmp, Scan.sBar, Scan.sXor, Scan.sShl, Scan.sShr,
28+ Scan.sEql, Scan.sNeq, Scan.sLss, Scan.sLeq, Scan.sGtr, Scan.sGeq,
29+ Scan.sSlash, Scan.sIn, Scan.sPlus, Scan.sMinus];
30+ Cmps: [6]Scan.Sym = [Scan.sEql, Scan.sNeq, Scan.sLss, Scan.sLeq, Scan.sGtr, Scan.sGeq];
31+
32+var
33+ Letters: []U8;
34+ seed: I64;
35+ ty: [NumT]^Sym.Type;
36+ vars: [NumT]^Sym.Obj; (* a variable of each type, placed anew for each procedure *)
37+ procs: [6]^Sym.Obj;
38+ strs: [3]^Sym.Obj;
39+ arrConst, typeObj, builtinObj, caseObj: ^Sym.Obj;
40+ mod0, mod1: ^Sym.Module;
41+ tuple2, record3, packedR, variantT: ^Sym.Type;
42+ results: [9]^Sym.Type;
43+ curRes: INT; (* the result of the procedure, an index of results *)
44+ call: Gen.CallInfo;
45+
46+proc rnd(n: INT): INT;
47+begin
48+ seed := (seed * 1103515245 + 12345) & 7FFFFFFFH;
49+ return INT((seed shr 8) mod I64(n));
50+end;
51+
52+proc flag: BOOL;
53+begin
54+ return rnd(2) = 0;
55+end;
56+
57+proc bit(f: BOOL): INT;
58+begin
59+ if f then return 1; end;
60+ return 0;
61+end;
62+
63+proc pos: Diag.Pos;
64+var p: Diag.Pos;
65+begin
66+ p.f := 0; p.a := rnd(400); p.b := p.a + 1 + rnd(12);
67+ return p;
68+end;
69+
70+proc constVal: I64;
71+var x: INT; r: I64;
72+begin
73+ x := rnd(1 shl 30);
74+ match rnd(7) of
75+ | 0: r := x mod 10;
76+ | 1: r := -(x mod 100);
77+ | 2: r := I64(1) shl (x mod 20);
78+ | 3: r := x;
79+ | 4: r := I64(x) * 4096 * 4096 * 9 - 7;
80+ | 5: r := -I64(x) * 8;
81+ | else: r := x mod 1000 - 500;
82+ end;
83+ return r;
84+end;
85+
86+(* A name, interned *)
87+proc intern(s: []U8): INT;
88+begin
89+ return Scan.intern(ADR(s[0]), LEN(s));
90+end;
91+
92+(* A name v00, v01, ... , interned *)
93+proc nameOf(i: INT): INT;
94+var s: [3]U8;
95+begin
96+ s[0] := 'v'; s[1] := U8(48 + i div 10); s[2] := U8(48 + i mod 10);
97+ return Scan.intern(ADR(s[0]), 3);
98+end;
99+
100+proc newObjs(cls: Sym.Class; t: ^Sym.Type; n: INT; step: I64; at: INT): ^Sym.Obj;
101+var first, o, last: ^Sym.Obj; i: INT;
102+begin
103+ first := nil; last := nil;
104+ for i := 0 to n - 1 do
105+ o := Sym.newObj(cls, nameOf(at + i), t);
106+ o^.val := step * I64(i);
107+ if last = nil then first := o; else last^.next := o; end;
108+ last := o;
109+ end;
110+ return first;
111+end;
112+
113+proc newType(form: Sym.Form; size, align: I64): ^Sym.Type;
114+begin
115+ return Sym.newType(form, size, align);
116+end;
117+
118+proc procType(res: ^Sym.Type; params: ^Sym.Obj; n: INT): ^Sym.Type;
119+var t: ^Sym.Type;
120+begin
121+ t := newType(Sym.fProc, 8, 8);
122+ t^.base := res;
123+ t^.fields := params;
124+ t^.len := n;
125+ return t;
126+end;
127+
128+proc param(t: ^Sym.Type; isVar: BOOL; at: INT): ^Sym.Obj;
129+var o: ^Sym.Obj;
130+begin
131+ o := Sym.newObj(Sym.oVar, nameOf(at), t);
132+ o^.param := true;
133+ o^.isVar := isVar;
134+ return o;
135+end;
136+
137+proc makeTypes;
138+var t: ^Sym.Type; p, q, r: ^Sym.Obj; i: INT;
139+begin
140+ ty[YInt] := Sym.tInt; ty[YI64] := Sym.tI64; ty[YI32] := Sym.tI32; ty[YU8] := Sym.tU8;
141+ ty[YU16] := Sym.tU16; ty[YU32] := Sym.tU32; ty[YU64] := Sym.tU64; ty[YBool] := Sym.tBool;
142+ ty[YReal] := Sym.tReal; ty[YF32] := Sym.tF32; ty[YI8] := Sym.tI8; ty[YErr] := Sym.tError;
143+ ty[YBytes] := Sym.tBytes;
144+ t := newType(Sym.fEnum, 1, 1); t^.len := 5; ty[YEnum] := t;
145+ t := newType(Sym.fSet, 8, 8); t^.len := 5; t^.base := ty[YEnum]; ty[YSet] := t;
146+ t := newType(Sym.fPtr, 8, 8); t^.base := Sym.tI64; ty[YPtr] := t;
147+ t := newType(Sym.fPtr, 8, 8); t^.base := Sym.tI64; t^.vol := true; ty[YVptr] := t;
148+ t := newType(Sym.fArray, 48, 8); t^.base := Sym.tI64; t^.len := 6; ty[YArr] := t;
149+ t := newType(Sym.fPtr, 8, 8); t^.base := ty[YArr]; ty[YPtrArr] := t;
150+ t := newType(Sym.fPtr, 8, 8); t^.base := ty[YArr]; t^.vol := true; ty[YVarr] := t;
151+ t := newType(Sym.fArray, 8, 1); t^.base := Sym.tU8; t^.len := 8; ty[YArrU8] := t;
152+ t := newType(Sym.fSlice, 16, 8); t^.base := Sym.tI64; ty[YSlice] := t;
153+ (* a record of an I64, an F64 and an I32 *)
154+ record3 := newType(Sym.fRecord, 24, 8);
155+ p := Sym.newObj(Sym.oField, nameOf(40), Sym.tI64); p^.val := 0;
156+ q := Sym.newObj(Sym.oField, nameOf(41), Sym.tReal); q^.val := 8; p^.next := q;
157+ r := Sym.newObj(Sym.oField, nameOf(42), Sym.tI32); r^.val := 16; q^.next := r;
158+ record3^.fields := p;
159+ ty[YRec] := record3;
160+ t := newType(Sym.fPtr, 8, 8); t^.base := record3; ty[YPtrRec] := t;
161+ t := newType(Sym.fPtr, 8, 8); t^.base := record3; t^.vol := true; ty[YVrec] := t;
162+ (* a packed record: a byte, then an I32 that may be misaligned *)
163+ packedR := newType(Sym.fRecord, 53, 1);
164+ packedR^.packd := true;
165+ p := Sym.newObj(Sym.oField, nameOf(43), Sym.tU8); p^.val := 0;
166+ q := Sym.newObj(Sym.oField, nameOf(44), Sym.tI32); q^.val := 1; p^.next := q;
167+ r := Sym.newObj(Sym.oField, nameOf(46), ty[YArr]); r^.val := 5; q^.next := r;
168+ packedR^.fields := p;
169+ ty[YPacked] := packedR;
170+ variantT := newType(Sym.fVariant, 16, 8);
171+ ty[YVariant] := variantT;
172+ tuple2 := newType(Sym.fRecord, 16, 8);
173+ tuple2^.tuple := true; tuple2^.len := 2; tuple2^.fields := newObjs(Sym.oVar, Sym.tInt, 2, 8, 45);
174+ (* procedures: (I64, F64) I64; (); (var I64, []I64) of two results *)
175+ p := param(Sym.tInt, false, 46); p^.next := param(Sym.tReal, false, 47);
176+ ty[YProc0] := procType(Sym.tInt, p, 2);
177+ ty[YProc1] := procType(nil, nil, 0);
178+ p := param(Sym.tI64, true, 48); p^.next := param(ty[YSlice], false, 49);
179+ ty[YProc2] := procType(tuple2, p, 2);
180+ results[0] := nil; results[1] := Sym.tInt; results[2] := Sym.tReal; results[3] := ty[YSlice];
181+ results[4] := tuple2; results[5] := record3; results[6] := Sym.tF32; results[7] := Sym.tI16;
182+ results[8] := ty[YBytes];
183+ for i := 0 to NumT - 1 do
184+ if ty[i] = nil then Diag.fatal("a type is missing"); end;
185+ end;
186+end;
187+
188+(* The objects named by the script: procedures, strings, constants of
189+ an array, a type, a built-in, a case of a variant *)
190+proc makeObjs;
191+var i, c: INT; o: ^Sym.Obj;
192+begin
193+ NEW(mod0, Heap.heap); mod0^.name := intern("Zero");
194+ NEW(mod1, Heap.heap); mod1^.name := intern("Other");
195+ Sym.setCurModule(mod0);
196+ for i := 0 to 5 do
197+ o := Sym.newObj(Sym.oProc, nameOf(50 + i), ty[YProc0 + i mod 3]);
198+ o^.chunk := FirstProc + rnd(NumProcs);
199+ o^.ext := i >= 4;
200+ o^.isCode := i = 3;
201+ procs[i] := o;
202+ end;
203+ for i := 0 to 2 do
204+ o := Sym.newObj(Sym.oConst, nameOf(60 + i), Sym.tStr);
205+ o^.val := 2 + 3 * i;
206+ c := Chunk.newChunk(Chunk.secRodata, -1, -1);
207+ Chunk.setData(c, ADR(Letters[0]), INT(o^.val) + 1, 1);
208+ o^.chunk := c;
209+ strs[i] := o;
210+ end;
211+ arrConst := Sym.newObj(Sym.oConst, nameOf(63), ty[YArr]);
212+ arrConst^.chunk := Chunk.newChunk(Chunk.secRodata, -1, -1);
213+ Chunk.setData(arrConst^.chunk, ADR(Letters[0]), 8, 8);
214+ typeObj := Sym.newObj(Sym.oType, nameOf(64), ty[YRec]);
215+ builtinObj := Sym.newObj(Sym.oBuiltin, nameOf(65), Sym.tNone);
216+ caseObj := Sym.newObj(Sym.oCase, nameOf(66), variantT);
217+ caseObj^.val := 3;
218+ caseObj^.fields := newObjs(Sym.oField, Sym.tInt, 2, 8, 67);
219+ caseObj^.fields^.val := 8;
220+end;
221+
222+(* The variable of each type, in the frame, a chunk, a slot, a register,
223+ another module or C's, as the procedure compiled has them *)
224+proc makeVars;
225+var i, k: INT; o: ^Sym.Obj; t: ^Sym.Type;
226+begin
227+ for i := 0 to NumT - 1 do
228+ t := ty[i];
229+ o := Sym.newObj(Sym.oVar, nameOf(i), t);
230+ o^.lev := 1;
231+ k := rnd(9);
232+ if k = 2 then
233+ o^.lev := 0; o^.chunk := FirstGlob + rnd(NumGlobs);
234+ elsif k = 3 then
235+ o^.ind := true; o^.val := Gen.allocPerm(8, 8); o^.off := 8 * rnd(3);
236+ elsif k = 4 then
237+ if (t^.form in {Sym.fInt, Sym.fPtr}) and (t^.size = 8) then
238+ o^.reg := Gen.VarRegs[rnd(5)];
239+ elsif t^.form = Sym.fReal then
240+ o^.reg := Gen.XVarRegs[rnd(4)];
241+ elsif t^.form = Sym.fSlice then
242+ o^.reg := Gen.VarRegs[rnd(3)]; o^.reg2 := Gen.VarRegs[3 + rnd(2)];
243+ end;
244+ if o^.reg = 0 then o^.val := Gen.allocPerm(t^.size, 8); end;
245+ elsif k = 5 then
246+ o^.lev := 0; o^.chunk := FirstGlob + rnd(NumGlobs); o^.home := mod1;
247+ elsif k = 6 then
248+ o^.lev := 0; o^.chunk := FirstGlob + rnd(NumGlobs); o^.ext := true;
249+ else
250+ o^.val := Gen.allocPerm(t^.size + 8, 8);
251+ end;
252+ vars[i] := o;
253+ end;
254+end;
255+
256+(* Operands *)
257+
258+proc intType: ^Sym.Type;
259+begin
260+ return ty[IntTypes[rnd(8)]];
261+end;
262+
263+proc varItem(var x: Item.Item; t: ^Sym.Type): ERROR;
264+var i, k: INT;
265+begin
266+ k := rnd(NumT);
267+ for i := 0 to NumT - 1 do
268+ if ty[i] = t then k := i; end;
269+ end;
270+ x := {};
271+ x.pos := pos();
272+ return Item.makeItem(x, vars[k]);
273+end;
274+
275+(* An operand of type t, or of any if t is nil *)
276+proc operand(var x: Item.Item; t: ^Sym.Type): ERROR;
277+var k: INT; r: F64; v: I64;
278+begin
279+ x := {};
280+ x.pos := pos();
281+ if t = nil then
282+ match rnd(14) of
283+ | 0: Item.makeConst(x, Sym.tConst, constVal());
284+ | 1: Item.makeConst(x, Sym.tConst, constVal() mod 200);
285+ | 2: t := intType(); v := constVal() mod 100; Item.makeConst(x, t, v);
286+ | 3: r := F64(constVal() mod 1000) / 8.0; Item.makeReal(x, r);
287+ | 4: Item.makeConst(x, Sym.tBool, I64(rnd(2)));
288+ | 5: return Item.makeItem(x, strs[rnd(3)]);
289+ | 6: Item.makeConst(x, Sym.tNil, 0);
290+ | 7: return Item.makeItem(x, procs[rnd(6)]);
291+ | 8: if rnd(4) = 0 then
292+ match rnd(3) of
293+ | 0: return Item.makeItem(x, typeObj);
294+ | 1: return Item.makeItem(x, builtinObj);
295+ | else: return Item.makeItem(x, caseObj);
296+ end;
297+ end;
298+ return Item.makeItem(x, arrConst);
299+ | 13: try Item.makeItem(x, vars[rnd(NumT)]); return Item.value(x);
300+ | else: return varItem(x, ty[rnd(NumT)]);
301+ end;
302+ return nil;
303+ end;
304+ k := rnd(10);
305+ if Sym.isInt(t) then
306+ if k < 3 then Item.makeConst(x, Sym.tConst, constVal() mod 100); return nil; end;
307+ if k = 3 then Item.makeConst(x, t, constVal() mod 100); return nil; end;
308+ elsif t^.form = Sym.fReal then
309+ if k < 3 then r := F64(constVal() mod 1000) / 8.0; Item.makeReal(x, r); return nil; end;
310+ elsif t^.form = Sym.fBool then
311+ if k < 3 then Item.makeConst(x, Sym.tBool, I64(rnd(2))); return nil; end;
312+ elsif t^.form = Sym.fPtr then
313+ if k < 2 then Item.makeConst(x, Sym.tNil, 0); return nil; end;
314+ elsif (t^.form = Sym.fSlice) and (t^.base = Sym.tU8) then
315+ if k < 3 then return Item.makeItem(x, strs[rnd(3)]); end;
316+ end;
317+ return varItem(x, t);
318+end;
319+
320+(* A condition, left as one: a comparison of two integers *)
321+proc condItem(var x: Item.Item): ERROR;
322+var y: Item.Item; L: INT; op: Scan.Sym; t: ^Sym.Type;
323+begin
324+ t := intType();
325+ op := Cmps[rnd(6)];
326+ try operand(x, t);
327+ try Item.op1(op, x, L);
328+ try operand(y, t);
329+ return Item.op2(op, x, y, L);
330+end;
331+
332+(* A variable, or part of one: through a pointer, a field, an element, a slice *)
333+proc place(var x: Item.Item): ERROR;
334+var i, k: INT; f: ^Sym.Obj; y, lo, hi: Item.Item;
335+begin
336+ try varItem(x, ty[rnd(NumT)]);
337+ for i := 1 to 3 do
338+ if rnd(3) # 0 then
339+ k := rnd(6);
340+ if (k = 0) or (x.typ^.form = Sym.fPtr) then
341+ try Item.deref(x);
342+ elsif x.typ^.form = Sym.fRecord then
343+ f := x.typ^.fields;
344+ k := rnd(3);
345+ while (k > 0) and (f^.next # nil) do f := f^.next; DEC(k); end;
346+ try Item.field(x, f);
347+ elsif (x.typ^.form in {Sym.fArray, Sym.fSlice, Sym.fStr}) then
348+ try Item.indexPrep(x);
349+ if k < 4 then
350+ try operand(y, intType());
351+ try Item.index(x, y);
352+ else
353+ try operand(lo, intType());
354+ try Item.sliceLo(lo);
355+ try operand(hi, intType());
356+ try Item.slice(x, lo, hi);
357+ end;
358+ end;
359+ end;
360+ end;
361+ return nil;
362+end;
363+
364+(* The state of an item *)
365+proc dump(var x: Item.Item);
366+var name: []U8; flags: INT;
367+begin
368+ name := "-";
369+ if x.typ # nil then name := Sym.typeName(x.typ); end;
370+ flags := bit(x.vol) + 2 * bit(x.isVar) + 4 * bit(x.odd) + 8 * bit(x.ro) + 16 * bit(x.deref);
371+ Fmt.print("I {} {} {} {} {} {} {}", [Fmt.int(INT(x.mode)), Fmt.str(name), Fmt.int(INT(x.rel)),
372+ Fmt.int(bit(x.relSigned)), Fmt.int(x.fj), Fmt.int(x.tj), Fmt.int(x.val)]);
373+ Fmt.print(" {} {} {} {} depth {} pushed {}\n", [Fmt.int(INT(x.base)), Fmt.int(x.chunk), Fmt.int(x.off),
374+ Fmt.int(flags), Fmt.int(Gen.depth), Fmt.int(Gen.pushed)]);
375+end;
376+
377+(* A call: of a procedure of the script or a variable of a procedure
378+ type, with arguments that mostly fit its parameters *)
379+proc doCall(var x: Item.Item): ERROR;
380+var f, a: Item.Item; p: ^Sym.Obj; n: INT;
381+begin
382+ f := {};
383+ f.pos := pos();
384+ if rnd(5) = 0 then try Item.makeItem(f, vars[YProc0 + rnd(3)]);
385+ else try Item.makeItem(f, procs[rnd(6)]); end;
386+ try Item.beginCall(call, f);
387+ p := call.param;
388+ n := rnd(4) - 1;
389+ while (p # nil) or (n > 0) do
390+ if p # nil then
391+ if p^.isVar and (rnd(2) = 0) then
392+ try varItem(a, ty[YVptr]);
393+ try Item.deref(a);
394+ elsif rnd(6) = 0 then try operand(a, nil);
395+ else try operand(a, p^.typ); end;
396+ p := p^.next;
397+ else
398+ try operand(a, nil);
399+ n := n - 1;
400+ end;
401+ try Item.passArg(call, a);
402+ if (p = nil) and (n < 0) then n := 0; end;
403+ if (p # nil) and (n < 0) and (rnd(4) = 0) then p := nil; n := 0; end;
404+ end;
405+ return Item.endCall(call, x);
406+end;
407+
408+(* A binary operation, with a condition's jumps made after it, sometimes *)
409+proc binary(var x: Item.Item): ERROR;
410+var y: Item.Item; L, M: INT; op: Scan.Sym; t: ^Sym.Type;
411+begin
412+ L := Gen.NoLabel;
413+ M := Gen.NoLabel;
414+ op := Ops[rnd(20)];
415+ match rnd(8) of
416+ | 0, 1: t := intType();
417+ | 2: t := ty[YReal + rnd(2)];
418+ | 3: t := ty[YBool];
419+ | 4: t := ty[YEnum + rnd(2)];
420+ | else: t := ty[rnd(NumT)];
421+ end;
422+ if rnd(6) = 0 then
423+ (* and, or *)
424+ if flag() then op := Scan.sAnd; else op := Scan.sOr; end;
425+ try condItem(x);
426+ try Item.op1(op, x, L);
427+ try condItem(y);
428+ elsif op = Scan.sIn then
429+ try operand(x, ty[YEnum]);
430+ try Item.op1(op, x, L);
431+ try operand(y, ty[YSet]);
432+ else
433+ try operand(x, t);
434+ try Item.op1(op, x, L);
435+ if rnd(5) = 0 then try operand(y, nil); else try operand(y, t); end;
436+ end;
437+ try Item.op2(op, x, y, L);
438+ if (x.mode = Item.mCond) and (rnd(3) # 0) then
439+ if flag() then try Item.condJump(x, M); else try Item.condJumpTrue(x, M); end;
440+ Gen.fix(M);
441+ x.mode := Item.mNone; (* its values are used *)
442+ end;
443+ return nil;
444+end;
445+
446+proc unary(var x: Item.Item): ERROR;
447+begin
448+ try operand(x, nil);
449+ match rnd(3) of
450+ | 0: return Item.neg(x);
451+ | 1: return Item.notOp(x);
452+ | else: return Item.complement(x);
453+ end;
454+end;
455+
456+(* match: the slot of a variant, an enumeration or an integer, and
457+ tests of it *)
458+proc doMatch(var x: Item.Item): ERROR;
459+var p, lo, hi: I64; L: INT;
460+begin
461+ L := Gen.NoLabel;
462+ match rnd(3) of
463+ | 0: try varItem(x, ty[YVariant]);
464+ | 1: try varItem(x, ty[YEnum]);
465+ | else: try operand(x, nil);
466+ end;
467+ p := try Item.matchBegin(x);
468+ Item.matchTag(p, constVal() mod 10, L);
469+ lo := constVal() mod 10;
470+ hi := constVal() mod 10 + 10;
471+ Item.matchRange(p, lo, hi, L);
472+ Item.matchRange(p, 3, 3, L);
473+ Gen.fix(L);
474+ return nil;
475+end;
476+
477+(* A for loop's variable stepped and tested *)
478+proc doFor(var x: Item.Item): ERROR;
479+var o: ^Sym.Obj; lim: Item.Item; step: I64; exitL: INT;
480+begin
481+ o := vars[IntTypes[rnd(8)]];
482+ step := constVal() mod 5;
483+ if step = 0 then step := 1; end;
484+ if rnd(2) = 0 then step := -step; end;
485+ lim := {};
486+ lim.pos := pos();
487+ Item.makeConst(lim, o^.typ, constVal() mod 50);
488+ exitL := Gen.NoLabel;
489+ try Item.forStep(o, step);
490+ try Item.forNext(o, lim, step, exitL, Chunk.pc, Chunk.pc);
491+ Gen.fix(exitL);
492+ x := lim;
493+ return nil;
494+end;
495+
496+(* INC and DEC, pin, COPY *)
497+proc doMisc(var x: Item.Item): ERROR;
498+var y: Item.Item;
499+begin
500+ match rnd(5) of
501+ | 0:
502+ try place(x);
503+ try Item.address(x);
504+ try operand(y, x.typ);
505+ return Item.incDec(x, y, flag());
506+ | 1:
507+ try place(x);
508+ return Item.pin(x);
509+ | 2:
510+ try place(x);
511+ try Item.copyDest(x);
512+ try place(y);
513+ return Item.copyFrom(x, y);
514+ | 3:
515+ try operand(x, nil);
516+ Item.makeStr(y);
517+ return Item.coerce(y, ty[YBytes]);
518+ | else:
519+ try operand(x, nil);
520+ Item.nilTest(x);
521+ Item.usesReals(x.pos);
522+ return Item.discard(x);
523+ end;
524+end;
525+
526+(* A variant, a record's fields, an error's chunk, the message of one *)
527+proc doTemp(var x: Item.Item): ERROR;
528+var a: Item.Item; c, h, n: INT; f: ^Sym.Obj;
529+begin
530+ x := {};
531+ x.pos := pos();
532+ match rnd(5) of
533+ | 0: Item.zeroTemp(x, ty[YVariant]);
534+ | 1:
535+ Item.construct(x, caseObj);
536+ f := caseObj^.fields;
537+ try operand(a, f^.typ);
538+ return Item.setField(x, f, a);
539+ | 2:
540+ Item.zeroTemp(x, ty[YRec]);
541+ f := ty[YRec]^.fields;
542+ if flag() then f := f^.next; end;
543+ try operand(a, f^.typ);
544+ return Item.setField(x, f, a);
545+ | 3:
546+ try operand(a, nil);
547+ h := rnd(3) - 1;
548+ n := rnd(3) - 1;
549+ c := try Item.errorChunk(a, h, n);
550+ Item.makeConst(x, Sym.tError, I64(c) + 1);
551+ return nil;
552+ | else:
553+ try operand(x, ty[YErr]);
554+ return Item.msg(x);
555+ end;
556+ return nil;
557+end;
558+
559+proc doReturn(var x: Item.Item): ERROR;
560+var f: ^Sym.Obj;
561+begin
562+ if (curRes = 4) and flag() then
563+ (* several results *)
564+ f := tuple2^.fields;
565+ if flag() then f := f^.next; end;
566+ if flag() then
567+ try operand(x, f^.typ);
568+ return Item.returnField(f, x);
569+ end;
570+ try doCall(x);
571+ return Item.returnAll(x);
572+ end;
573+ if rnd(4) = 0 then return Item.returnNone(); end;
574+ try operand(x, results[curRes]);
575+ return Item.returnValue(x);
576+end;
577+
578+(* One step of the script, whose item is x *)
579+proc step(k: INT; var x: Item.Item): ERROR;
580+var y: Item.Item;
581+begin
582+ x := {};
583+ match k of
584+ | 0: try operand(x, nil); return Item.value(x);
585+ | 1: try operand(x, nil); return Item.address(x);
586+ | 2: try operand(x, nil); return Item.coerce(x, ty[rnd(NumT)]);
587+ | 3: try operand(x, nil); return Item.coerceExact(x, intType(), "");
588+ | 4:
589+ try place(x);
590+ try operand(y, x.typ);
591+ return Item.assign(x, y);
592+ | 5: return unary(x);
593+ | 6: return binary(x);
594+ | 7: try operand(x, nil); return Item.convert(x, ty[rnd(NumT)]);
595+ | 8: return place(x);
596+ | 9: return doCall(x);
597+ | 10: return doMatch(x);
598+ | 11: return doFor(x);
599+ | 12: return doMisc(x);
600+ | 13: return doTemp(x);
601+ | 14: return doReturn(x);
602+ | else: return binary(x);
603+ end;
604+end;
605+
606+(* One procedure of Steps steps *)
607+proc genProc(c: INT);
608+var
609+ sig: ^Sym.Type; i, k, line: INT; x: Item.Item; err: ERROR;
610+begin
611+ curRes := rnd(9);
612+ sig := procType(results[curRes], nil, 0);
613+ Item.beginProc(sig, nil);
614+ for i := 0 to 5 do _ := Gen.allocPerm(8, 8); end;
615+ makeVars();
616+ Item.setChecks(flag());
617+ line := 1 + rnd(40);
618+ Gen.enterBody(c, line);
619+ for i := 1 to Steps do
620+ if Diag.errors >= 19 then break; end; (* the 20th would end the run *)
621+ k := rnd(17);
622+ Item.setDemoted(false);
623+ err := step(k, x);
624+ if err # nil then
625+ Fmt.print("S {} {} failed\n", [Fmt.int(c), Fmt.int(k)]);
626+ else
627+ Fmt.print("S {} {} ok\n", [Fmt.int(c), Fmt.int(k)]);
628+ dump(x);
629+ (* the items of these steps are as an operand is, on the stack *)
630+ if (k < 4) or ((k >= 5) and (k <= 9)) then _ := Item.discard(x); end;
631+ end;
632+ Fmt.print("demoted {}\n", [Fmt.int(bit(Item.demoted))]);
633+ Gen.resetStack(0, 0);
634+ end;
635+ _ := Gen.endProc(c, sig^.base # nil);
636+end;
637+
638+proc chunkNameOf(i: INT): INT;
639+var s: [3]U8;
640+begin
641+ s[0] := 'p'; s[1] := U8(48 + i div 10); s[2] := U8(48 + i mod 10);
642+ return Scan.intern(ADR(s[0]), 3);
643+end;
644+
645+proc main*;
646+var i, c: INT; path: []U8; arg: []U8;
647+begin
648+ arg := Files.arg(1);
649+ seed := 5;
650+ for i := 0 to LEN(arg) - 1 do seed := seed * 10 + I64(arg[i]) - 48; end;
651+ Letters := "abcdefgh\0";
652+ path := "src/test/ItemDump.txt";
653+ if LEN(Scan.open(path)) # 0 then Diag.fatal("no file"); end;
654+ Scan.next; (* the string the file starts with *)
655+ X.setListing(true);
656+ Chunk.setCurFile(Scan.intern(ADR(path[0]), LEN(path)));
657+ for i := 0 to NumProcs - 1 do c := Chunk.newChunk(Chunk.secText, -1, chunkNameOf(i)); Chunk.setLive(c); end;
658+ for i := 0 to NumGlobs - 1 do
659+ c := Chunk.newChunk(Chunk.secBss, -1, chunkNameOf(NumProcs + i));
660+ Chunk.setBss(c, 64, 8);
661+ end;
662+ makeTypes();
663+ makeObjs();
664+ for i := 0 to NumProcs - 1 do genProc(FirstProc + i); end;
665+ Fmt.print("pc {} fixups {} lines {} said {}\n", [Fmt.int(Chunk.pc),
666+ Fmt.int(Chunk.numFixups), Fmt.int(Chunk.numLines), Fmt.int(X.saidCount())]);
667+ for i := 0 to Chunk.pc - 1 do Out.hex(U64(Chunk.text[i]), 2); end;
668+ Out.ln;
669+ for i := 0 to Chunk.numFixups - 1 do
670+ Fmt.print("F {} {} {}\n", [Fmt.int(Chunk.fixups[i].at), Fmt.int(Chunk.fixups[i].chunk), Fmt.int(Chunk.fixups[i].addend)]);
671+ end;
672+ for i := 0 to Chunk.numLines - 1 do
673+ Fmt.print("L {} {} {} {}\n", [Fmt.int(Chunk.lines[i].at), Fmt.int(Chunk.lines[i].chunk),
674+ Fmt.int(Chunk.lines[i].line), Fmt.int(Chunk.lines[i].col)]);
675+ end;
676+ X.list(-1);
677+end;
678+
679+end ItemDump.

src/test/ItemDump.txt added +41 -0

@@ -0,0 +1,41 @@
1+"item test"
2+ x value sum alpha beta;
3+ next beta items len alpha next count alpha beta;
4+ value beta count beta next value;
5+ len beta count;
6+ sum len alpha len len value alpha count;
7+ next x n;
8+ x next beta len n next;
9+ sum x beta len len sum count items beta;
10+ tmp beta len alpha len count p;
11+ next value items p len p items n;
12+ x tmp count beta;
13+ n next p items tmp p n;
14+ beta beta next value x items x;
15+ value alpha sum beta next len;
16+ items items tmp items len p len p beta;
17+ beta n p tmp sum beta alpha tmp tmp;
18+ sum len sum p n;
19+ value sum items alpha p items x len;
20+ p alpha count;
21+ n x tmp count value value p beta x;
22+ value next n x value next;
23+ tmp value items sum value;
24+ x beta x x;
25+ sum count alpha p;
26+ len x n n alpha x value next items;
27+ len items x tmp next len sum;
28+ tmp alpha p sum next value value value;
29+ beta p sum value alpha count;
30+ count p x;
31+ items len alpha;
32+ alpha len x;
33+ beta items len alpha beta count len;
34+ x sum n items len items;
35+ beta beta p p p p;
36+ beta x beta tmp items;
37+ n p tmp x next alpha count next;
38+ x tmp next alpha next;
39+ sum beta tmp n next;
40+ x items count next next;
41+ next items sum count len count count value tmp;

src/test/LinkDump.pas added +91 -0

@@ -0,0 +1,91 @@
1+{ Makes a program of chunks by a fixed pseudo-random script, links it and
2+ writes it as an executable to the file of the second argument, in the
3+ way the first says (0 static, 1 dynamic, 2 stripped): the seed's side
4+ of a test of src/Link.raz and src/Elf.raz, whose LinkDump.raz does
5+ the same and writes the same file. }
6+program linkdump;
7+{$mode objfpc}{$H-}
8+uses diag, scan, chunk, link, elf;
9+const NumC = 200;
10+var
11+ seed: int64;
12+ names: array[0..7] of longint;
13+ i, j, k, kind, n, x, y, z, mode: longint;
14+ b: array[0..63] of byte;
15+
16+function Rnd(n: longint): longint;
17+begin
18+ seed := (seed * 1103515245 + 12345) and $7FFFFFFF;
19+ Rnd := (seed shr 8) mod n;
20+end;
21+
22+var c, e, line, col: longint;
23+begin
24+ seed := 5;
25+ mode := ord(ParamStr(1)[1]) - 48;
26+ for i := 0 to 7 do begin b[0] := 97 + i; names[i] := Intern(@b[0], 1) end;
27+ placesChunk := NewChunk(secRodata, -1, -1);
28+ SetData(placesChunk, @b[0], 0, 8);
29+ for i := 0 to NumC - 1 do begin
30+ if i = 0 then kind := 0 else kind := Rnd(10);
31+ x := Rnd(4); y := Rnd(8);
32+ case kind of
33+ 0..5: begin
34+ c := NewChunk(secText, x - 1, y);
35+ BeginChunk(c);
36+ z := Rnd(3); curFile := names[z];
37+ line := Rnd(300); col := Rnd(60);
38+ NoteLine(line, col);
39+ if i = 0 then begin AddFixup(pc, placesChunk, 0); Put4(0) end;
40+ n := 2 + Rnd(10);
41+ for j := 1 to n do begin
42+ z := Rnd(5);
43+ if z <= 1 then begin
44+ e := Rnd(NumC); y := Rnd(8);
45+ AddFixup(pc, e, y);
46+ Put4(0);
47+ end else if z = 2 then begin
48+ z := Rnd(3); curFile := names[z];
49+ line := Rnd(300); col := Rnd(60);
50+ NoteLine(line, col);
51+ end else begin x := Rnd(1 shl 30); Put4(x); x := Rnd(256); Put1(x) end;
52+ end;
53+ EndChunk(c);
54+ n := Rnd(3);
55+ for j := 1 to n do begin
56+ x := Rnd(8); y := Rnd(200); z := Rnd(6);
57+ NoteVar(c, names[x], y - 100, z);
58+ end;
59+ end;
60+ 6, 7: begin
61+ c := NewChunk(secRodata, x - 1, y);
62+ n := 8 * (1 + Rnd(4));
63+ for j := 0 to n - 1 do b[j] := Rnd(256);
64+ SetData(c, @b[0], n, 8);
65+ for j := 0 to n div 8 - 1 do begin
66+ z := Rnd(2);
67+ if z = 0 then begin e := Rnd(NumC); y := Rnd(8); AddDataFixup(c, j * 8, e, y) end;
68+ end;
69+ end;
70+ 8: begin
71+ c := NewChunk(secBss, x - 1, y);
72+ z := Rnd(200); e := Rnd(4);
73+ SetBss(c, 1 + z, 1 shl e);
74+ end;
75+ 9: begin z := Rnd(8); c := ExternChunk(names[z]) end;
76+ end;
77+ end;
78+ { every chunk a fixup names must exist, and be defined if it is reached }
79+ while numChunks < NumC do begin c := NewChunk(secBss, -1, -1); SetBss(c, 8, 8) end;
80+ for i := 0 to numChunks - 1 do
81+ if chunks^[i].size < 0 then SetBss(i, 8, 8);
82+ mainPath := 'some/main.raz';
83+ if mode = 1 then begin
84+ numNeeded := 2;
85+ needed[0] := names[0]; needed[1] := names[1];
86+ end;
87+ stripped := mode = 2;
88+ if mode = 2 then placesChunk := -1;
89+ MarkLive(1);
90+ WriteElf(ParamStr(2), 1);
91+end.

src/test/LinkDump.raz added +103 -0

@@ -0,0 +1,103 @@
1+(* Makes a program of chunks by a fixed pseudo-random script, links it
2+ and writes it as an executable to the file of the second argument,
3+ in the way the first says (0 static, 1 dynamic, 2 stripped):
4+ src/Link.raz's and src/Elf.raz's side of a test against the seed's,
5+ LinkDump.pas, which writes the same file. *)
6+module LinkDump;
7+import Files, Diag, Scan, Chunk, Link, Elf;
8+
9+const NumC = 200;
10+
11+var seed: I64;
12+
13+proc rnd(n: INT): INT;
14+begin
15+ seed := (seed * 1103515245 + 12345) & 7FFFFFFFH;
16+ return INT((seed shr 8) mod I64(n));
17+end;
18+
19+(* a library that must be taken *)
20+proc ok(taken: BOOL);
21+begin
22+ if not taken then Diag.fatal("too many libraries"); end;
23+end;
24+
25+proc main*;
26+var
27+ names: [8]INT; b: [64]U8; arg: []U8;
28+ i, j, kind, n, x, y, z, c, e, line, col, mode: INT;
29+begin
30+ seed := 5;
31+ arg := Files.arg(1);
32+ mode := INT(arg[0]) - 48;
33+ for i := 0 to 7 do b[0] := U8(97 + i); names[i] := Scan.intern(ADR(b[0]), 1); end;
34+ Link.setPlaces(Chunk.newChunk(Chunk.secRodata, -1, -1));
35+ Chunk.setData(Link.placesChunk, ADR(b[0]), 0, 8);
36+ for i := 0 to NumC - 1 do
37+ if i = 0 then kind := 0; else kind := rnd(10); end;
38+ x := rnd(4); y := rnd(8);
39+ match kind of
40+ | 0..5:
41+ c := Chunk.newChunk(Chunk.secText, x - 1, y);
42+ Chunk.beginChunk(c);
43+ z := rnd(3); Chunk.setCurFile(names[z]);
44+ line := rnd(300); col := rnd(60);
45+ Chunk.noteLine(line, col);
46+ if i = 0 then Chunk.addFixup(Chunk.pc, Link.placesChunk, 0); Chunk.put4(0); end;
47+ n := 2 + rnd(10);
48+ for j := 1 to n do
49+ z := rnd(5);
50+ if z <= 1 then
51+ e := rnd(NumC); y := rnd(8);
52+ Chunk.addFixup(Chunk.pc, e, y);
53+ Chunk.put4(0);
54+ elsif z = 2 then
55+ z := rnd(3); Chunk.setCurFile(names[z]);
56+ line := rnd(300); col := rnd(60);
57+ Chunk.noteLine(line, col);
58+ else
59+ x := rnd(1 shl 30); Chunk.put4(x); x := rnd(256); Chunk.put1(x);
60+ end;
61+ end;
62+ Chunk.endChunk(c);
63+ n := rnd(3);
64+ for j := 1 to n do
65+ x := rnd(8); y := rnd(200); z := rnd(6);
66+ Chunk.noteVar(c, names[x], y - 100, z);
67+ end;
68+ | 6, 7:
69+ c := Chunk.newChunk(Chunk.secRodata, x - 1, y);
70+ n := 8 * (1 + rnd(4));
71+ for j := 0 to n - 1 do b[j] := U8(rnd(256)); end;
72+ Chunk.setData(c, ADR(b[0]), n, 8);
73+ for j := 0 to n div 8 - 1 do
74+ z := rnd(2);
75+ if z = 0 then e := rnd(NumC); y := rnd(8); Chunk.addDataFixup(c, j * 8, e, y); end;
76+ end;
77+ | 8:
78+ c := Chunk.newChunk(Chunk.secBss, x - 1, y);
79+ z := rnd(200); e := rnd(4);
80+ Chunk.setBss(c, 1 + z, 1 shl e);
81+ | else: z := rnd(8); c := Chunk.externChunk(names[z]);
82+ end;
83+ end;
84+ (* every chunk a fixup names must exist, and be defined if it is reached *)
85+ while Chunk.numChunks < NumC do
86+ c := Chunk.newChunk(Chunk.secBss, -1, -1);
87+ Chunk.setBss(c, 8, 8);
88+ end;
89+ for i := 0 to Chunk.numChunks - 1 do
90+ if Chunk.chunks[i].size < 0 then Chunk.setBss(i, 8, 8); end;
91+ end;
92+ Elf.setMainPath("some/main.raz");
93+ if mode = 1 then
94+ ok(Elf.needLib(names[0]));
95+ ok(Elf.needLib(names[1]));
96+ end;
97+ Elf.setStripped(mode = 2);
98+ if mode = 2 then Link.setPlaces(-1); end;
99+ Link.markLive(1);
100+ Elf.writeElf(Files.arg(2), 1);
101+end;
102+
103+end LinkDump.

src/test/Recover.raz (history) added +38 -0

@@ -0,0 +1,38 @@
1+(* Tests going on after an error, as the parser does with try: a driver
2+ reads a file's symbols and reports each name `bad` as an error,
3+ several calls deep; the error comes back up through them, and the
4+ driver reads on from the next symbol. *)
5+module Recover;
6+import Out, Files, Diag, Scan;
7+
8+var failed, names: INT;
9+
10+proc deep(n: INT): ERROR;
11+begin
12+ if n > 0 then
13+ try deep(n - 1);
14+ return nil;
15+ end;
16+ return Scan.mark("a bad name");
17+end;
18+
19+proc main*;
20+var err: ERROR;
21+begin
22+ if LEN(Scan.open(Files.arg(1))) # 0 then Diag.fatal("no file"); end;
23+ while Scan.tok # Scan.sEof do
24+ Scan.next;
25+ if Scan.tok = Scan.sIdent then
26+ INC(names);
27+ if Scan.nameOf(Scan.id) = "bad" then
28+ err := deep(5);
29+ if err # nil then INC(failed); end;
30+ end;
31+ end;
32+ end;
33+ Out.int(names); Out.str(" names, "); Out.int(failed); Out.str(" failed, ");
34+ Out.int(Diag.errors); Out.str(" errors\n");
35+ Diag.finish;
36+end;
37+
38+end Recover.

src/test/ScanBench.pas added +12 -0

@@ -0,0 +1,12 @@
1+{ Counts the symbols of a file and nothing else, for timing scan.pas
2+ against src/Scan.raz (ScanBench.raz). }
3+program scanbench;
4+{$mode objfpc}{$H-}
5+uses diag, scan;
6+var n: longint;
7+begin
8+ if Open(ParamStr(1)) <> '' then Fatal('no file');
9+ n := 0;
10+ repeat Next; inc(n) until tok = sEof;
11+ writeln(n, ' symbols');
12+end.

src/test/ScanBench.raz added +15 -0

@@ -0,0 +1,15 @@
1+(* Counts the symbols of a file and nothing else, for timing Scan.raz
2+ against the seed's scan.pas (ScanBench.pas). *)
3+module ScanBench;
4+import Out, Files, Diag, Scan;
5+
6+proc main*;
7+var n: INT;
8+begin
9+ if LEN(Scan.open(Files.arg(1))) # 0 then Diag.fatal("no file"); end;
10+ n := 0;
11+ repeat Scan.next; INC(n); until Scan.tok = Scan.sEof;
12+ Out.int(n); Out.str(" symbols\n");
13+end;
14+
15+end ScanBench.

src/test/ScanDump.pas added +21 -0

@@ -0,0 +1,21 @@
1+{ Prints the symbols of a file, one per line: the seed's side of a test
2+ of src/Scan.raz, which prints the same. A real is shown by its bits,
3+ so that no formatting library decides what is the same. }
4+program scandump;
5+{$mode objfpc}{$H-}
6+uses diag, scan;
7+var i: longint; bits: int64;
8+begin
9+ if Open(ParamStr(1)) <> '' then Fatal('no file');
10+ repeat
11+ Next;
12+ write(LineOf(TokPos), ':', TokPos.a, ':', TokPos.b, ' ', CurLine, ':', CurCol, ' ', ord(tok));
13+ case tok of
14+ sIdent: write(' ', NameOf(id), ' ', id);
15+ sInt, sChar: write(' ', ival);
16+ sReal: begin Move(rval, bits, 8); write(' ', HexStr(bits, 16)) end;
17+ sString: begin write(' "'); for i := 0 to slen - 1 do write(sbuf[i], ','); write('"') end;
18+ end;
19+ writeln;
20+ until tok = sEof;
21+end.

src/test/ScanDump.raz added +35 -0

@@ -0,0 +1,35 @@
1+(* Prints the symbols of a file, one per line: src/Scan.raz's side of a
2+ test against the seed's, ScanDump.pas, which prints the same. *)
3+module ScanDump;
4+import Out, Fmt, Files, Diag, Scan;
5+
6+proc main*;
7+var p: Diag.Pos; bits: ^U64; i: INT; str: []U8; r: F64;
8+begin
9+ if LEN(Scan.open(Files.arg(1))) # 0 then Diag.fatal("no file"); end;
10+ repeat
11+ Scan.next;
12+ p := Scan.tokPos();
13+ Fmt.print("{}:{}:{} {}:{} {}", [Fmt.int(Diag.lineOf(p)), Fmt.int(p.a), Fmt.int(p.b),
14+ Fmt.int(Scan.curLine()), Fmt.int(Scan.curCol()), Fmt.int(INT(Scan.tok))]);
15+ match Scan.tok of
16+ | sIdent: Fmt.print(" {} {}", [Fmt.str(Scan.nameOf(Scan.id)), Fmt.int(Scan.id)]);
17+ | sInt: Fmt.print(" {}", [Fmt.int(Scan.ival)]);
18+ | sChar: Fmt.print(" {}", [Fmt.int(Scan.ival)]);
19+ | sReal:
20+ r := Scan.rval;
21+ bits := ^U64(ADR(r));
22+ Out.str(" ");
23+ Out.hex(bits^, 16);
24+ | sString:
25+ Out.str(" \"");
26+ str := Scan.strBytes();
27+ for i := 0 to LEN(str) - 1 do Fmt.print("{},", [Fmt.int(INT(str[i]))]); end;
28+ Out.str("\"");
29+ | else:
30+ end;
31+ Out.ln;
32+ until Scan.tok = Scan.sEof;
33+end;
34+
35+end ScanDump.

src/test/SymDump.pas added +185 -0

@@ -0,0 +1,185 @@
1+{ Builds types and objects by a fixed pseudo-random script, asks of them
2+ what the parser asks of sym, and prints the answers: the seed's side
3+ of a test of src/Sym.raz, whose SymDump.raz does the same and prints
4+ the same. With the argument dup or deep it ends in the error of a name
5+ declared twice, or of too many scopes. }
6+program symdump;
7+{$mode objfpc}{$H-}
8+uses diag, scan, sym;
9+const
10+ Words: array[0..19] of string = ('alpha', 'alpho', 'beta', 'bet', 'gamma', 'gama', 'delta', 'Delta',
11+ 'eps', 'zeta', 'eta', 'theta', 'iota', 'kappa', 'lambda', 'mu', 'nu', 'xi', 'omicron', 'pi');
12+var
13+ seed: int64;
14+ names: array[0..19] of longint;
15+ mods: array[0..2] of PModule;
16+ base: array[0..11] of PType;
17+ pool: array[0..299] of PType;
18+ objs: array[0..299] of PObj;
19+ numPool, numObjs, i, k, n, op, x, y, z: longint;
20+ t, o2: PType;
21+ o: PObj;
22+ saved: array[0..MaxDepth - 1] of longint;
23+ d: longint;
24+ v: int64;
25+
26+function Rnd(n: longint): longint;
27+begin
28+ seed := (seed * 1103515245 + 12345) and $7FFFFFFF;
29+ Rnd := (seed shr 8) mod n;
30+end;
31+
32+function Fields(m: longint; allowVar: boolean): PObj;
33+var f, first, last: PObj; j, x, y, z: longint;
34+begin
35+ first := nil; last := nil;
36+ for j := 1 to m do begin
37+ x := Rnd(20); y := Rnd(numPool);
38+ f := NewObj(oField, names[x], pool[y]);
39+ z := Rnd(2); f^.exported := z = 0;
40+ z := Rnd(3); f^.isVar := allowVar and (z = 0);
41+ f^.val := j * 8;
42+ if first = nil then first := f else last^.next := f;
43+ last := f;
44+ end;
45+ Fields := first;
46+end;
47+
48+procedure Add(t: PType);
49+begin
50+ if numPool <= High(pool) then begin pool[numPool] := t; inc(numPool) end;
51+end;
52+
53+procedure MakeType;
54+var t: PType; r, m, x: longint; f: PObj;
55+begin
56+ r := Rnd(11);
57+ case r of
58+ 0: t := NewType(fPtr, 8, 8);
59+ 1: t := NewType(fArray, 0, 1);
60+ 2: t := NewType(fSlice, 16, 8);
61+ 3: t := NewType(fRecord, 0, 8);
62+ 4: t := NewType(fProc, 8, 8);
63+ 5: t := NewType(fSet, 8, 8);
64+ 6: t := NewType(fVariant, 16, 8);
65+ 7: t := NewType(fEnum, 1, 1);
66+ 8: t := NewType(fRecord, 16, 8);
67+ 9: t := NewType(fProc, 8, 8);
68+ else t := NewType(fPtr, 8, 8);
69+ end;
70+ x := Rnd(numPool); t^.base := pool[x];
71+ t^.len := Rnd(5);
72+ x := Rnd(4); t^.vol := x = 0;
73+ x := Rnd(4); t^.variadic := (t^.form = fProc) and (x = 0);
74+ x := Rnd(2); t^.tuple := (t^.form = fRecord) and (x = 0);
75+ if t^.form in [fRecord, fProc, fVariant] then begin
76+ m := Rnd(4);
77+ t^.fields := Fields(m, t^.form = fProc);
78+ t^.len := m;
79+ if t^.form = fRecord then t^.base := nil;
80+ x := Rnd(2);
81+ if (t^.form = fProc) and (x = 0) then t^.base := nil;
82+ if t^.form = fVariant then begin
83+ f := t^.fields;
84+ while f <> nil do begin f^.cls := oCase; x := Rnd(3); f^.fields := Fields(x, false); f := f^.next end;
85+ end;
86+ end;
87+ x := Rnd(3);
88+ if x = 0 then begin
89+ x := Rnd(20); t^.obj := NewObj(oType, names[x], t);
90+ x := Rnd(3); t^.obj^.module := mods[x];
91+ end;
92+ Add(t);
93+end;
94+
95+begin
96+ seed := 11;
97+ for i := 0 to 19 do names[i] := Intern(@Words[i][1], length(Words[i]));
98+ for i := 0 to 2 do begin
99+ New(mods[i]); FillChar(mods[i]^, SizeOf(TModule), 0);
100+ mods[i]^.sname := names[i * 5];
101+ end;
102+ curModule := mods[0];
103+ base[0] := tI8; base[1] := tI16; base[2] := tI32; base[3] := tI64; base[4] := tU8;
104+ base[5] := tU16; base[6] := tU32; base[7] := tU64; base[8] := tBool; base[9] := tF32;
105+ base[10] := tReal; base[11] := tInt;
106+ for i := 0 to 11 do Add(base[i]);
107+ if ParamCount >= 1 then begin if Open('lib/Rt.raz') <> '' then Fatal('no file'); Next; Next end;
108+ numObjs := 0;
109+ for k := 1 to 4000 do begin
110+ op := Rnd(14);
111+ case op of
112+ 0, 1, 2: MakeType;
113+ 3, 4: if numObjs <= High(objs) then begin
114+ x := Rnd(8); y := Rnd(20);
115+ if Find(x, names[y]) = nil then begin
116+ z := Rnd(8); n := Rnd(numPool);
117+ o := NewObj(TClass(z), names[y], pool[n]);
118+ z := Rnd(2); o^.exported := z = 0;
119+ z := Rnd(3); o^.module := mods[z];
120+ Insert(o, x);
121+ objs[numObjs] := o; inc(numObjs);
122+ writeln('I ', x, ' ', NameOf(names[y]), ' ', o^.scope);
123+ end;
124+ end;
125+ 5: begin x := Rnd(8); y := Rnd(20); o := Find(x, names[y]);
126+ write('F ', x, ' ', NameOf(names[y]), ' ');
127+ if o = nil then writeln('-') else writeln(ord(o^.cls), ' ', o^.scope);
128+ end;
129+ 6: begin
130+ x := Rnd(8); y := Rnd(20);
131+ if ScopeDepth < 6 then OpenScope(x);
132+ o := Lookup(names[y]);
133+ write('L ', ScopeDepth, ' ', NameOf(names[y]), ' ');
134+ if o = nil then writeln('-') else writeln(ord(o^.cls), ' ', o^.scope);
135+ z := Rnd(2);
136+ if (ScopeDepth > 1) and (z = 0) then CloseScope;
137+ end;
138+ 7: begin
139+ y := Rnd(20); x := Rnd(9) - 1; z := Rnd(3); curModule := mods[z];
140+ o := Closest(names[y], x);
141+ write('C ', NameOf(names[y]), ' ', x, ' ');
142+ if o = nil then writeln('-') else writeln(NameOf(o^.name), ' ', o^.scope);
143+ end;
144+ 8: begin
145+ x := Rnd(numPool); z := Rnd(3); curModule := mods[z];
146+ writeln('T ', TypeName(pool[x]));
147+ end;
148+ 9: begin
149+ x := Rnd(numPool); y := Rnd(numPool);
150+ writeln('S ', ord(Same(pool[x], pool[y])), ' ', ord(Same(pool[x], pool[x])));
151+ t := NewType(fPtr, 8, 8); t^.base := pool[x];
152+ o2 := t; t := NewType(fPtr, 8, 8); t^.base := pool[x];
153+ writeln('S ', ord(Same(o2, t)));
154+ end;
155+ 10: if numObjs > 0 then begin x := Rnd(numObjs); writeln('P ', HexStr(Fingerprint(objs[x]), 16)) end;
156+ 11: begin
157+ x := Rnd(numPool); y := Rnd(1 shl 20); z := Rnd(2); n := Rnd(2);
158+ v := int64(y) * 4096 * z - y * n;
159+ t := pool[x];
160+ writeln('B ', ord(Fits(v, t)), ' ', ord(IsInt(t)), ' ', ord(IsScalar(t)), ' ', ord(IsAggregate(t)), ' ',
161+ ord(InTwoRegs(t)), ' ', ord(BehindPointer(t)), ' ', AlignUp(y, 1 shl z));
162+ end;
163+ 12: if (ScopeDepth > 1) and (ScopeDepth < 6) then begin
164+ d := ScopeDepth; SaveScopes(d, saved);
165+ writeln('V ', ScopeDepth, ' ', TopScope);
166+ RestoreScopes(d, saved);
167+ writeln('V ', ScopeDepth, ' ', TopScope);
168+ x := NewScope; writeln('N ', x);
169+ end;
170+ 13: begin x := ScopeDepth; if x > 3 then CutScopes(2); writeln('X ', x, ' ', ScopeDepth) end;
171+ end;
172+ end;
173+ { the universe, and the sizes it made }
174+ for i := 0 to 11 do writeln('U ', ord(base[i]^.form), ' ', base[i]^.size, ' ', ord(base[i]^.signed), ' ', NameOf(base[i]^.obj^.name));
175+ if ParamCount >= 1 then begin
176+ if ParamStr(1) = 'dup' then begin
177+ o := NewObj(oVar, names[3], tI8);
178+ Insert(o, 100); Insert(o, 100);
179+ end;
180+ if ParamStr(1) = 'deep' then begin
181+ CutScopes(1);
182+ for i := 1 to MaxDepth + 1 do OpenScope(i);
183+ end;
184+ end;
185+end.

src/test/SymDump.raz added +225 -0

@@ -0,0 +1,225 @@
1+(* Builds types and objects by a fixed pseudo-random script, asks of them
2+ what the parser asks of Sym, and prints the answers: src/Sym.raz's
3+ side of a test against the seed's, SymDump.pas, which prints the same.
4+ With the argument dup or deep it ends in the error of a name declared
5+ twice, or of too many scopes. *)
6+module SymDump;
7+import Out, Fmt, Files, Heap, Diag, Scan, Sym;
8+
9+const
10+ Words: [20][]U8 = ["alpha", "alpho", "beta", "bet", "gamma", "gama", "delta", "Delta",
11+ "eps", "zeta", "eta", "theta", "iota", "kappa", "lambda", "mu", "nu", "xi", "omicron", "pi"];
12+
13+var
14+ seed: I64;
15+ names: [20]INT;
16+ mods: [3]^Sym.Module;
17+ base: [12]^Sym.Type;
18+ pool: [300]^Sym.Type;
19+ objs: [300]^Sym.Obj;
20+ classes: [8]Sym.Class;
21+ numPool, numObjs: INT;
22+
23+proc rnd(n: INT): INT;
24+begin
25+ seed := (seed * 1103515245 + 12345) & 7FFFFFFFH;
26+ return INT((seed shr 8) mod I64(n));
27+end;
28+
29+proc bit(f: BOOL): INT;
30+begin
31+ if f then return 1; end;
32+ return 0;
33+end;
34+
35+proc nm(i: INT): []U8;
36+begin
37+ return Scan.nameOf(names[i]);
38+end;
39+
40+(* The result of a call that must succeed *)
41+proc ok(e: ERROR);
42+begin
43+ if e # nil then Diag.finish; end;
44+end;
45+
46+proc fields(m: INT; allowVar: BOOL): ^Sym.Obj;
47+var f, first, last: ^Sym.Obj; j, x, y, z: INT;
48+begin
49+ first := nil; last := nil;
50+ for j := 1 to m do
51+ x := rnd(20); y := rnd(numPool);
52+ f := Sym.newObj(Sym.oField, names[x], pool[y]);
53+ z := rnd(2); f^.exported := z = 0;
54+ z := rnd(3); f^.isVar := allowVar and (z = 0);
55+ f^.val := j * 8;
56+ if first = nil then first := f; else last^.next := f; end;
57+ last := f;
58+ end;
59+ return first;
60+end;
61+
62+proc add(t: ^Sym.Type);
63+begin
64+ if numPool < 300 then pool[numPool] := t; INC(numPool); end;
65+end;
66+
67+proc makeType;
68+var t: ^Sym.Type; r, m, x: INT; f: ^Sym.Obj;
69+begin
70+ r := rnd(11);
71+ match r of
72+ | 0: t := Sym.newType(Sym.fPtr, 8, 8);
73+ | 1: t := Sym.newType(Sym.fArray, 0, 1);
74+ | 2: t := Sym.newType(Sym.fSlice, 16, 8);
75+ | 3: t := Sym.newType(Sym.fRecord, 0, 8);
76+ | 4: t := Sym.newType(Sym.fProc, 8, 8);
77+ | 5: t := Sym.newType(Sym.fSet, 8, 8);
78+ | 6: t := Sym.newType(Sym.fVariant, 16, 8);
79+ | 7: t := Sym.newType(Sym.fEnum, 1, 1);
80+ | 8: t := Sym.newType(Sym.fRecord, 16, 8);
81+ | 9: t := Sym.newType(Sym.fProc, 8, 8);
82+ | else: t := Sym.newType(Sym.fPtr, 8, 8);
83+ end;
84+ x := rnd(numPool); t^.base := pool[x];
85+ t^.len := rnd(5);
86+ x := rnd(4); t^.vol := x = 0;
87+ x := rnd(4); t^.variadic := (t^.form = Sym.fProc) and (x = 0);
88+ x := rnd(2); t^.tuple := (t^.form = Sym.fRecord) and (x = 0);
89+ if (t^.form = Sym.fRecord) or (t^.form = Sym.fProc) or (t^.form = Sym.fVariant) then
90+ m := rnd(4);
91+ t^.fields := fields(m, t^.form = Sym.fProc);
92+ t^.len := m;
93+ if t^.form = Sym.fRecord then t^.base := nil; end;
94+ x := rnd(2);
95+ if (t^.form = Sym.fProc) and (x = 0) then t^.base := nil; end;
96+ if t^.form = Sym.fVariant then
97+ f := t^.fields;
98+ while f # nil do
99+ f^.cls := Sym.oCase;
100+ x := rnd(3); f^.fields := fields(x, false);
101+ f := f^.next;
102+ end;
103+ end;
104+ end;
105+ x := rnd(3);
106+ if x = 0 then
107+ x := rnd(20); t^.obj := Sym.newObj(Sym.oType, names[x], t);
108+ x := rnd(3); t^.obj^.home := mods[x];
109+ end;
110+ add(t);
111+end;
112+
113+proc main*;
114+var
115+ i, k, op, x, y, z, n, d: INT; t, o2: ^Sym.Type; o: ^Sym.Obj; v: I64;
116+ saved: [Sym.MaxDepth]INT; arg: []U8;
117+begin
118+ seed := 11;
119+ classes := [Sym.oConst, Sym.oType, Sym.oVar, Sym.oProc, Sym.oModule, Sym.oField, Sym.oCase, Sym.oBuiltin];
120+ for i := 0 to 19 do names[i] := Scan.intern(ADR(Words[i][0]), LEN(Words[i])); end;
121+ for i := 0 to 2 do
122+ NEW(mods[i], Heap.heap);
123+ mods[i]^.sname := names[i * 5];
124+ end;
125+ Sym.setCurModule(mods[0]);
126+ base[0] := Sym.tI8; base[1] := Sym.tI16; base[2] := Sym.tI32; base[3] := Sym.tI64; base[4] := Sym.tU8;
127+ base[5] := Sym.tU16; base[6] := Sym.tU32; base[7] := Sym.tU64; base[8] := Sym.tBool; base[9] := Sym.tF32;
128+ base[10] := Sym.tReal; base[11] := Sym.tInt;
129+ for i := 0 to 11 do add(base[i]); end;
130+ arg := "";
131+ if ARGC > 1 then arg := Files.arg(1); end;
132+ if LEN(arg) > 0 then
133+ if LEN(Scan.open("lib/Rt.raz")) # 0 then Diag.fatal("no file"); end;
134+ Scan.next; Scan.next;
135+ end;
136+ numObjs := 0;
137+ for k := 1 to 4000 do
138+ op := rnd(14);
139+ match op of
140+ | 0, 1, 2: makeType;
141+ | 3, 4:
142+ if numObjs < 300 then
143+ x := rnd(8); y := rnd(20);
144+ if Sym.find(x, names[y]) = nil then
145+ z := rnd(8); n := rnd(numPool);
146+ o := Sym.newObj(classes[z], names[y], pool[n]);
147+ z := rnd(2); o^.exported := z = 0;
148+ z := rnd(3); o^.home := mods[z];
149+ ok(Sym.insert(o, x));
150+ objs[numObjs] := o; INC(numObjs);
151+ Fmt.print("I {} {} {}\n", [Fmt.int(x), Fmt.str(nm(y)), Fmt.int(o^.scope)]);
152+ end;
153+ end;
154+ | 5:
155+ x := rnd(8); y := rnd(20); o := Sym.find(x, names[y]);
156+ Fmt.print("F {} {} ", [Fmt.int(x), Fmt.str(nm(y))]);
157+ if o = nil then Out.str("-\n");
158+ else Fmt.print("{} {}\n", [Fmt.int(INT(o^.cls)), Fmt.int(o^.scope)]); end;
159+ | 6:
160+ x := rnd(8); y := rnd(20);
161+ if Sym.scopeDepth() < 6 then ok(Sym.openScope(x)); end;
162+ o := Sym.lookup(names[y]);
163+ Fmt.print("L {} {} ", [Fmt.int(Sym.scopeDepth()), Fmt.str(nm(y))]);
164+ if o = nil then Out.str("-\n");
165+ else Fmt.print("{} {}\n", [Fmt.int(INT(o^.cls)), Fmt.int(o^.scope)]); end;
166+ z := rnd(2);
167+ if (Sym.scopeDepth() > 1) and (z = 0) then Sym.closeScope; end;
168+ | 7:
169+ y := rnd(20); x := rnd(9) - 1; z := rnd(3); Sym.setCurModule(mods[z]);
170+ o := Sym.closest(names[y], x);
171+ Fmt.print("C {} {} ", [Fmt.str(nm(y)), Fmt.int(x)]);
172+ if o = nil then Out.str("-\n");
173+ else Fmt.print("{} {}\n", [Fmt.str(Scan.nameOf(o^.name)), Fmt.int(o^.scope)]); end;
174+ | 8:
175+ x := rnd(numPool); z := rnd(3); Sym.setCurModule(mods[z]);
176+ Fmt.print("T {}\n", [Fmt.str(Sym.typeName(pool[x]))]);
177+ | 9:
178+ x := rnd(numPool); y := rnd(numPool);
179+ Fmt.print("S {} {}\n", [Fmt.int(bit(Sym.same(pool[x], pool[y]))), Fmt.int(bit(Sym.same(pool[x], pool[x])))]);
180+ t := Sym.newType(Sym.fPtr, 8, 8); t^.base := pool[x];
181+ o2 := t; t := Sym.newType(Sym.fPtr, 8, 8); t^.base := pool[x];
182+ Fmt.print("S {}\n", [Fmt.int(bit(Sym.same(o2, t)))]);
183+ | 10:
184+ if numObjs > 0 then
185+ x := rnd(numObjs);
186+ Out.str("P "); Out.hex(Sym.fingerprint(objs[x]), 16); Out.ln;
187+ end;
188+ | 11:
189+ x := rnd(numPool); y := rnd(1 shl 20); z := rnd(2); n := rnd(2);
190+ v := I64(y) * 4096 * I64(z) - I64(y) * I64(n);
191+ t := pool[x];
192+ Fmt.print("B {} {} {} {} {} {} {}\n", [Fmt.int(bit(Sym.fits(v, t))), Fmt.int(bit(Sym.isInt(t))),
193+ Fmt.int(bit(Sym.isScalar(t))), Fmt.int(bit(Sym.isAggregate(t))), Fmt.int(bit(Sym.inTwoRegs(t))),
194+ Fmt.int(bit(Sym.behindPointer(t))), Fmt.int(Sym.alignUp(y, 1 shl z))]);
195+ | 12:
196+ if (Sym.scopeDepth() > 1) and (Sym.scopeDepth() < 6) then
197+ d := Sym.saveScopes(saved);
198+ Fmt.print("V {} {}\n", [Fmt.int(Sym.scopeDepth()), Fmt.int(Sym.topScope())]);
199+ Sym.restoreScopes(d, saved);
200+ Fmt.print("V {} {}\n", [Fmt.int(Sym.scopeDepth()), Fmt.int(Sym.topScope())]);
201+ x := Sym.newScope();
202+ Fmt.print("N {}\n", [Fmt.int(x)]);
203+ end;
204+ | else:
205+ x := Sym.scopeDepth();
206+ if x > 3 then Sym.cutScopes(2); end;
207+ Fmt.print("X {} {}\n", [Fmt.int(x), Fmt.int(Sym.scopeDepth())]);
208+ end;
209+ end;
210+ for i := 0 to 11 do
211+ Fmt.print("U {} {} {} {}\n", [Fmt.int(INT(base[i]^.form)), Fmt.int(base[i]^.size),
212+ Fmt.int(bit(base[i]^.signed)), Fmt.str(Scan.nameOf(base[i]^.obj^.name))]);
213+ end;
214+ if arg = "dup" then
215+ o := Sym.newObj(Sym.oVar, names[3], Sym.tI8);
216+ ok(Sym.insert(o, 100));
217+ ok(Sym.insert(o, 100));
218+ end;
219+ if arg = "deep" then
220+ Sym.cutScopes(1);
221+ for i := 1 to Sym.MaxDepth + 1 do ok(Sym.openScope(i)); end;
222+ end;
223+end;
224+
225+end SymDump.

src/test/X64Dump.pas added +160 -0

@@ -0,0 +1,160 @@
1+{ Writes every instruction the encoder makes, with operands drawn by a
2+ fixed pseudo-random script, then prints the bytes, the fixups and the
3+ listing (raz -S) of what it made: the seed's side of a test of
4+ src/X64.raz, whose X64Dump.raz does the same and prints the same. }
5+program x64dump;
6+{$mode objfpc}{$H-}
7+uses diag, scan, chunk, x64;
8+var
9+ seed: int64;
10+ i, k, op, a, b, c, d, lab1, lab2: longint;
11+ m: TMem;
12+ path: string;
13+
14+function Rnd(n: longint): longint;
15+begin
16+ seed := (seed * 1103515245 + 12345) and $7FFFFFFF;
17+ Rnd := (seed shr 8) mod n;
18+end;
19+
20+{ a register, with the stack and base pointers and the high ones often enough }
21+function Reg: longint;
22+begin
23+ Reg := Rnd(16);
24+end;
25+
26+{ a size of 1, 2, 4 or 8 bytes }
27+function Size: longint;
28+begin
29+ Size := 1 shl Rnd(4);
30+end;
31+
32+{ a value that fits size bytes, of 8 as 32 bits }
33+function Imm(sz: longint): longint;
34+var x: longint;
35+begin
36+ x := Rnd(1 shl 30);
37+ case Rnd(3) of
38+ 0: Imm := x mod 100 - 50;
39+ 1: Imm := x - (1 shl 29);
40+ else Imm := x mod 20000 - 10000;
41+ end;
42+ if sz = 1 then Imm := Imm mod 128
43+ else if sz = 2 then Imm := Imm mod 32768;
44+end;
45+
46+function RandMem: TMem;
47+var kind, base, idx, sc, disp, x: longint;
48+begin
49+ kind := Rnd(6);
50+ base := Reg; idx := Reg; sc := 1 shl Rnd(4); x := Rnd(5);
51+ case x of
52+ 0: disp := 0;
53+ 1: disp := Rnd(250) - 125;
54+ 2: disp := Rnd(1 shl 20) - (1 shl 19);
55+ 3: disp := 127 + Rnd(3) - 1;
56+ else disp := -128 + Rnd(3) - 1;
57+ end;
58+ case kind of
59+ 0, 1: RandMem := Mem(base, disp);
60+ 2: RandMem := MemRip(Rnd(5), disp);
61+ 3, 4: RandMem := MemIdx(base, idx, sc, disp);
62+ else RandMem := Mem(base, 0);
63+ end;
64+end;
65+
66+begin
67+ seed := 3;
68+ path := 'lib/Rt.raz';
69+ if Open(path) <> '' then Fatal('no file');
70+ listing := true;
71+ for i := 0 to 4 do NewChunk(secText, i - 1, i);
72+ curFile := Intern(@path[1], length(path));
73+ BeginChunk(0);
74+ lab1 := NoLabel; lab2 := NoLabel;
75+ for k := 1 to 3000 do begin
76+ if k mod 7 = 0 then begin a := Rnd(300); b := Rnd(60); NoteLine(1 + a, b) end;
77+ op := Rnd(50);
78+ case op of
79+ 0: begin a := Reg; b := Reg; MovRR(a, b) end;
80+ 1: begin
81+ a := Reg; b := Rnd(6); c := Rnd(1 shl 30);
82+ case b of
83+ 0: MovRI(a, 0);
84+ 1: MovRI(a, c);
85+ 2: MovRI(a, -c);
86+ 3: MovRI(a, int64(c) * 8 + 5);
87+ 4: MovRI(a, int64(c) * 4096 * 4096 * 9 - 7);
88+ else MovRI(a, 0);
89+ end;
90+ end;
91+ 2: begin a := Rnd(8); m := RandMem; b := Size; c := Imm(b); AluMI(a, m, c, b) end;
92+ 3: begin m := RandMem; b := Size; c := Imm(b); StoreI(m, c, b) end;
93+ 4: begin a := Reg; m := RandMem; b := Size; c := Rnd(2); Load(a, m, b, c = 0) end;
94+ 5: begin m := RandMem; a := Reg; b := Size; Store(m, a, b) end;
95+ 6: begin a := Reg; m := RandMem; Lea(a, m) end;
96+ 7: begin a := Rnd(8); b := Reg; c := Reg; Alu(a, b, c) end;
97+ 8: begin a := Rnd(8); b := Reg; c := Imm(8); AluI(a, b, c) end;
98+ 9: begin a := Rnd(8); b := Reg; m := RandMem; AluM(a, b, m) end;
99+ 10: begin a := Reg; b := Reg; Imul(a, b) end;
100+ 11: begin a := Reg; c := Imm(8); ImulI(a, c) end;
101+ 12: begin a := Rnd(3); b := Reg; if a = 0 then a := shShl else if a = 1 then a := shShr else a := shSar; Shift(a, b) end;
102+ 13: begin a := Rnd(3); b := Reg; c := Rnd(64); if a = 0 then a := shShl else if a = 1 then a := shShr else a := shSar; ShiftI(a, b, c) end;
103+ 14: begin a := Rnd(4); b := Reg; if a < 2 then a := a + 2 else a := a + 4; Unary(a, b) end;
104+ 15: Cqo;
105+ 16: begin a := Reg; b := 1 shl Rnd(3); c := Rnd(2); Extend(a, b, c = 0) end;
106+ 17: begin a := Rnd(16); b := Reg; SetCC(a, b) end;
107+ 18: begin a := Reg; b := Reg; TestRR(a, b) end;
108+ 19: begin a := Reg; Push(a) end;
109+ 20: begin a := Reg; Pop(a) end;
110+ 21: begin a := Rnd(5); CallChunk(a) end;
111+ 22: begin a := Rnd(1000); CallBack(a) end;
112+ 23: begin a := Reg; CallR(a) end;
113+ 24: begin a := Reg; JmpR(a) end;
114+ 25: begin m := RandMem; CallM(m) end;
115+ 26: begin a := Rnd(5); case a of 0: Ret; 1: Leave; 2: Syscall; 3: Mfence; else Ud2 end end;
116+ 27: begin a := 8 shl Rnd(3); Align(a) end;
117+ 28: begin a := Rnd(5); case a of 0: RepMovsb; 1: Std; 2: Cld; 3: RepStosb; else RepeCmpsb end end;
118+ 29: begin m := RandMem; a := Reg; LockCmpxchg(m, a) end;
119+ 30: begin m := RandMem; a := Reg; Xchg(m, a) end;
120+ 31: begin m := RandMem; a := Reg; LockXadd(m, a) end;
121+ 32: begin a := Reg; b := Reg; MovqXR(a, b) end;
122+ 33: begin a := Reg; b := Reg; MovqRX(a, b) end;
123+ 34: begin a := Reg; b := Reg; MovX(a, b) end;
124+ 35: begin a := Reg; m := RandMem; b := Rnd(2); MovsXM(a, m, b = 0) end;
125+ 36: begin m := RandMem; a := Reg; b := Rnd(2); MovsMX(m, a, b = 0) end;
126+ 37: begin
127+ d := Rnd(5); a := Reg; b := Reg; c := Rnd(2);
128+ case d of 0: d := $58; 1: d := $59; 2: d := $5C; 3: d := $5E; else d := $5A end;
129+ Sse(d, a, b, c = 0);
130+ end;
131+ 38: begin
132+ d := Rnd(5); a := Reg; m := RandMem; c := Rnd(2);
133+ case d of 0: d := $58; 1: d := $59; 2: d := $5C; 3: d := $5E; else d := $5A end;
134+ SseM(d, a, m, c = 0);
135+ end;
136+ 39: begin a := Reg; b := Reg; c := Rnd(2); Ucomis(a, b, c = 0) end;
137+ 40: begin a := Reg; b := Reg; c := Rnd(2); Cvtsi2s(a, b, c = 0) end;
138+ 41: begin a := Reg; b := Reg; c := Rnd(2); Cvtts2si(a, b, c = 0) end;
139+ 42: begin a := Reg; b := Rnd(64); Btc(a, b) end;
140+ 43: begin
141+ a := Rnd(16); b := Rnd(2);
142+ if b = 0 then Jmp(lab1) else Jcc(a, lab2);
143+ end;
144+ 44: begin a := Rnd(16); b := Rnd(2); c := pc - Rnd(200); if b = 0 then JmpBack(c) else JccBack(a, c) end;
145+ 45: if Rnd(3) = 0 then begin FixLink(lab1); lab1 := NoLabel end
146+ else begin FixLinkTo(lab2, pc - 20); lab2 := NoLabel end;
147+ 46: begin Jmp(lab1); DropJumpTo(lab1) end;
148+ 47: begin a := JoinLinks(lab1, lab2); lab1 := a; lab2 := NoLabel end;
149+ else begin a := Rnd(256); Put1(a) end;
150+ end;
151+ end;
152+ FixLink(lab1); FixLink(lab2);
153+ EndChunk(0);
154+ chunks^[0].live := true;
155+ writeln('pc ', pc, ' fixups ', numFixups, ' lines ', numLines, ' said ', SaidCount);
156+ for i := 0 to pc - 1 do write(HexStr(code^[i], 2));
157+ writeln;
158+ for i := 0 to numFixups - 1 do writeln('F ', fixups^[i].at, ' ', fixups^[i].chunk, ' ', fixups^[i].addend);
159+ List(-1);
160+end.

src/test/X64Dump.raz added +208 -0

@@ -0,0 +1,208 @@
1+(* Writes every instruction the encoder makes, with operands drawn by a
2+ fixed pseudo-random script, then prints the bytes, the fixups and the
3+ listing (raz -S) of what it made: src/X64.raz's side of a test
4+ against the seed's, X64Dump.pas, which prints the same. *)
5+module X64Dump;
6+import Out, Fmt, Diag, Scan, Chunk, X64;
7+
8+var seed: I64;
9+
10+proc rnd(n: INT): INT;
11+begin
12+ seed := (seed * 1103515245 + 12345) & 7FFFFFFFH;
13+ return INT((seed shr 8) mod I64(n));
14+end;
15+
16+(* a register *)
17+proc reg: INT;
18+begin
19+ return rnd(16);
20+end;
21+
22+(* a size of 1, 2, 4 or 8 bytes *)
23+proc size: INT;
24+begin
25+ return 1 shl rnd(4);
26+end;
27+
28+(* a value that fits sz bytes, of 8 as 32 bits *)
29+proc imm(sz: INT): INT;
30+var x, r: INT;
31+begin
32+ x := rnd(1 shl 30);
33+ match rnd(3) of
34+ | 0: r := x mod 100 - 50;
35+ | 1: r := x - (1 shl 29);
36+ | else: r := x mod 20000 - 10000;
37+ end;
38+ if sz = 1 then
39+ r := r mod 128;
40+ elsif sz = 2 then
41+ r := r mod 32768;
42+ end;
43+ return r;
44+end;
45+
46+proc randMem: X64.Mem;
47+var kind, base, idx, sc, disp, x: INT;
48+begin
49+ kind := rnd(6);
50+ base := reg(); idx := reg(); sc := 1 shl rnd(4); x := rnd(5);
51+ match x of
52+ | 0: disp := 0;
53+ | 1: disp := rnd(250) - 125;
54+ | 2: disp := rnd(1 shl 20) - (1 shl 19);
55+ | 3: disp := 127 + rnd(3) - 1;
56+ | else: disp := -128 + rnd(3) - 1;
57+ end;
58+ match kind of
59+ | 0, 1: return X64.mem(base, disp);
60+ | 2: return X64.memRip(rnd(5), disp);
61+ | 3, 4: return X64.memIdx(base, idx, sc, disp);
62+ | else: return X64.mem(base, 0);
63+ end;
64+end;
65+
66+proc main*;
67+var
68+ i, k, op, a, b, c, d, lab1, lab2: INT; m: X64.Mem; path: []U8;
69+begin
70+ seed := 3;
71+ path := "lib/Rt.raz";
72+ if LEN(Scan.open(path)) # 0 then Diag.fatal("no file"); end;
73+ X64.setListing(true);
74+ for i := 0 to 4 do c := Chunk.newChunk(Chunk.secText, i - 1, i); end;
75+ Chunk.setCurFile(Scan.intern(ADR(path[0]), LEN(path)));
76+ Chunk.beginChunk(0);
77+ lab1 := X64.NoLabel; lab2 := X64.NoLabel;
78+ for k := 1 to 3000 do
79+ if k mod 7 = 0 then a := rnd(300); b := rnd(60); Chunk.noteLine(1 + a, b); end;
80+ op := rnd(50);
81+ match op of
82+ | 0: a := reg(); b := reg(); X64.movRR(a, b);
83+ | 1:
84+ a := reg(); b := rnd(6); c := rnd(1 shl 30);
85+ match b of
86+ | 0: X64.movRI(a, 0);
87+ | 1: X64.movRI(a, c);
88+ | 2: X64.movRI(a, -c);
89+ | 3: X64.movRI(a, I64(c) * 8 + 5);
90+ | 4: X64.movRI(a, I64(c) * 4096 * 4096 * 9 - 7);
91+ | else: X64.movRI(a, 0);
92+ end;
93+ | 2: a := rnd(8); m := randMem(); b := size(); c := imm(b); X64.aluMI(a, m, c, b);
94+ | 3: m := randMem(); b := size(); c := imm(b); X64.storeI(m, c, b);
95+ | 4: a := reg(); m := randMem(); b := size(); c := rnd(2); X64.load(a, m, b, c = 0);
96+ | 5: m := randMem(); a := reg(); b := size(); X64.store(m, a, b);
97+ | 6: a := reg(); m := randMem(); X64.lea(a, m);
98+ | 7: a := rnd(8); b := reg(); c := reg(); X64.alu(a, b, c);
99+ | 8: a := rnd(8); b := reg(); c := imm(8); X64.aluI(a, b, c);
100+ | 9: a := rnd(8); b := reg(); m := randMem(); X64.aluM(a, b, m);
101+ | 10: a := reg(); b := reg(); X64.imul(a, b);
102+ | 11: a := reg(); c := imm(8); X64.imulI(a, c);
103+ | 12:
104+ a := rnd(3); b := reg();
105+ if a = 0 then a := X64.shShl; elsif a = 1 then a := X64.shShr; else a := X64.shSar; end;
106+ X64.shift(a, b);
107+ | 13:
108+ a := rnd(3); b := reg(); c := rnd(64);
109+ if a = 0 then a := X64.shShl; elsif a = 1 then a := X64.shShr; else a := X64.shSar; end;
110+ X64.shiftI(a, b, c);
111+ | 14:
112+ a := rnd(4); b := reg();
113+ if a < 2 then a := a + 2; else a := a + 4; end;
114+ X64.unary(a, b);
115+ | 15: X64.cqo;
116+ | 16: a := reg(); b := 1 shl rnd(3); c := rnd(2); X64.extend(a, b, c = 0);
117+ | 17: a := rnd(16); b := reg(); X64.setCC(a, b);
118+ | 18: a := reg(); b := reg(); X64.testRR(a, b);
119+ | 19: a := reg(); X64.push(a);
120+ | 20: a := reg(); X64.pop(a);
121+ | 21: a := rnd(5); X64.callChunk(a);
122+ | 22: a := rnd(1000); X64.callBack(a);
123+ | 23: a := reg(); X64.callR(a);
124+ | 24: a := reg(); X64.jmpR(a);
125+ | 25: m := randMem(); X64.callM(m);
126+ | 26:
127+ a := rnd(5);
128+ match a of
129+ | 0: X64.ret;
130+ | 1: X64.leave;
131+ | 2: X64.syscall;
132+ | 3: X64.mfence;
133+ | else: X64.ud2;
134+ end;
135+ | 27: a := 8 shl rnd(3); X64.align(a);
136+ | 28:
137+ a := rnd(5);
138+ match a of
139+ | 0: X64.repMovsb;
140+ | 1: X64.std;
141+ | 2: X64.cld;
142+ | 3: X64.repStosb;
143+ | else: X64.repeCmpsb;
144+ end;
145+ | 29: m := randMem(); a := reg(); X64.lockCmpxchg(m, a);
146+ | 30: m := randMem(); a := reg(); X64.xchg(m, a);
147+ | 31: m := randMem(); a := reg(); X64.lockXadd(m, a);
148+ | 32: a := reg(); b := reg(); X64.movqXR(a, b);
149+ | 33: a := reg(); b := reg(); X64.movqRX(a, b);
150+ | 34: a := reg(); b := reg(); X64.movX(a, b);
151+ | 35: a := reg(); m := randMem(); b := rnd(2); X64.movsXM(a, m, b = 0);
152+ | 36: m := randMem(); a := reg(); b := rnd(2); X64.movsMX(m, a, b = 0);
153+ | 37:
154+ d := rnd(5); a := reg(); b := reg(); c := rnd(2);
155+ match d of
156+ | 0: d := 58H;
157+ | 1: d := 59H;
158+ | 2: d := 5CH;
159+ | 3: d := 5EH;
160+ | else: d := 5AH;
161+ end;
162+ X64.sse(d, a, b, c = 0);
163+ | 38:
164+ d := rnd(5); a := reg(); m := randMem(); c := rnd(2);
165+ match d of
166+ | 0: d := 58H;
167+ | 1: d := 59H;
168+ | 2: d := 5CH;
169+ | 3: d := 5EH;
170+ | else: d := 5AH;
171+ end;
172+ X64.sseM(d, a, m, c = 0);
173+ | 39: a := reg(); b := reg(); c := rnd(2); X64.ucomis(a, b, c = 0);
174+ | 40: a := reg(); b := reg(); c := rnd(2); X64.cvtsi2s(a, b, c = 0);
175+ | 41: a := reg(); b := reg(); c := rnd(2); X64.cvtts2si(a, b, c = 0);
176+ | 42: a := reg(); b := rnd(64); X64.btc(a, b);
177+ | 43:
178+ a := rnd(16); b := rnd(2);
179+ if b = 0 then X64.jmp(lab1); else X64.jcc(a, lab2); end;
180+ | 44:
181+ a := rnd(16); b := rnd(2); c := Chunk.pc - rnd(200);
182+ if b = 0 then X64.jmpBack(c); else X64.jccBack(a, c); end;
183+ | 45:
184+ a := rnd(3);
185+ if a = 0 then
186+ X64.fixLink(lab1); lab1 := X64.NoLabel;
187+ else
188+ X64.fixLinkTo(lab2, Chunk.pc - 20); lab2 := X64.NoLabel;
189+ end;
190+ | 46: X64.jmp(lab1); X64.dropJumpTo(lab1);
191+ | 47: a := X64.joinLinks(lab1, lab2); lab1 := a; lab2 := X64.NoLabel;
192+ | else: a := rnd(256); Chunk.put1(a);
193+ end;
194+ end;
195+ X64.fixLink(lab1); X64.fixLink(lab2);
196+ Chunk.endChunk(0);
197+ Chunk.setLive(0);
198+ Fmt.print("pc {} fixups {} lines {} said {}\n", [Fmt.int(Chunk.pc), Fmt.int(Chunk.numFixups),
199+ Fmt.int(Chunk.numLines), Fmt.int(X64.saidCount())]);
200+ for i := 0 to Chunk.pc - 1 do Out.hex(U64(Chunk.text[i]), 2); end;
201+ Out.ln;
202+ for i := 0 to Chunk.numFixups - 1 do
203+ Fmt.print("F {} {} {}\n", [Fmt.int(Chunk.fixups[i].at), Fmt.int(Chunk.fixups[i].chunk), Fmt.int(Chunk.fixups[i].addend)]);
204+ end;
205+ X64.list(-1);
206+end;
207+
208+end X64Dump.

src/test/genasm.py added +244 -0

@@ -0,0 +1,244 @@
1+#!/usr/bin/env python3
2+"""Writes the files the assembler of X64 is tested on, into the directory
3+given: valid.raz, a long run of instructions of every kind the assembler
4+knows, and one small file for each error it reports. Each ends in `end`,
5+as a code procedure's body does. Fixed seed: the same files each run."""
6+import random, sys, os
7+
8+random.seed(7)
9+out = sys.argv[1]
10+os.makedirs(out, exist_ok=True)
11+
12+R64 = "rax rcx rdx rbx rsp rbp rsi rdi r8 r9 r10 r11 r12 r13 r14 r15".split()
13+R32 = "eax ecx edx ebx esp ebp esi edi r8d r9d r10d r11d r12d r13d r14d r15d".split()
14+R16 = "ax cx dx bx sp bp si di r8w r9w r10w r11w r12w r13w r14w r15w".split()
15+R8 = "al cl dl bl spl bpl sil dil r8b r9b r10b r11b r12b r13b r14b r15b".split()
16+BY = {8: R64, 4: R32, 2: R16, 1: R8}
17+PRE = {8: "qword ", 4: "dword ", 2: "word ", 1: "byte "}
18+XM = ["xmm%d" % i for i in range(16)]
19+CC = "o no b ae e ne be a s ns p np l ge le g c nae nc nb z nz na nbe nge nl ng nle".split()
20+
21+
22+def reg(size=8):
23+ return random.choice(BY[size])
24+
25+
26+def mem(size=0):
27+ k = random.randrange(8)
28+ b = random.choice(R64)
29+ i = random.choice([r for r in R64 if r != "rsp"])
30+ d = random.choice([0, 8, -8, 127, -128, 128, 4096, -4096, 100000])
31+ s = random.choice([1, 2, 4, 8])
32+ p = PRE[size] if size else ""
33+ if k == 0:
34+ t = "[%s]" % b
35+ elif k == 1:
36+ t = "[%s + %d]" % (b, abs(d)) if d >= 0 else "[%s - %d]" % (b, -d)
37+ elif k == 2:
38+ t = "[%s + %s * %d]" % (b, i, s)
39+ elif k == 3:
40+ t = "[%s + %s * %d + %d]" % (b, i, s, abs(d)) if d >= 0 else "[%s + %s * %d - %d]" % (b, i, s, -d)
41+ elif k == 4:
42+ t = "[%s + %s]" % (b, i)
43+ elif k == 5:
44+ t = "[%s + 0]" % b
45+ elif k == 6:
46+ t = "[rsp + %d]" % abs(d)
47+ else:
48+ t = "[%s - %d]" % (b, abs(d) + 1)
49+ return p + t
50+
51+
52+def imm(size):
53+ if size == 1:
54+ return str(random.choice([0, 1, -1, 127, 255, -128, 77]))
55+ if size == 2:
56+ return str(random.choice([0, 1, -1, 300, 32767, -32768, 255, 65535]))
57+ return str(random.choice([0, 1, -1, 127, 128, -128, -129, 100000, -100000, 2147483647, -2147483648, 4294967295]))
58+
59+
60+def size():
61+ return random.choice([1, 2, 4, 8])
62+
63+
64+lines = []
65+
66+
67+def emit(s):
68+ lines.append(" " + s + ";")
69+
70+
71+for n in range(900):
72+ k = random.randrange(40)
73+ sz = size()
74+ if k < 6:
75+ op = random.choice("add or adc sbb and sub xor cmp".split())
76+ f = random.randrange(5)
77+ if f == 0:
78+ emit("%s %s, %s" % (op, reg(sz), reg(sz)))
79+ elif f == 1:
80+ emit("%s %s, %s" % (op, reg(sz), mem(sz if random.random() < .5 else 0)))
81+ elif f == 2:
82+ emit("%s %s, %s" % (op, mem(sz if random.random() < .5 else 0), reg(sz)))
83+ elif f == 3:
84+ emit("%s %s, %s" % (op, reg(sz), imm(sz)))
85+ else:
86+ emit("%s %s, %s" % (op, mem(sz), imm(sz)))
87+ elif k < 10:
88+ f = random.randrange(5)
89+ if f == 0:
90+ emit("mov %s, %s" % (reg(sz), reg(sz)))
91+ elif f == 1:
92+ emit("mov %s, %s" % (reg(sz), mem()))
93+ elif f == 2:
94+ emit("mov %s, %s" % (mem(), reg(sz)))
95+ elif f == 3:
96+ v = random.choice([0, 5, -5, 2147483647, 4294967295, 4294967296, -2147483649, 123456789012345])
97+ emit("mov %s, %d" % (reg(8 if sz >= 4 else sz) if sz >= 4 else reg(sz), v if sz == 8 else (v % 65536 if sz == 2 else v % 256 if sz == 1 else v % 4294967296)))
98+ else:
99+ emit("mov %s, %s" % (mem(sz), imm(sz)))
100+ elif k == 10:
101+ emit("test %s, %s" % (reg(sz), random.choice([reg(sz), imm(sz) if sz != 1 else "1"])))
102+ elif k == 11:
103+ emit("xchg %s, %s" % (random.choice([reg(sz), mem()]), reg(sz)))
104+ elif k == 12:
105+ emit("%slock %s %s, %s" % ("", random.choice(["cmpxchg", "xadd"]), mem(), reg(sz)))
106+ elif k == 13:
107+ emit("lea %s, %s" % (reg(random.choice([2, 4, 8])), mem()))
108+ elif k == 14:
109+ op = random.choice(["movzx", "movsx"])
110+ emit("%s %s, %s" % (op, reg(random.choice([2, 4, 8])), random.choice([mem(random.choice([1, 2])), reg(random.choice([1, 2]))])))
111+ elif k == 15:
112+ emit("movsxd %s, %s" % (reg(8), random.choice([mem(4), reg(4)])))
113+ elif k == 16:
114+ emit("%s %s" % (random.choice("not neg mul imul div idiv inc dec".split()), random.choice([reg(sz), mem(sz)])))
115+ elif k == 17:
116+ emit("imul %s" % ", ".join([reg(sz if sz > 1 else 4), random.choice([reg(sz if sz > 1 else 4)] * 1 + [mem()])] + ([imm(sz if sz > 1 else 4)] if random.random() < .4 else [])).replace("%", "%"))
117+ elif k == 18:
118+ op = random.choice("rol ror rcl rcr shl shr sal sar".split())
119+ emit("%s %s, %s" % (op, random.choice([reg(sz), mem(sz)]), random.choice([str(random.randrange(64)), "cl"])))
120+ elif k == 19:
121+ emit("%s %s" % (random.choice(["push", "pop"]), reg(8)))
122+ elif k == 20:
123+ op = random.choice(["call", "jmp"])
124+ emit("%s %s" % (op, random.choice([reg(8), mem()]) if op == "call" else mem()))
125+ elif k == 21:
126+ emit("set%s %s" % (random.choice(CC), random.choice([reg(1), mem(1)])))
127+ elif k == 22:
128+ emit("cmov%s %s, %s" % (random.choice(CC), reg(random.choice([2, 4, 8])), random.choice([reg(8), mem()])))
129+ elif k == 23:
130+ op = random.choice("sqrt add mul sub min div max".split()) + random.choice(["sd", "ss"])
131+ emit("%s %s, %s" % (op, random.choice(XM), random.choice([random.choice(XM), mem()])))
132+ elif k == 24:
133+ op = random.choice("punpcklbw punpcklwd pcmpeqb pand pandn por pxor paddb psubb".split())
134+ emit("%s %s, %s" % (op, random.choice(XM), random.choice([random.choice(XM), mem()])))
135+ elif k == 25:
136+ emit("pshufd %s, %s, %d" % (random.choice(XM), random.choice([random.choice(XM), mem()]), random.randrange(256)))
137+ elif k == 26:
138+ op = random.choice(["movdqu", "movdqa"])
139+ if random.random() < .5:
140+ emit("%s %s, %s" % (op, random.choice(XM), random.choice([random.choice(XM), mem()])))
141+ else:
142+ emit("%s %s, %s" % (op, mem(), random.choice(XM)))
143+ elif k == 27:
144+ emit("pmovmskb %s, %s" % (reg(4), random.choice(XM)))
145+ elif k == 28:
146+ emit("%s %s, %s" % (random.choice("bsf bsr tzcnt lzcnt popcnt".split()), reg(random.choice([4, 8])), random.choice([reg(8), mem()])))
147+ elif k == 29:
148+ op = random.choice(["movsd", "movss"])
149+ if random.random() < .5:
150+ emit("%s %s, %s" % (op, random.choice(XM), random.choice([random.choice(XM), mem()])))
151+ else:
152+ emit("%s %s, %s" % (op, mem(), random.choice(XM)))
153+ elif k == 30:
154+ op = random.choice(["movq", "movd"])
155+ if random.random() < .5:
156+ emit("%s %s, %s" % (op, random.choice(XM), random.choice([reg(8), mem()])))
157+ else:
158+ emit("%s %s, %s" % (op, random.choice([reg(8), mem()]), random.choice(XM)))
159+ elif k == 31:
160+ emit("%s %s, %s" % (random.choice(["ucomisd", "ucomiss"]), random.choice(XM), random.choice([random.choice(XM), mem()])))
161+ elif k == 32:
162+ emit("%s %s, %s" % (random.choice(["cvtsi2sd", "cvtsi2ss"]), random.choice(XM), random.choice([reg(random.choice([4, 8])), mem(random.choice([4, 8]))])))
163+ elif k == 33:
164+ emit("%s %s, %s" % (random.choice(["cvttsd2si", "cvttss2si"]), reg(random.choice([4, 8])), random.choice([random.choice(XM), mem()])))
165+ elif k == 34:
166+ emit("%s %s, %s" % (random.choice(["cvtsd2ss", "cvtss2sd"]), random.choice(XM), random.choice([random.choice(XM), mem()])))
167+ elif k == 35:
168+ emit(random.choice("ret leave syscall cpuid rdtsc pause nop ud2 int3 hlt cqo cdq mfence lfence sfence".split()))
169+ elif k == 36:
170+ emit("db " + ", ".join(str(random.choice([0, 1, 255, 128, 77, -1, -128])) for _ in range(random.randrange(1, 6))))
171+ elif k == 37:
172+ lines.append(" L%d:" % n)
173+ lines.append(" add rax, 1;")
174+ lines.append(" j%s L%d;" % (random.choice(CC), n))
175+ lines.append(" jmp L%d;" % n)
176+ elif k == 38:
177+ lines.append(" jmp F%d;" % n)
178+ lines.append(" nop;")
179+ lines.append(" j%s F%d;" % (random.choice(CC), n))
180+ lines.append(" F%d:" % n)
181+ else:
182+ emit("lock add %s, %s" % (mem(sz), reg(sz)))
183+
184+open(os.path.join(out, "valid.raz"), "w").write("\n".join(lines) + "\n end\n")
185+
186+errors = {
187+ "empty": "",
188+ "badop": "foo rax;",
189+ "noinsn": "42;",
190+ "nosemi": "nop",
191+ "undefined": "jmp nowhere;",
192+ "twice": "a: nop; a: nop;",
193+ "toomany": "add rax, rbx, rcx, rdx;",
194+ "movimm": "mov 1, 2;",
195+ "movmm": "mov [rax], [rbx];",
196+ "addimm": "add 1, rax;",
197+ "pushmem": "push [rax];",
198+ "pushsmall": "push eax;",
199+ "badmem": "mov rax, [rsi * 4];",
200+ "badscale": "mov rax, [rsi + rdi * 3];",
201+ "nomem": "mov rax, [];",
202+ "unclosed": "mov rax, [rbx;",
203+ "shiftcl": "shl rax, dl;",
204+ "shiftimm": "shl 3, 1;",
205+ "lea": "lea rax, rbx;",
206+ "movzx": "movzx rax, rbx;",
207+ "movzx4": "movzx rax, dword [rbx];",
208+ "setsize": "sete rax;",
209+ "cmovimm": "cmove rax, 5;",
210+ "sse": "addsd rax, xmm1;",
211+ "sse1": "addsd xmm1;",
212+ "pshufd": "pshufd xmm1, xmm2;",
213+ "pand3": "pand xmm1, xmm2, 3;",
214+ "movdq": "movdqu rax, xmm1;",
215+ "pmov": "pmovmskb xmm1, rax;",
216+ "bits": "popcnt ax, bx;",
217+ "movsd": "movsd rax, xmm1;",
218+ "movq": "movq rax, rbx;",
219+ "ucomi": "ucomisd rax, xmm1;",
220+ "cvtsi": "cvtsi2sd rax, xmm1;",
221+ "cvtt": "cvttsd2si xmm1, xmm2;",
222+ "cvtss": "cvtss2sd rax, xmm1;",
223+ "plainops": "ret rax;",
224+ "dbrange": "db 256;",
225+ "dbneg": "db -129;",
226+ "imul1": "imul rax, 5;",
227+ "imulmem": "imul [rax], rbx;",
228+ "unary2": "not rax, rbx;",
229+ "unaryimm": "neg 5;",
230+ "inc": "inc 5;",
231+ "xchgimm": "xchg rax, 5;",
232+ "cmpxchg": "cmpxchg rax, 5;",
233+ "calli": "call 5;",
234+ "jmpimm": "jmp 5;",
235+ "labels65": "".join("l%d: nop; " % i for i in range(65)),
236+ "xmm16": "addsd xmm16, xmm1;",
237+ "noend": None,
238+}
239+for name, body in errors.items():
240+ if body is None:
241+ text = " nop;\n"
242+ else:
243+ text = " " + body + "\n end\n"
244+ open(os.path.join(out, "err_%s.raz" % name), "w").write(text)

src/test/genlex.py added +29 -0

@@ -0,0 +1,29 @@
1+# Writes into the directory given a file for each message the scanner
2+# makes, with the places diag shows them in: after a tab, in a long
3+# line, after characters of several bytes, in a CRLF file.
4+import sys
5+d = sys.argv[1]
6+cases = {
7+ "slip1": "x == y;\n", "slip2": "a && b;\n", "slip3": "a || b;\n", "slip4": "a != b;\n", "slip5": "!a;\n",
8+ "str": "x := \"abc\n", "chr": "x := 'a\n", "chr2": "x := 'ab';\n", "chr3": "x := '';\n",
9+ "esc": "x := \"\\q\";\n", "esc2": "x := 'a\\x41';\n", "esc3": "x := \"\\x4\";\n",
10+ "esc4": "x := \"\\u41\";\n", "esc5": "x := \"\\u{110000}\";\n", "esc6": "x := \"\\u{D800}\";\n",
11+ "esc7": "x := \"\\u{1234567}\";\n", "esc8": "x := \"\\u{}\";\n", "esc9": "x := \"\\u{41\";\n",
12+ "esc10": "x := \"\\u{1F600}\\u{e9}\\x00\\xff\\n\\t\\r\\0\\\\\\'\\\"\";\n",
13+ "cmt": "x := 1; (* open (* nested *)\n", "nul": "x := 1;\0 y;\n", "hexbad": "x := 12AB;\n",
14+ "hexbig": "x := 1FFFFFFFFFFFFFFFFH;\n", "hexok": "x := 0FFFFFFFFFFFFFFFFH; y := 7FFFFFFFFFFFFFFFH;\n",
15+ "decbig": "x := 9223372036854775808;\n", "decmax": "x := 9223372036854775807;\n",
16+ "realhex": "x := 1A.5;\n", "realexp": "x := 1.5E;\n", "realexp2": "x := 1.5E+;\n", "realbig": "x := 1.0E309;\n",
17+ "realmax": "x := 1.7976931348623159E308;\n", "reallong": "x := " + "1" * 254 + ".5;\n",
18+ "digname": "x := 12abc;\n", "uni": "x := \u00e9;\n", "badutf": b"x := \"a\xc3(\";\n", "badutf2": b"x := \"\xed\xa0\x80\";\n",
19+ "badutf3": b"x := \"\xc0\x80\";\n", "badutf4": b"x := \"\xf5\x80\x80\x80\";\n", "badutf5": b"x := \"\xe2\x82\";\n",
20+ "okutf": "x := \"h\u00e9llo \u20ac \U0001F600\"; y := '\u00e9'; (* \u00e9 *)\n",
21+ "unexp": "x := @;\n", "long": "x := " + "a + " * 60 + "@;\n", "longmid": "x := " + "a + " * 40 + "@ " + "+ b" * 40 + ";\n",
22+ "tab": "\t\tx := @;\n", "multi": "x := \"\u00e9\u00e9\u00e9\" + @;\n", "ident64": "x" * 64 + ";\n", "ident63": "x" * 63 + ";\n",
23+ "bigstr": "x := \"" + "a" * 70000 + "\";\n", "empty": "", "nonl": "x := y",
24+ "ops": "+ - * / = # < <= > >= := : ; , . .. ... ( ) [ ] { } ^ & ~ | _ __ _a\n",
25+ "words": "and begin break by code const defer div do else elsif end extern for forward if import in link match mod module not of or packed proc record repeat return set shl shr then to try type until var variant VOLATILE while xor Volatile\n",
26+}
27+for k, v in cases.items():
28+ open(f"{d}/{k}.raz", "wb").write(v.encode("utf-8", "surrogateescape") if isinstance(v, str) else v)
29+open(f"{d}/crlf.raz", "wb").write(b"x := 1;\r\ny := @;\r\n")

src/test/genreals.py added +19 -0

@@ -0,0 +1,19 @@
1+# Prints a raz module of reals that are hard to read exactly: the
2+# extremes, halves between neighbours, and many random ones.
3+import random
4+random.seed(7)
5+v = ["0.0", "1.0", "0.1", "4.9E-324", "2.4703282292062327E-324", "2.4703282292062328E-324",
6+ "2.2250738585072014E-308", "2.2250738585072011E-308", "1.7976931348623157E308",
7+ "9007199254740993.0", "9007199254740992.5", "9007199254740993.5", "0.000001E+3",
8+ "123456789012345678901234567890.0E-10", "1.0E-400", "0.5E1", "5.0E-1"]
9+for _ in range(3000):
10+ d = random.randint(1, 10 ** random.randint(1, 30))
11+ e = random.randint(-320, 300)
12+ s = str(d)
13+ v.append(s[0] + "." + (s[1:] or "0") + "E" + ("%+d" % e if random.random() < .5 else str(e)))
14+for _ in range(500):
15+ v.append("%d.%d" % (random.randint(0, 10 ** 6), random.randint(0, 10 ** 12)))
16+print("module Reals;\nvar x: F64;\nbegin")
17+for s in v:
18+ print(" x := " + s + ";")
19+print("end Reals.")

src/x64.pas deleted +0 -1208

@@ -1,1208 +0,0 @@
1-{ x64.pas: machine code for x86-64.
2-
3- The encoder writes the instructions the code generator needs, and
4- no others, into the text of chunk.pas. Registers are numbered as the
5- hardware numbers them. Jumps within a procedure are patched here, as
6- soon as their target is known.
7-
8- Depends on: scan, for errors; chunk, for the code buffer and fixups.
9- Leaves out: choosing instructions; that is gen.pas. }
10-
11-unit x64;
12-
13-{$mode objfpc}{$H-}
14-
15-interface
16-
17-uses scan, diag, chunk;
18-
19-const
20- 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; R12 = 12; R13 = 13; R14 = 14; R15 = 15;
22- RIP = -1; { a base meaning rip-relative, to a chunk }
23- NoIndex = -1;
24-
25- { condition codes }
26- ccB = 2; ccAE = 3; ccE = 4; ccNE = 5; ccBE = 6; ccA = 7; ccS = 8;
27- ccP = 10; ccNP = 11; ccL = 12; ccGE = 13; ccLE = 14; ccG = 15;
28-
29- { group 1 operations, the /digit of 81 and 83 }
30- aluAdd = 0; aluOr = 1; aluAnd = 4; aluSub = 5; aluXor = 6; aluCmp = 7;
31-
32- { the /digit of D3 and C1 }
33- shShl = 4; shShr = 5; shSar = 7;
34-
35- NoLabel = -1;
36-
37-type
38- TMem = record
39- base: longint; { a register, or RIP }
40- index: longint; { a register, or NoIndex }
41- scale: longint; { 1, 2, 4 or 8 }
42- disp: longint;
43- chunk: longint; { with RIP: the chunk addressed }
44- end;
45-
46-var
47- listing: boolean; { -S: each instruction's text is kept, for List }
48-
49-function Here: TMem;
50-function Mem(base: longint; disp: int64): TMem;
51-function MemRip(chunk: longint; disp: longint): TMem;
52-function MemIdx(base, index, scale: longint; disp: int64): TMem;
53-
54-procedure MovRR(dst, src: longint);
55-procedure MovRI(r: longint; v: int64);
56-procedure Load(r: longint; const m: TMem; size: longint; signed: boolean);
57-procedure Store(const m: TMem; r: longint; size: longint);
58-procedure Lea(r: longint; const m: TMem);
59-procedure Alu(op, dst, src: longint);
60-procedure AluI(op, r: longint; v: longint);
61-procedure AluM(op, r: longint; const m: TMem);
62-procedure AluMI(op: longint; m: TMem; v, size: longint);
63-procedure StoreI(m: TMem; v, size: longint);
64-procedure Imul(dst, src: longint);
65-procedure ImulI(r: longint; v: longint);
66-procedure Shift(op, r: longint);
67-procedure ShiftI(op, r, n: longint);
68-procedure Unary(ext, r: longint); { F7 /ext: 2 not, 3 neg, 6 div, 7 idiv }
69-procedure Cqo;
70-procedure Extend(r, size: longint; signed: boolean);
71-procedure SetCC(cc, r: longint);
72-procedure TestRR(a, b: longint);
73-procedure Push(r: longint);
74-procedure Pop(r: longint);
75-procedure CallChunk(c: longint);
76-procedure CallBack(target: longint);
77-procedure CallR(r: longint);
78-procedure JmpR(r: longint);
79-procedure CallM(const m: TMem);
80-procedure Ret;
81-procedure Leave;
82-procedure Syscall;
83-procedure Mfence;
84-procedure Ud2;
85-procedure Align(n: longint);
86-procedure RepMovsb;
87-procedure Std;
88-procedure Cld;
89-procedure RepStosb;
90-procedure RepeCmpsb;
91-procedure LockCmpxchg(const m: TMem; r: longint);
92-procedure Xchg(const m: TMem; r: longint);
93-procedure LockXadd(const m: TMem; r: longint);
94-procedure MovqXR(x, r: longint);
95-procedure MovqRX(r, x: longint);
96-procedure MovX(x, y: longint);
97-{ The real instructions take single: F32 (ss) rather than F64 (sd) }
98-procedure MovsXM(x: longint; const m: TMem; single: boolean);
99-procedure MovsMX(const m: TMem; x: longint; single: boolean);
100-procedure Sse(op, x, y: longint; single: boolean); { 58 add, 59 mul, 5C sub, 5E div, 5A convert }
101-procedure SseM(op, x: longint; const m: TMem; single: boolean);
102-procedure Ucomis(x, y: longint; single: boolean);
103-procedure Cvtsi2s(x, r: longint; single: boolean);
104-procedure Cvtts2si(r, x: longint; single: boolean);
105-procedure Btc(r, bit: longint);
106-
107-procedure Jmp(var L: longint);
108-procedure Jcc(cc: longint; var L: longint);
109-procedure JmpBack(target: longint);
110-procedure JccBack(cc, target: longint);
111-procedure FixLink(L: longint);
112-procedure DropJumpTo(var L: longint);
113-procedure FixLinkTo(L, target: longint);
114-function JoinLinks(L1, L2: longint): longint;
115-
116-type
117- { The parser's reader of an integer constant in a code procedure: a
118- whole expression, or, when whole is false, a single factor }
119- TConstFn = function(whole: boolean): int64;
120-
121-const
122- RegNames: array[0..3, 0..15] of string[5] = (
123- ('rax', 'rcx', 'rdx', 'rbx', 'rsp', 'rbp', 'rsi', 'rdi',
124- 'r8', 'r9', 'r10', 'r11', 'r12', 'r13', 'r14', 'r15'),
125- ('eax', 'ecx', 'edx', 'ebx', 'esp', 'ebp', 'esi', 'edi',
126- 'r8d', 'r9d', 'r10d', 'r11d', 'r12d', 'r13d', 'r14d', 'r15d'),
127- ('ax', 'cx', 'dx', 'bx', 'sp', 'bp', 'si', 'di',
128- 'r8w', 'r9w', 'r10w', 'r11w', 'r12w', 'r13w', 'r14w', 'r15w'),
129- ('al', 'cl', 'dl', 'bl', 'spl', 'bpl', 'sil', 'dil',
130- 'r8b', 'r9b', 'r10b', 'r11b', 'r12b', 'r13b', 'r14b', 'r15b'));
131- CondNames: array[0..15] of string[3] = ('o', 'no', 'b', 'ae', 'e', 'ne',
132- 'be', 'a', 's', 'ns', 'p', 'np', 'l', 'ge', 'le', 'g');
133-
134-procedure Assemble(constExpr: TConstFn);
135-procedure Say(const s: shortstring);
136-function SaidCount: longint;
137-procedure Unsay(n: longint);
138-procedure Restate(at: longint; const s: shortstring);
139-procedure List(module: longint);
140-
141-implementation
142-
143-{ Operands }
144-
145-function Mem(base: longint; disp: int64): TMem;
146-begin
147- if (disp < low(longint)) or (disp > high(longint)) then Mark('an offset beyond 32 bits');
148- Mem.base := base; Mem.index := NoIndex; Mem.scale := 1;
149- Mem.disp := disp; Mem.chunk := -1;
150-end;
151-
152-function MemRip(chunk: longint; disp: longint): TMem;
153-begin
154- MemRip.base := RIP; MemRip.index := NoIndex; MemRip.scale := 1;
155- MemRip.disp := disp; MemRip.chunk := chunk;
156-end;
157-
158-function MemIdx(base, index, scale: longint; disp: int64): TMem;
159-begin
160- MemIdx := Mem(base, disp);
161- MemIdx.index := index;
162- MemIdx.scale := scale;
163-end;
164-
165-{ The address of the code about to be written, as an operand }
166-function Here: TMem;
167-begin
168- Here := MemRip(curChunk, pc - chunks^[curChunk].start);
169-end;
170-
171-{ Encoding. An instruction is: a legacy prefix, REX, the opcode, ModRM,
172- SIB and displacement. Opcodes of more than one byte are given with
173- their first byte in the low eight bits. }
174-
175-procedure Opcode(op: longint);
176-begin
177- repeat
178- Put1(op and $FF);
179- op := op shr 8;
180- until op = 0;
181-end;
182-
183-{ The legacy prefix pfx, if any, and REX: wide is REX.W; byte4 says
184- a byte register of 4 to 7 is used, spl to dil, which exist only with
185- a REX prefix. }
186-procedure Prefix(pfx: longint; w: boolean; reg, index, base: longint; byte4: boolean);
187-var rex: longint;
188-begin
189- if pfx <> 0 then Put1(pfx);
190- rex := 0;
191- if w then rex := rex or 8;
192- if reg >= 8 then rex := rex or 4;
193- if index >= 8 then rex := rex or 2;
194- if base >= 8 then rex := rex or 1;
195- if (rex <> 0) or byte4 then Put1($40 or rex);
196-end;
197-
198-{ op reg, [mem] }
199-procedure OpM(pfx: longint; w: boolean; op, reg: longint; const m: TMem; byteReg: boolean = false);
200-var md, b, sc: longint;
201-begin
202- byteReg := byteReg and (reg >= 4) and (reg <= 7);
203- if m.base = RIP then Prefix(pfx, w, reg, NoIndex, 0, byteReg)
204- else Prefix(pfx, w, reg, m.index, m.base, byteReg);
205- Opcode(op);
206- reg := reg and 7;
207- if m.base = RIP then begin
208- Put1(reg shl 3 or 5);
209- { mod 00 with r/m 101 is rip + disp32. The displacement counts
210- from the end of the instruction, and the fixup takes it to end
211- with these four bytes: an instruction with an immediate after
212- them, AluMI's or StoreI's, takes the immediate's size off disp
213- first (the assembler can't name a chunk). }
214- AddFixup(pc, m.chunk, m.disp);
215- Put4(0);
216- exit;
217- end;
218- b := m.base and 7;
219- { mod 00 takes no displacement, but with r/m 101 (RBP or R13) it means
220- rip-relative, or disp32 under a SIB byte, so those bases take a
221- zero disp8 }
222- if (m.disp = 0) and (b <> RBP) then md := 0
223- else if (m.disp >= -128) and (m.disp <= 127) then md := 1
224- else md := 2;
225- { r/m 100 (RSP or R12) means a SIB byte follows, so those bases need
226- one, with index 100 meaning none }
227- if (m.index <> NoIndex) or (b = RSP) then begin
228- Put1(md shl 6 or reg shl 3 or 4);
229- case m.scale of 1: sc := 0; 2: sc := 1; 4: sc := 2; else sc := 3; end;
230- if m.index = NoIndex then Put1(sc shl 6 or 4 shl 3 or b)
231- else Put1(sc shl 6 or (m.index and 7) shl 3 or b);
232- end else
233- Put1(md shl 6 or reg shl 3 or b);
234- if md = 1 then Put1(m.disp)
235- else if md = 2 then Put4(m.disp);
236-end;
237-
238-{ op reg, rm (both registers) }
239-procedure OpR(pfx: longint; w: boolean; op, reg, rm: longint; byteReg: boolean = false);
240-begin
241- Prefix(pfx, w, reg, NoIndex, rm, byteReg and ((reg in [4..7]) or (rm in [4..7])));
242- Opcode(op);
243- Put1($C0 or (reg and 7) shl 3 or (rm and 7));
244-end;
245-
246-{ The listing: the text of each instruction, as it is made }
247-
248-type
249- TSaid = record
250- at: longint; { where the instruction starts in code }
251- text: string[63];
252- end;
253-
254-var
255- said: ^TSaid;
256- numSaid, saidCap: longint;
257-
258-{ How many instructions the listing has, and back to n of them, for
259- code made again }
260-function SaidCount: longint;
261-begin
262- SaidCount := numSaid;
263-end;
264-
265-procedure Unsay(n: longint);
266-begin
267- numSaid := n;
268-end;
269-
270-procedure SayAt(at: longint; const s: shortstring);
271-begin
272- if not listing then exit;
273- if numSaid = saidCap then begin
274- saidCap := saidCap * 2 + 1024;
275- said := ReAllocMem(said, saidCap * SizeOf(TSaid));
276- end;
277- said[numSaid].at := at;
278- said[numSaid].text := s;
279- inc(numSaid);
280-end;
281-
282-{ The text of the instruction about to be written }
283-procedure Say(const s: shortstring);
284-begin
285- SayAt(pc, s);
286-end;
287-
288-{ The text of the instruction at at, said again, as when its operand is
289- patched }
290-procedure Restate(at: longint; const s: shortstring);
291-var i: longint;
292-begin
293- i := numSaid - 1;
294- while (i >= 0) and (said[i].at <> at) do dec(i);
295- if i >= 0 then said[i].text := s;
296-end;
297-
298-function RN(r: longint; size: longint = 8): shortstring;
299-begin
300- case size of
301- 1: RN := RegNames[3, r];
302- 2: RN := RegNames[2, r];
303- 4: RN := RegNames[1, r];
304- else RN := RegNames[0, r];
305- end;
306-end;
307-
308-function XN(x: longint): shortstring;
309-begin
310- XN := 'xmm' + IntStr(x);
311-end;
312-
313-{ A memory operand, with the size of what it holds, as the assembler
314- reads it }
315-function MN(const m: TMem; size: longint = 0): shortstring;
316-var s: shortstring;
317-begin
318- case size of
319- 1: s := 'byte ';
320- 2: s := 'word ';
321- 4: s := 'dword ';
322- 8: s := 'qword ';
323- else s := '';
324- end;
325- if m.base = RIP then s := s + '[' + ChunkName(m.chunk)
326- else s := s + '[' + RN(m.base);
327- if m.index <> NoIndex then s := s + ' + ' + RN(m.index) + ' * ' + IntStr(m.scale);
328- if m.disp > 0 then s := s + ' + ' + IntStr(m.disp)
329- else if m.disp < 0 then s := s + ' - ' + IntStr(-m.disp);
330- MN := s + ']';
331-end;
332-
333-const
334- AluNames: array[0..7] of string[3] = ('add', 'or', 'adc', 'sbb', 'and', 'sub', 'xor', 'cmp');
335- ShiftNames: array[0..7] of string[3] = ('rol', 'ror', 'rcl', 'rcr', 'shl', 'shr', 'sal', 'sar');
336- UnaryNames: array[2..7] of string[4] = ('not', 'neg', 'mul', 'imul', 'div', 'idiv');
337-
338-procedure MovRR(dst, src: longint);
339-begin
340- if listing then Say('mov ' + RN(dst) + ', ' + RN(src));
341- OpR(0, true, $89, src, dst);
342-end;
343-
344-{ The immediate of n bytes that ends an instruction }
345-procedure PutImm(v, n: longint);
346-begin
347- if n = 4 then Put4(v)
348- else begin
349- Put1(v and $FF);
350- if n = 2 then Put1((v shr 8) and $FF);
351- end;
352-end;
353-
354-{ op [m], v, on size bytes; v fits in them, or in 32 bits for 8 }
355-procedure AluMI(op: longint; m: TMem; v, size: longint);
356-var n: longint;
357-begin
358- if listing then Say(AluNames[op] + ' ' + MN(m, size) + ', ' + IntStr(v));
359- if (size = 1) or (v >= -128) and (v <= 127) then n := 1
360- else if size = 2 then n := 2
361- else n := 4;
362- if m.base = RIP then dec(m.disp, n);
363- if size = 1 then OpM(0, false, $80, op, m)
364- else if n = 1 then OpM(ord(size = 2) * $66, size = 8, $83, op, m)
365- else OpM(ord(size = 2) * $66, size = 8, $81, op, m);
366- PutImm(v, n);
367-end;
368-
369-{ mov [m], v, of size bytes; v fits in them, or in 32 bits for 8 }
370-procedure StoreI(m: TMem; v, size: longint);
371-var n: longint;
372-begin
373- if listing then Say('mov ' + MN(m, size) + ', ' + IntStr(v));
374- n := size;
375- if n > 4 then n := 4;
376- if m.base = RIP then dec(m.disp, n);
377- if size = 1 then OpM(0, false, $C6, 0, m)
378- else OpM(ord(size = 2) * $66, size = 8, $C7, 0, m);
379- PutImm(v, n);
380-end;
381-
382-procedure MovRI(r: longint; v: int64);
383-begin
384- if not listing then
385- else if v = 0 then Say('xor ' + RN(r, 4) + ', ' + RN(r, 4))
386- else Say('mov ' + RN(r) + ', ' + IntStr(v));
387- if (v >= low(longint)) and (v <= high(longint)) then begin
388- if v = 0 then OpR(0, false, $31, r, r) { xor r32, r32 }
389- else if v > 0 then begin { mov r32, imm32 }
390- Prefix(0, false, 0, NoIndex, r, false); Put1($B8 + r and 7); Put4(v)
391- end else begin
392- OpR(0, true, $C7, 0, r); Put4(v) { sign-extended imm32 }
393- end;
394- end else if (v > 0) and (v <= $FFFFFFFF) then begin
395- Prefix(0, false, 0, NoIndex, r, false); Put1($B8 + r and 7); Put4(longint(v))
396- end else begin
397- Prefix(0, true, 0, NoIndex, r, false); Put1($B8 + r and 7); Put8(v)
398- end;
399-end;
400-
401-procedure Load(r: longint; const m: TMem; size: longint; signed: boolean);
402-begin
403- if not listing then
404- else if size = 8 then Say('mov ' + RN(r) + ', ' + MN(m))
405- else if (size = 4) and not signed then Say('mov ' + RN(r, 4) + ', ' + MN(m))
406- else if size = 4 then Say('movsxd ' + RN(r) + ', ' + MN(m, 4))
407- else if signed then Say('movsx ' + RN(r) + ', ' + MN(m, size))
408- else Say('movzx ' + RN(r, 4) + ', ' + MN(m, size));
409- case size of
410- 1: if signed then OpM(0, true, $BE0F, r, m) else OpM(0, false, $B60F, r, m);
411- 2: if signed then OpM(0, true, $BF0F, r, m) else OpM(0, false, $B70F, r, m);
412- 4: if signed then OpM(0, true, $63, r, m) else OpM(0, false, $8B, r, m);
413- else OpM(0, true, $8B, r, m);
414- end;
415-end;
416-
417-procedure Store(const m: TMem; r: longint; size: longint);
418-begin
419- if listing then Say('mov ' + MN(m) + ', ' + RN(r, size));
420- case size of
421- 1: OpM(0, false, $88, r, m, true);
422- 2: OpM($66, false, $89, r, m);
423- 4: OpM(0, false, $89, r, m);
424- else OpM(0, true, $89, r, m);
425- end;
426-end;
427-
428-procedure Lea(r: longint; const m: TMem);
429-begin
430- if listing then Say('lea ' + RN(r) + ', ' + MN(m));
431- OpM(0, true, $8D, r, m);
432-end;
433-
434-procedure Alu(op, dst, src: longint);
435-begin
436- if listing then Say(AluNames[op] + ' ' + RN(dst) + ', ' + RN(src));
437- OpR(0, true, op shl 3 or 1, src, dst);
438-end;
439-
440-procedure AluI(op, r: longint; v: longint);
441-begin
442- if listing then Say(AluNames[op] + ' ' + RN(r) + ', ' + IntStr(v));
443- if (v >= -128) and (v <= 127) then begin
444- OpR(0, true, $83, op, r); Put1(v)
445- end else begin
446- OpR(0, true, $81, op, r); Put4(v)
447- end;
448-end;
449-
450-{ op r, [m] }
451-procedure AluM(op, r: longint; const m: TMem);
452-begin
453- if listing then Say(AluNames[op] + ' ' + RN(r) + ', ' + MN(m));
454- OpM(0, true, op shl 3 or 3, r, m);
455-end;
456-
457-procedure Imul(dst, src: longint);
458-begin
459- if listing then Say('imul ' + RN(dst) + ', ' + RN(src));
460- OpR(0, true, $AF0F, dst, src);
461-end;
462-
463-procedure ImulI(r: longint; v: longint);
464-begin
465- if listing then Say('imul ' + RN(r) + ', ' + RN(r) + ', ' + IntStr(v));
466- OpR(0, true, $69, r, r);
467- Put4(v);
468-end;
469-
470-procedure Shift(op, r: longint);
471-begin
472- if listing then Say(ShiftNames[op] + ' ' + RN(r) + ', cl');
473- OpR(0, true, $D3, op, r);
474-end;
475-
476-procedure ShiftI(op, r, n: longint);
477-begin
478- if listing then Say(ShiftNames[op] + ' ' + RN(r) + ', ' + IntStr(n));
479- OpR(0, true, $C1, op, r);
480- Put1(n);
481-end;
482-
483-procedure Unary(ext, r: longint);
484-begin
485- if listing then Say(UnaryNames[ext] + ' ' + RN(r));
486- OpR(0, true, $F7, ext, r);
487-end;
488-
489-procedure Cqo;
490-begin
491- if listing then Say('cqo');
492- Put1($48); Put1($99);
493-end;
494-
495-{ Brings a value of size bytes in r to 64 bits, by its sign or zeros. }
496-procedure Extend(r, size: longint; signed: boolean);
497-begin
498- if not listing then
499- else if size = 4 then begin
500- if signed then Say('movsxd ' + RN(r) + ', ' + RN(r, 4)) else Say('mov ' + RN(r, 4) + ', ' + RN(r, 4))
501- end else if signed then Say('movsx ' + RN(r) + ', ' + RN(r, size))
502- else Say('movzx ' + RN(r, 4) + ', ' + RN(r, size));
503- case size of
504- 1: if signed then OpR(0, true, $BE0F, r, r, true) else OpR(0, false, $B60F, r, r, true);
505- 2: if signed then OpR(0, true, $BF0F, r, r) else OpR(0, false, $B70F, r, r);
506- 4: if signed then OpR(0, true, $63, r, r) else OpR(0, false, $89, r, r);
507- end;
508-end;
509-
510-{ r := 1 if the condition holds, else 0 }
511-procedure SetCC(cc, r: longint);
512-begin
513- if listing then Say('set' + CondNames[cc] + ' ' + RN(r, 1));
514- OpR(0, false, $900F + cc shl 8, 0, r, true);
515- if listing then Say('movzx ' + RN(r, 4) + ', ' + RN(r, 1));
516- OpR(0, false, $B60F, r, r, true);
517-end;
518-
519-procedure TestRR(a, b: longint);
520-begin
521- if listing then Say('test ' + RN(a) + ', ' + RN(b));
522- OpR(0, true, $85, b, a);
523-end;
524-
525-procedure Push(r: longint);
526-begin
527- if listing then Say('push ' + RN(r));
528- if r >= 8 then Put1($41);
529- Put1($50 + r and 7);
530-end;
531-
532-procedure Pop(r: longint);
533-begin
534- if listing then Say('pop ' + RN(r));
535- if r >= 8 then Put1($41);
536- Put1($58 + r and 7);
537-end;
538-
539-procedure CallChunk(c: longint);
540-begin
541- if listing then Say('call ' + ChunkName(c));
542- Put1($E8);
543- AddFixup(pc, c, 0);
544- Put4(0);
545-end;
546-
547-procedure CallBack(target: longint);
548-begin
549- if listing then Say('call');
550- Put1($E8);
551- Put4(target - (pc + 4));
552-end;
553-
554-procedure CallR(r: longint);
555-begin
556- if listing then Say('call ' + RN(r));
557- OpR(0, false, $FF, 2, r);
558-end;
559-
560-procedure JmpR(r: longint);
561-begin
562- if listing then Say('jmp ' + RN(r));
563- OpR(0, false, $FF, 4, r);
564-end;
565-
566-procedure CallM(const m: TMem);
567-begin
568- if listing then Say('call ' + MN(m));
569- OpM(0, false, $FF, 2, m);
570-end;
571-
572-procedure Ret; begin if listing then Say('ret'); Put1($C3) end;
573-procedure Leave; begin Say('leave'); Put1($C9) end;
574-procedure Syscall; begin Say('syscall'); Put1($0F); Put1($05) end;
575-procedure Mfence; begin Say('mfence'); Put1($0F); Put1($AE); Put1($F0) end;
576-procedure Ud2; begin Say('ud2'); Put1($0F); Put1($0B) end;
577-
578-{ Code made up to a multiple of n bytes with no-ops, the fewest: the
579- long forms of nop, of up to 8 bytes, that x86 decodes as one }
580-procedure Align(n: longint);
581-const
582- Nops: array[1..8] of string[8] = (#$90, #$66#$90, #$0F#$1F#$00, #$0F#$1F#$40#$00,
583- #$0F#$1F#$44#$00#$00, #$66#$0F#$1F#$44#$00#$00, #$0F#$1F#$80#$00#$00#$00#$00,
584- #$0F#$1F#$84#$00#$00#$00#$00#$00);
585-var k, i: longint;
586-begin
587- while pc mod n <> 0 do begin
588- k := n - pc mod n;
589- if k > 8 then k := 8;
590- Say('nop');
591- for i := 1 to k do Put1(ord(Nops[k][i]));
592- end;
593-end;
594-procedure RepMovsb; begin Say('rep movsb'); Put1($F3); Put1($A4) end;
595-{ the direction flag, which has rep movsb go down, and back up }
596-procedure Std; begin Say('std'); Put1($FD) end;
597-procedure Cld; begin Say('cld'); Put1($FC) end;
598-procedure RepStosb; begin Say('rep stosb'); Put1($F3); Put1($AA) end;
599-procedure RepeCmpsb; begin Say('repe cmpsb'); Put1($F3); Put1($A6) end;
600-
601-procedure LockCmpxchg(const m: TMem; r: longint);
602-begin
603- if listing then Say('lock cmpxchg ' + MN(m) + ', ' + RN(r));
604- Put1($F0);
605- OpM(0, true, $B10F, r, m);
606-end;
607-
608-procedure Xchg(const m: TMem; r: longint);
609-begin
610- if listing then Say('xchg ' + MN(m) + ', ' + RN(r));
611- OpM(0, true, $87, r, m);
612-end;
613-
614-procedure LockXadd(const m: TMem; r: longint);
615-begin
616- if listing then Say('lock xadd ' + MN(m) + ', ' + RN(r));
617- Put1($F0);
618- OpM(0, true, $C10F, r, m);
619-end;
620-
621-procedure MovqXR(x, r: longint);
622-begin
623- if listing then Say('movq ' + XN(x) + ', ' + RN(r));
624- OpR($66, true, $6E0F, x, r);
625-end;
626-
627-procedure MovqRX(r, x: longint);
628-begin
629- if listing then Say('movq ' + RN(r) + ', ' + XN(x));
630- OpR($66, true, $7E0F, x, r);
631-end;
632-
633-{ movaps: all of xmm y to xmm x, the shortest move between two }
634-procedure MovX(x, y: longint);
635-begin
636- if listing then Say('movaps ' + XN(x) + ', ' + XN(y));
637- OpR(0, false, $280F, x, y);
638-end;
639-
640-const
641- RealPfx: array[boolean] of longint = ($F2, $F3);
642- RealEnd: array[boolean] of string[2] = ('sd', 'ss');
643-
644-procedure MovsXM(x: longint; const m: TMem; single: boolean);
645-begin
646- if listing then Say('movs' + RealEnd[single][2] + ' ' + XN(x) + ', ' + MN(m));
647- OpM(RealPfx[single], false, $100F, x, m);
648-end;
649-
650-procedure MovsMX(const m: TMem; x: longint; single: boolean);
651-begin
652- if listing then Say('movs' + RealEnd[single][2] + ' ' + MN(m) + ', ' + XN(x));
653- OpM(RealPfx[single], false, $110F, x, m);
654-end;
655-
656-function SseName(op: longint; single: boolean): shortstring;
657-begin
658- case op of
659- $58: SseName := 'add' + RealEnd[single];
660- $59: SseName := 'mul' + RealEnd[single];
661- $5C: SseName := 'sub' + RealEnd[single];
662- $5E: SseName := 'div' + RealEnd[single];
663- else SseName := 'cvt' + RealEnd[single] + '2' + RealEnd[not single];
664- end;
665-end;
666-
667-procedure Sse(op, x, y: longint; single: boolean);
668-begin
669- if listing then Say(SseName(op, single) + ' ' + XN(x) + ', ' + XN(y));
670- OpR(RealPfx[single], false, $0F or op shl 8, x, y);
671-end;
672-
673-{ The same, its right operand in memory: addsd x, [m] }
674-procedure SseM(op, x: longint; const m: TMem; single: boolean);
675-begin
676- if listing then Say(SseName(op, single) + ' ' + XN(x) + ', ' + MN(m));
677- OpM(RealPfx[single], false, $0F or op shl 8, x, m);
678-end;
679-
680-procedure Ucomis(x, y: longint; single: boolean);
681-begin
682- if listing then Say('ucomi' + RealEnd[single] + ' ' + XN(x) + ', ' + XN(y));
683- if single then OpR(0, false, $2E0F, x, y) else OpR($66, false, $2E0F, x, y);
684-end;
685-
686-procedure Cvtsi2s(x, r: longint; single: boolean);
687-begin
688- if listing then Say('cvtsi2' + RealEnd[single] + ' ' + XN(x) + ', ' + RN(r));
689- OpR(RealPfx[single], true, $2A0F, x, r);
690-end;
691-
692-procedure Cvtts2si(r, x: longint; single: boolean);
693-begin
694- if listing then Say('cvtt' + RealEnd[single] + '2si ' + RN(r) + ', ' + XN(x));
695- OpR(RealPfx[single], true, $2C0F, r, x);
696-end;
697-
698-procedure Btc(r, bit: longint);
699-begin
700- if listing then Say('btc ' + RN(r) + ', ' + IntStr(bit));
701- OpR(0, true, $BA0F, 7, r);
702- Put1(bit);
703-end;
704-
705-{ Jumps. A label not yet placed is the chain of the jumps to it, each
706- rel32 field holding the position of the one before, NoLabel ending
707- it. Placing the label walks the chain and patches each. }
708-
709-procedure Jmp(var L: longint);
710-begin
711- if listing then Say('jmp');
712- Put1($E9);
713- Put4(L);
714- L := pc - 4;
715-end;
716-
717-procedure Jcc(cc: longint; var L: longint);
718-begin
719- if listing then Say('j' + CondNames[cc]);
720- Put1($0F); Put1($80 + cc);
721- Put4(L);
722- L := pc - 4;
723-end;
724-
725-procedure JmpBack(target: longint);
726-begin
727- if listing then Say('jmp');
728- Put1($E9);
729- Put4(target - (pc + 4));
730-end;
731-
732-procedure JccBack(cc, target: longint);
733-begin
734- if listing then Say('j' + CondNames[cc]);
735- Put1($0F); Put1($80 + cc);
736- Put4(target - (pc + 4));
737-end;
738-
739-procedure FixLinkTo(L, target: longint);
740-var next: longint;
741-begin
742- while L <> NoLabel do begin
743- next := Get4At(L);
744- Put4At(L, target - (L + 4));
745- L := next;
746- end;
747-end;
748-
749-procedure FixLink(L: longint);
750-begin
751- FixLinkTo(L, pc);
752-end;
753-
754-{ If the last instruction made is a jmp to L, it is taken back, since L
755- is to be placed just after it: a return at the end of a procedure
756- needn't jump to the code that returns. L is the place of the latest
757- jump's 4-byte field, so the last instruction is that jump when L is
758- 4 bytes back and an E9 byte (jmp) is before it; a jcc's field follows
759- the bytes 0F 8x, never E9. L then becomes the next jump on the chain,
760- which the field held. The caller must place L next, before anything
761- can have noted where the jmp ended. }
762-procedure DropJumpTo(var L: longint);
763-begin
764- if (L = NoLabel) or (L <> pc - 4) or (code^[L - 1] <> $E9) then exit;
765- L := Get4At(L);
766- TakeBack(5);
767- if listing and (numSaid > 0) and (said[numSaid - 1].at = pc) then dec(numSaid);
768-end;
769-
770-{ The jumps of chains L1 and L2, as one chain: each jump's field holds
771- the next one's place until it is fixed, the last NoLabel }
772-function JoinLinks(L1, L2: longint): longint;
773-var L: longint;
774-begin
775- if L2 = NoLabel then exit(L1);
776- if L1 <> NoLabel then begin
777- L := L2;
778- while Get4At(L) <> NoLabel do L := Get4At(L);
779- Put4At(L, L1);
780- end;
781- JoinLinks := L2;
782-end;
783-
784-
785-{ The assembler, for code procedures: x86-64 in Intel's syntax as NASM
786- writes it (report, appendix A). It reads instructions with the
787- scanner up to end, and encodes them with OpM and OpR; constants are
788- read by the parser's constExpr. }
789-
790-const
791- NoBase = -3; { a memory operand's base, not yet read }
792-
793-type
794- TOpKind = (oReg, oXmm, oMem, oImm);
795- TOpd = record
796- kind: TOpKind;
797- r, size: longint; { oReg, oXmm: the register and its size; oMem: its size, or 0 }
798- m: TMem;
799- v: int64; { oImm }
800- end;
801-
802-{ The current symbol as a word: an identifier, or a reserved word that
803- is also an instruction }
804-function AsmWord: shortstring;
805-begin
806- case tok of
807- sIdent: AsmWord := NameOf(id);
808- sAnd: AsmWord := 'and';
809- sOr: AsmWord := 'or';
810- sXor: AsmWord := 'xor';
811- sNot: AsmWord := 'not';
812- sDiv: AsmWord := 'div';
813- sShl: AsmWord := 'shl';
814- sShr: AsmWord := 'shr';
815- else AsmWord := '';
816- end;
817-end;
818-
819-{ Whether w names a register: rax, eax, ax, al and so on, or xmm0 to
820- xmm15 (size 16) }
821-function IsReg(const w: shortstring; var r, size: longint): boolean;
822-const Sizes: array[0..3] of longint = (8, 4, 2, 1);
823-var i, j, e: longint;
824-begin
825- IsReg := true;
826- for i := 0 to 3 do
827- for j := 0 to 15 do
828- if RegNames[i, j] = w then begin r := j; size := Sizes[i]; exit end;
829- size := 16;
830- Val(copy(w, 4, 2), r, e);
831- IsReg := (copy(w, 1, 3) = 'xmm') and (length(w) > 3) and (e = 0) and (r in [0..15]);
832-end;
833-
834-{ Which word of list, a list of words each with a space either side,
835- w is, from 0; -1 if none }
836-function WordIndex(const w, list: shortstring): longint;
837-var i, k: longint;
838-begin
839- k := pos(' ' + w + ' ', list);
840- WordIndex := -1;
841- if k = 0 then exit;
842- WordIndex := 0;
843- for i := 2 to k do if list[i] = ' ' then inc(WordIndex);
844-end;
845-
846-{ The condition a name ends in: e of je, nz of jnz }
847-function Cond(const w: shortstring): longint;
848-const
849- Alias: array[0..11] of string[3] = ('c', 'nae', 'nc', 'nb', 'z', 'nz', 'na', 'nbe', 'nge', 'nl', 'ng', 'nle');
850- AliasCc: array[0..11] of longint = (2, 2, 3, 3, 4, 5, 6, 7, 12, 13, 14, 15);
851-var i: longint;
852-begin
853- for i := 0 to 15 do if CondNames[i] = w then exit(i);
854- for i := 0 to 11 do if Alias[i] = w then exit(AliasCc[i]);
855- Cond := -1;
856-end;
857-
858-procedure Operand(var o: TOpd; constExpr: TConstFn);
859-var w: shortstring; r, size, sz: longint; st: TScanState;
860-begin
861- FillChar(o, SizeOf(o), 0);
862- w := AsmWord;
863- sz := 0;
864- if w = 'byte' then sz := 1 else if w = 'word' then sz := 2
865- else if w = 'dword' then sz := 4 else if w = 'qword' then sz := 8;
866- if sz <> 0 then begin Next; w := AsmWord end;
867- if tok = sLbrak then begin
868- { [base + index * scale + disp], the displacement last }
869- Next;
870- o.kind := oMem; o.size := sz;
871- o.m := Mem(NoBase, 0);
872- repeat
873- if IsReg(AsmWord, r, size) and (size = 8) then begin
874- Next;
875- { the scale is a single number or constant: a whole expression
876- would take in the displacement after it, as 4 + 16 in
877- [rdi + rsi * 4 + 16] }
878- if tok = sTimes then begin
879- Next;
880- o.m.index := r;
881- o.m.scale := constExpr(false);
882- end
883- else if o.m.base = NoBase then o.m.base := r
884- else begin o.m.index := r; o.m.scale := 1 end;
885- end else o.m.disp := o.m.disp + constExpr(true);
886- if not (tok in [sPlus, sMinus]) then break;
887- SaveScan(st);
888- Next;
889- if not IsReg(AsmWord, r, size) and (st.tok = sMinus) then RestoreScan(st);
890- until false;
891- if (tok <> sRbrak) or (o.m.base = NoBase) or not (o.m.scale in [1, 2, 4, 8]) then
892- Mark('expected a memory operand, [base + index * scale + disp]');
893- Next;
894- end else if IsReg(w, o.r, o.size) then begin
895- if o.size = 16 then o.kind := oXmm else o.kind := oReg;
896- Next;
897- end else begin
898- o.kind := oImm;
899- o.v := constExpr(true);
900- end;
901-end;
902-
903-{ op with register reg and the register or memory operand o }
904-procedure RM(pfx: longint; w: boolean; op, reg: longint; const o: TOpd; byteReg: boolean = false);
905-begin
906- if o.kind = oMem then OpM(pfx, w, op, reg, o.m, byteReg)
907- else OpR(pfx, w, op, reg, o.r, byteReg);
908-end;
909-
910-procedure PutImm(v: int64; size: longint);
911-begin
912- case size of
913- 1: Put1(v);
914- 2: begin Put1(v); Put1(v shr 8) end;
915- else Put4(v);
916- end;
917-end;
918-
919-procedure Assemble(constExpr: TConstFn);
920-const
921- Alus = ' add or adc sbb and sub xor cmp ';
922- Unaries = ' not neg mul imul div idiv ';
923- Shifts = ' rol ror rcl rcr shl shr sal sar ';
924- SseOps = ' sqrt add mul sub min div max ';
925- SseCodes: array[0..6] of longint = ($51, $58, $59, $5C, $5D, $5E, $5F);
926- { SSE2 integer instructions that work on 16 bytes at a time: 66 0F code,
927- xmm and xmm or memory (pshufd also takes a byte) }
928- PackedOps = ' punpcklbw punpcklwd pcmpeqb pshufd pand pandn por pxor paddb psubb ';
929- PackedCodes: array[0..9] of longint = ($60, $61, $74, $70, $DB, $DF, $EB, $EF, $FC, $F8);
930- { bit scans and counts: reg, reg or memory, with the prefix and code that tell them }
931- BitOps = ' bsf bsr tzcnt lzcnt popcnt ';
932- BitPfx: array[0..4] of longint = (0, 0, $F3, $F3, $F3);
933- BitCodes: array[0..4] of longint = ($BC0F, $BD0F, $BC0F, $BD0F, $B80F);
934- Plain: array[0..14] of string[7] = ('ret', 'leave', 'syscall', 'cpuid', 'rdtsc',
935- 'pause', 'nop', 'ud2', 'int3', 'hlt', 'cqo', 'cdq', 'mfence', 'lfence', 'sfence');
936- PlainOp: array[0..14] of longint = ($C3, $C9, $050F, $A20F, $310F,
937- $90F3, $90, $0B0F, $CC, $F4, $9948, $99, $F0AE0F, $E8AE0F, $F8AE0F);
938-var
939- w: shortstring; o: array[0..2] of TOpd; n, i, k, size, pfx, cc: longint;
940- wide, byteOp, wasListing: boolean; at, start: TPos; v: int64; first: longint;
941- names, places, chains: array[0..63] of longint; numLabels: longint;
942- usedAt: array[0..63] of TPos;
943-
944- { the label called n, entered if new }
945- function Lab(n: longint): longint;
946- var i: longint;
947- begin
948- for i := 0 to numLabels - 1 do if names[i] = n then exit(i);
949- if numLabels > High(names) then Mark('more than 64 labels');
950- names[numLabels] := n; places[numLabels] := -1; chains[numLabels] := NoLabel;
951- usedAt[numLabels] := TokPos;
952- Lab := numLabels;
953- inc(numLabels);
954- end;
955-
956- procedure Bad;
957- begin
958- MarkAt(at, 'can''t assemble ' + w + ' with these operands');
959- end;
960-
961- { an instruction of two operands: a register or memory, and a
962- register (opcode toRM), the other way (fromRM), or an immediate
963- (opImm /digit, or none if opImm < 0) }
964- procedure Two(toRM, fromRM, opImm, digit: longint);
965- begin
966- if n <> 2 then Bad;
967- if o[1].kind = oImm then begin
968- if (o[0].kind = oImm) or (opImm < 0) then Bad;
969- if (opImm = $81) and not byteOp and (o[1].v >= -128) and (o[1].v <= 127) then begin
970- RM(pfx, wide, $83, digit, o[0]); { a byte, sign-extended }
971- Put1(o[1].v);
972- end else begin
973- RM(pfx, wide, opImm - ord(byteOp), digit, o[0]);
974- PutImm(o[1].v, size);
975- end;
976- end else if (o[1].kind = oReg) and (o[0].kind in [oReg, oMem]) then
977- RM(pfx, wide, toRM - ord(byteOp), o[1].r, o[0], byteOp)
978- else if (o[0].kind = oReg) and (o[1].kind = oMem) then
979- RM(pfx, wide, fromRM - ord(byteOp), o[0].r, o[1], byteOp)
980- else Bad;
981- end;
982-
983-begin
984- numLabels := 0;
985- while not (tok in [sEnd, sEof]) do begin
986- at := TokPos;
987- w := AsmWord;
988- if tok = sSemicolon then begin Next; continue end;
989- if w = '' then Mark('expected an instruction');
990- Next;
991- if tok = sColon then begin
992- SayAt(pc, w + ':');
993- k := Lab(Intern(@w[1], length(w)));
994- if places[k] >= 0 then MarkAt(at, 'label ' + w + ' is defined twice');
995- places[k] := pc;
996- FixLink(chains[k]);
997- Next;
998- continue;
999- end;
1000- first := pc;
1001- wasListing := listing;
1002- listing := false; { the instruction is said as it is written }
1003- if w = 'lock' then begin
1004- Put1($F0);
1005- w := AsmWord;
1006- Next;
1007- end;
1008- cc := -1;
1009- if w = 'db' then
1010- repeat
1011- start := TokPos;
1012- v := constExpr(true);
1013- if (v < -128) or (v > 255) then MarkAt(SpanFrom(start), 'expected a byte from 0 to 255, found ' + IntStr(v));
1014- Put1(v);
1015- if tok <> sComma then break;
1016- Next;
1017- until false
1018- else if (w[1] = 'j') and ((w = 'jmp') or (Cond(copy(w, 2, 3)) >= 0)) and (tok = sIdent) then begin
1019- { a jump to a label }
1020- k := Lab(id);
1021- Next;
1022- if w <> 'jmp' then cc := Cond(copy(w, 2, 3));
1023- if places[k] >= 0 then begin
1024- if cc < 0 then JmpBack(places[k]) else JccBack(cc, places[k])
1025- end else if cc < 0 then Jmp(chains[k]) else Jcc(cc, chains[k]);
1026- end else begin
1027- n := 0;
1028- if tok <> sSemicolon then
1029- repeat
1030- if n > High(o) then Mark('too many operands');
1031- Operand(o[n], constExpr);
1032- inc(n);
1033- if tok <> sComma then break;
1034- Next;
1035- until false;
1036- { the size: a register's, or what the memory operand says }
1037- size := 8;
1038- for i := n - 1 downto 0 do
1039- if (o[i].kind = oReg) or (o[i].kind = oMem) and (o[i].size <> 0) then size := o[i].size;
1040- if n > 0 then
1041- if (o[0].kind = oReg) or (o[0].kind = oMem) and (o[0].size <> 0) then size := o[0].size;
1042- wide := size = 8;
1043- byteOp := size = 1;
1044- if size = 2 then pfx := $66 else pfx := 0;
1045- if WordIndex(w, Alus) >= 0 then begin
1046- k := WordIndex(w, Alus);
1047- Two(k * 8 + 1, k * 8 + 3, $81, k)
1048- end
1049- else if w = 'mov' then begin
1050- if (n = 2) and (o[0].kind = oReg) and (o[1].kind = oImm) and (size >= 4) then begin
1051- if wide then MovRI(o[0].r, o[1].v)
1052- else begin Prefix(0, false, 0, NoIndex, o[0].r, false); Put1($B8 + o[0].r and 7); Put4(o[1].v) end;
1053- end else Two($89, $8B, $C7, 0);
1054- end else if w = 'test' then Two($85, $85, $F7, 0)
1055- else if w = 'xchg' then Two($87, $87, -1, 0)
1056- else if (w = 'cmpxchg') or (w = 'xadd') then begin
1057- if (n <> 2) or (o[1].kind <> oReg) then Bad;
1058- if w = 'xadd' then k := $C10F else k := $B10F;
1059- RM(pfx, wide, k - ord(byteOp) shl 8, o[1].r, o[0], byteOp);
1060- end else if w = 'lea' then begin
1061- if (n <> 2) or (o[0].kind <> oReg) or (o[1].kind <> oMem) then Bad;
1062- RM(pfx, wide, $8D, o[0].r, o[1]);
1063- end else if (w = 'movzx') or (w = 'movsx') or (w = 'movsxd') then begin
1064- if (n <> 2) or (o[0].kind <> oReg) or (o[1].kind = oImm) then Bad;
1065- if w = 'movsxd' then k := $63
1066- else if o[1].size = 1 then k := $B60F
1067- else if o[1].size = 2 then k := $B70F
1068- else Bad;
1069- if w = 'movsx' then k := k + $0800;
1070- RM(pfx, wide, k, o[0].r, o[1], o[1].size = 1);
1071- end else if ((WordIndex(w, Unaries) >= 0) and (n = 1)) or (w = 'inc') or (w = 'dec') then begin
1072- if o[0].kind = oImm then Bad;
1073- if w = 'inc' then RM(pfx, wide, $FF - ord(byteOp), 0, o[0], byteOp)
1074- else if w = 'dec' then RM(pfx, wide, $FF - ord(byteOp), 1, o[0], byteOp)
1075- else RM(pfx, wide, $F7 - ord(byteOp), WordIndex(w, Unaries) + 2, o[0], byteOp);
1076- end else if w = 'imul' then begin
1077- if (n < 2) or (o[0].kind <> oReg) or (o[1].kind = oImm) then Bad;
1078- if n = 2 then RM(pfx, wide, $AF0F, o[0].r, o[1])
1079- else begin RM(pfx, wide, $69, o[0].r, o[1]); PutImm(o[2].v, size) end;
1080- end else if WordIndex(w, Shifts) >= 0 then begin
1081- k := WordIndex(w, Shifts);
1082- if k = 6 then k := 4; { sal is shl }
1083- if (n <> 2) or (o[0].kind = oImm) then Bad;
1084- if o[1].kind = oImm then begin RM(pfx, wide, $C1 - ord(byteOp), k, o[0], byteOp); Put1(o[1].v) end
1085- else if (o[1].kind = oReg) and (o[1].r = RCX) and (o[1].size = 1) then RM(pfx, wide, $D3 - ord(byteOp), k, o[0], byteOp)
1086- else Bad;
1087- end else if (w = 'push') or (w = 'pop') then begin
1088- if (n <> 1) or (o[0].kind <> oReg) or not wide then Bad;
1089- if w = 'push' then Push(o[0].r) else Pop(o[0].r);
1090- end else if (w = 'call') or (w = 'jmp') then begin
1091- if (n <> 1) or (o[0].kind = oImm) then Bad;
1092- if w = 'call' then RM(0, false, $FF, 2, o[0]) else RM(0, false, $FF, 4, o[0]);
1093- end else if (copy(w, 1, 3) = 'set') and (Cond(copy(w, 4, 3)) >= 0) then begin
1094- if (n <> 1) or (o[0].kind = oImm) or (size <> 1) then Bad;
1095- RM(0, false, $900F + Cond(copy(w, 4, 3)) shl 8, 0, o[0], true);
1096- end else if (copy(w, 1, 4) = 'cmov') and (Cond(copy(w, 5, 3)) >= 0) then begin
1097- if (n <> 2) or (o[0].kind <> oReg) or (o[1].kind = oImm) then Bad;
1098- RM(pfx, wide, $400F + Cond(copy(w, 5, 3)) shl 8, o[0].r, o[1]);
1099- end else if (length(w) > 2) and (WordIndex(copy(w, 1, length(w) - 2), SseOps) >= 0)
1100- and ((copy(w, length(w) - 1, 2) = 'sd') or (copy(w, length(w) - 1, 2) = 'ss')) then begin
1101- { sqrtsd, addss and the like: xmm, xmm or memory }
1102- if (n <> 2) or (o[0].kind <> oXmm) or not (o[1].kind in [oXmm, oMem]) then Bad;
1103- k := $0F or SseCodes[WordIndex(copy(w, 1, length(w) - 2), SseOps)] shl 8;
1104- RM(RealPfx[w[length(w)] = 's'], false, k, o[0].r, o[1]);
1105- end else if WordIndex(w, PackedOps) >= 0 then begin
1106- if (n < 2) or (o[0].kind <> oXmm) or not (o[1].kind in [oXmm, oMem]) then Bad;
1107- k := WordIndex(w, PackedOps);
1108- RM($66, false, $0F or PackedCodes[k] shl 8, o[0].r, o[1]);
1109- if w = 'pshufd' then begin
1110- if (n <> 3) or (o[2].kind <> oImm) then Bad;
1111- Put1(o[2].v);
1112- end else if n <> 2 then Bad;
1113- end else if (w = 'movdqu') or (w = 'movdqa') then begin
1114- { the load is 6F and the store 7F; movdqu is F3, movdqa 66 }
1115- if w = 'movdqu' then k := $F3 else k := $66;
1116- if (n = 2) and (o[0].kind = oXmm) and (o[1].kind in [oXmm, oMem]) then RM(k, false, $6F0F, o[0].r, o[1])
1117- else if (n = 2) and (o[0].kind = oMem) and (o[1].kind = oXmm) then RM(k, false, $7F0F, o[1].r, o[0])
1118- else Bad;
1119- end else if w = 'pmovmskb' then begin
1120- if (n <> 2) or (o[0].kind <> oReg) or (o[1].kind <> oXmm) then Bad;
1121- RM($66, false, $D70F, o[0].r, o[1]);
1122- end else if WordIndex(w, BitOps) >= 0 then begin
1123- if (n <> 2) or (o[0].kind <> oReg) or (o[1].kind = oImm) or (size < 4) then Bad;
1124- k := WordIndex(w, BitOps);
1125- RM(BitPfx[k], wide, BitCodes[k], o[0].r, o[1]);
1126- end else if (w = 'movsd') or (w = 'movss') then begin
1127- if w = 'movsd' then k := $F2 else k := $F3;
1128- if (n = 2) and (o[0].kind = oXmm) and (o[1].kind in [oXmm, oMem]) then RM(k, false, $100F, o[0].r, o[1])
1129- else if (n = 2) and (o[0].kind = oMem) and (o[1].kind = oXmm) then RM(k, false, $110F, o[1].r, o[0])
1130- else Bad;
1131- end else if (w = 'movq') or (w = 'movd') then begin
1132- if (n = 2) and (o[0].kind = oXmm) and (o[1].kind in [oReg, oMem]) then RM($66, w = 'movq', $6E0F, o[0].r, o[1])
1133- else if (n = 2) and (o[1].kind = oXmm) and (o[0].kind in [oReg, oMem]) then RM($66, w = 'movq', $7E0F, o[1].r, o[0])
1134- else Bad;
1135- end else if (w = 'ucomisd') or (w = 'ucomiss') then begin
1136- if (n <> 2) or (o[0].kind <> oXmm) or not (o[1].kind in [oXmm, oMem]) then Bad;
1137- if w = 'ucomisd' then RM($66, false, $2E0F, o[0].r, o[1]) else RM(0, false, $2E0F, o[0].r, o[1]);
1138- end else if (w = 'cvtsi2sd') or (w = 'cvtsi2ss') then begin
1139- if (n <> 2) or (o[0].kind <> oXmm) or not (o[1].kind in [oReg, oMem]) then Bad;
1140- RM(RealPfx[w = 'cvtsi2ss'], o[1].size <> 4, $2A0F, o[0].r, o[1]);
1141- end else if (w = 'cvttsd2si') or (w = 'cvttss2si') then begin
1142- if (n <> 2) or (o[0].kind <> oReg) or not (o[1].kind in [oXmm, oMem]) then Bad;
1143- RM(RealPfx[w = 'cvttss2si'], wide, $2C0F, o[0].r, o[1]);
1144- end else if (w = 'cvtsd2ss') or (w = 'cvtss2sd') then begin
1145- if (n <> 2) or (o[0].kind <> oXmm) or not (o[1].kind in [oXmm, oMem]) then Bad;
1146- RM(RealPfx[w = 'cvtss2sd'], false, $5A0F, o[0].r, o[1]);
1147- end else begin
1148- k := 0;
1149- while (k <= High(Plain)) and (Plain[k] <> w) do inc(k);
1150- if (k > High(Plain)) or (n <> 0) then MarkAt(at, 'unknown instruction ' + w);
1151- Opcode(PlainOp[k]);
1152- end;
1153- end;
1154- if tok <> sSemicolon then Mark('expected ";"');
1155- listing := wasListing;
1156- SayAt(first, Source(SpanFrom(at)));
1157- Next;
1158- end;
1159- for k := 0 to numLabels - 1 do
1160- if places[k] < 0 then MarkAt(usedAt[k], 'label ' + NameOf(names[k]) + ' isn''t defined');
1161-end;
1162-
1163-{ The listing, raz -S: each live procedure of the module in the order
1164- it was made, each line of source it comes from, and under it the
1165- instructions made for it, at their offsets in the procedure; a jump
1166- within it says where to by its offset too. }
1167-procedure List(module: longint);
1168-var order: ^longint; n, i, j, k, c, t, line: longint; text: shortstring;
1169-begin
1170- order := GetMem(numChunks * SizeOf(longint));
1171- n := 0;
1172- for c := 0 to numChunks - 1 do
1173- if chunks^[c].live and (chunks^[c].sec = secText) and (chunks^[c].module = module) then begin
1174- i := n;
1175- while (i > 0) and (chunks^[order[i - 1]].start > chunks^[c].start) do begin
1176- order[i] := order[i - 1];
1177- dec(i);
1178- end;
1179- order[i] := c;
1180- inc(n);
1181- end;
1182- i := 0; j := 0;
1183- for k := 0 to n - 1 do begin
1184- c := order[k];
1185- writeln;
1186- writeln(ChunkName(c), ':');
1187- line := -1;
1188- while (i < numSaid) and (said[i].at < chunks^[c].start) do inc(i);
1189- while (i < numSaid) and (said[i].at < chunks^[c].start + chunks^[c].size) do begin
1190- while (j < numLines) and (lines^[j].at <= said[i].at) do begin
1191- if (lines^[j].chunk = c) and (lines^[j].line <> line) then begin
1192- line := lines^[j].line;
1193- writeln(line: 6, ' ', LineText(NameOf(lines^[j].path), line));
1194- end;
1195- inc(j);
1196- end;
1197- text := said[i].text;
1198- t := said[i].at;
1199- if (text = 'jmp') or (text = 'call') then text := text + ' ' + IntStr(t + 5 + Get4At(t + 1) - chunks^[c].start)
1200- else if (text[1] = 'j') and (pos(' ', text) = 0) then text := text + ' ' + IntStr(t + 6 + Get4At(t + 2) - chunks^[c].start);
1201- writeln(t - chunks^[c].start: 14, ' ', text);
1202- inc(i);
1203- end;
1204- end;
1205- FreeMem(order);
1206-end;
1207-
1208-end.