raz / commit 6a2ca870

commit
6a2ca870340781a4d243c28b75bc4ecae85eec2d
author
Luis <42945842+ldiaz94@users.noreply.github.com>
date
parent
a4419423
Self step 3a: Gen in raz, tested against the seed's

self/Gen.raz, the code generator: the stack machine, checks, calls,
frames, defers and the entry point. test/GenDump.{pas,raz} compile 80
procedures from a fixed pseudo-random script of valid calls, with every
kind of expression, statement and call, on both sides; the bytes,
fixups, line notes and listing are the same (static and dynamic entry).
README lists what the port found.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

patch · log

4 files changed, +3803 -0

self/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.

self/check.sh modified +13 -0

@@ -91,3 +91,16 @@
9191 done
9292 echo "x64: $n assembler files, $bad differ"
9393 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"

self/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+ 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 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: 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.