From ff8675c833ca4fcd8cd9cb5c5a55f01d404a1d60 Mon Sep 17 00:00:00 2001 From: Luis <42945842+ldiaz94@users.noreply.github.com> Date: Mon, 12 Oct 2026 15:27:02 +0100 Subject: [PATCH] Comments a beginner can follow v0.7.0 step 7, second part: the fresh reader's review, comments and compiler.md only (and parentheses in BeginProc that change nothing). gen.pas's header says what a slice is, what spill, System V and callee-saved mean, and which results come back in rax and rdx; Check lists every kind of failure and the registers Rt.fail gets; Drop's register keeping its value is said once; the magic numbers of div, idiv, neg, not and the SSE operations are named where used; DivPow2, the real compares, Call's r8 and r9, the stack's alignment, the prologue, the entry point and the fail stubs are walked through. ForNext's comment is the report's rule, then each case. compiler.md stops saying the value at depth d is in register d, and lists lHeld. Left unexplained: EndProc's frame of at least 16 bytes, whose reason neither the code nor its history gives; failStubs's slot 5, which no Check uses. --- diff --git a/doc/compiler.md b/doc/compiler.md index 8f16251..f624dc9 100644 --- a/doc/compiler.md +++ b/doc/compiler.md @@ -10,12 +10,12 @@ |---|---|---|---| | `src/diag.pas` | 316 | 233 | Messages: positions, source excerpts, colour, counts | | `src/scan.pas` | 886 | 747 | Symbols, literals, comments, positions | -| `src/sym.pas` | 643 | 527 | Types, objects, scopes, layout | +| `src/sym.pas` | 644 | 527 | Types, objects, scopes, layout | | `src/chunk.pas` | 318 | 246 | The compiled program: chunks, fixups, line notes | -| `src/x64.pas` | 1,125 | 936 | The instruction encoder, jumps within a procedure, the assembler | -| `src/gen.pas` | 1,666 | 1,291 | The stack machine, for x86-64: values, operations, checks, calls, frames | -| `src/item.pas` | 1,536 | 1,278 | Items: types, constants, variables, operators, conversions, calls | -| `src/parse.pas` | 2,967 | 2,612 | Declarations, statements, expressions, built-ins, recovery, warnings | +| `src/x64.pas` | 1,128 | 936 | The instruction encoder, jumps within a procedure, the assembler | +| `src/gen.pas` | 1,768 | 1,291 | The stack machine, for x86-64: values, operations, checks, calls, frames | +| `src/item.pas` | 1,551 | 1,278 | Items: types, constants, variables, operators, conversions, calls | +| `src/parse.pas` | 2,975 | 2,612 | Declarations, statements, expressions, built-ins, recovery, warnings | | `src/link.pas` | 247 | 190 | Tree shaking, layout, patching, the places | | `src/elf.pas` | 435 | 352 | Static and dynamic ELF, symbol table, line numbers | | `src/raz.pas` | 197 | 147 | The command line | @@ -41,18 +41,23 @@ another machine is a new `gen.pas`, with an encoder of its own in place of `x64.pas`. -On x86-64 the stack lives in registers, as in Wirth's compilers: the -value at depth `d` is in register `d`, of `r8` to `r11`, and a constant -or an address in the frame or of a chunk is only noted, until something -needs it in a register, so that it can be an instruction's operand. A +On x86-64 the stack lives in registers, as in Wirth's compilers +(Niklaus Wirth's Pascal and Oberon compilers): the value at depth `d`, +depth 0 being the bottom, is in register `d mod 4`, of `r8` to `r11`. +A value that needs a register a lower one holds *spills* it: stores it +in a frame slot, to free the register. A constant or an address in the +frame or of a chunk is only noted, until something needs it in a +register, so that it can be an instruction's operand. A comparison, too, waits as a condition, so that `if` and `while` jump on it directly. Which register a value goes in is settled by its depth, so there is no register allocator for values, and every access the program writes is one instruction, in the order written. That is also why `VOLATILE` costs the compiler nothing: it never does anything clever to begin with. A procedure's busiest variables, up to -five, live in the registers that calls leave alone (`rbx` and `r12` to -`r15`), where nothing but their own assignments can change them. +five, live in registers that calls leave alone: the callee-saved ones +of System V, the calling convention of x86-64 Linux, which a called +procedure must give back as it found them (`rbx` and `r12` to `r15`). +Nothing but their own assignments can change them. The output is a set of *chunks*: one for each procedure, each module variable, each string. Code refers to other chunks through *fixups*, @@ -432,23 +437,28 @@ instruction. The stack: `stack` notes where each value is, a constant (`lConst`), an -address not yet computed (`lAdr`, `AdrMem`'s operand), in its register -(`lReg`) or in a frame slot (`lFrame`); `owner` which +address not yet computed (`lAdr`, `AdrMem`'s operand), a register +variable's own register, read in place (`lHeld`), the value's own +register (`lReg`) or a frame slot (`lFrame`); `owner` says which value each register holds. The value at depth `d` belongs in `Regs[d mod 4]`, `r8` to `r11`: `rax`, `rdx` and `rcx`, which division and shifts need, and `rsi` and `rdi`, which copying needs, aren't among -them. `Claim` gives a value its register, and `Spill`s a deeper one +them. `Claim` gives a value its register, and `Spill`s the lower one that holds it, when an expression is deeper than the registers; `Loaded` brings a value into its register, from its constant, address -or slot; `Place` uses a noted address as the operand itself, and -`PopVar` and `IncDec` an operand of memory and a constant, so `DEC(n)` -is `sub qword [rbp - 8], 1`; `Top` is `Loaded` for the value on top, and `Target` the -register a new one is computed in. Before a call every value in a -register is spilled (`SpillBelow`), since the call may change them, and -so are the values under a comparison that jumps out of an expression -(`JumpOut`), which both ways to its label must find in the same place. `pushed` counts what -is on the machine's stack, which a call must align: the return -address, in a deferred statement. `Op` takes a +or slot; `Place` uses a noted address as the operand itself, so that +`PopVar`, storing a constant, and `IncDec` are one instruction on +memory: `DEC(n)` is `sub qword [rbp - 8], 1`. `Top` is `Loaded` for the +value on top, and `Target` the register a new one is computed in. +`Drop` emits no code, and the dropped value's register still holds it +until the next push, which several routines rely on. Before a call every +value in a register is spilled (`SpillBelow`), since the call may change +them, and so are the values under a comparison that jumps out of an +expression (`JumpOut`), which both ways to its label must find in the +same place. `pushed` counts the quadwords on the machine's stack. A +call needs `rsp` a multiple of 16, so `Call` pads by one quadword when +`pushed` plus its stack arguments is odd; in a deferred statement +`pushed` starts at 1, for the return address. `Op` takes a constant on the right as it is, after moving one on the left of `+`, `*`, `&`, `|` or `xor` there, and a power of two on the right of `*`, `div` or `mod` becomes shifts (`DivPow2`), since `idiv` is slow; an @@ -497,9 +507,12 @@ `sym.pas`), comes back in rax and rdx, as System V returns a struct of two integers: `return` leaves both on the stack for `ReturnJump`. `Call` leaves two results on the stack, and stores a slice in a -temporary of the caller's. Any other record or -several results come back through a hidden pointer in `rdi`, as C's -structs do (`BehindPointer`, `ResultTo`, `CopyResult`). +temporary of the caller's. Any other record, or +several results, come back in memory the caller provides, through a +hidden pointer in `rdi` (`BehindPointer`, `ResultTo`, `CopyResult`). C +returns a struct of up to 16 bytes in `rax` and `rdx`; raz sends every +record through memory, and only a slice or two single values in +registers. Frames: `BeginProc` gives the parameters their slots; `EnterBody` writes the prologue, which zeroes the locals in memory (with a few @@ -515,8 +528,9 @@ in a register has no slot of its own. Gen saves the registers in slots a quadword each, after the locals and not zeroed, as each is written first. The -prologue saves them, zeroes them, and takes a parameter's value from -where it came; the epilogue restores them. A variable in one is an +prologue saves them, zeroes them, and moves a parameter into its +register from the register or stack slot it arrived in; the epilogue +restores them. A variable in one is an item at `bReg`: `PushVar` notes it (`lHeld`) rather than copying it, `Peek` reads it in place where the value is only read, so `i < n` is `cmp rbx, r12`, and `PopVar` and `IncDecReg` write it. Rt finds the @@ -708,7 +722,8 @@ **Register variables.** One pass can't know whether a variable's address will be taken before its code is made, so `ChooseRegs` reads the body ahead, as `InstancesFor` does, and counts each variable's -uses: 1 for each, 4 in a loop, 16 in two; one `ADR` takes is out. The +uses: 1 for each, 4 in a loop, 16 in two, at most 64 (loops nested three +deep or more); one `ADR` takes is out. The five busiest used at least three times get registers (`o^.reg`). An address wanted after all, by a `var` parameter, say, comes to `Address` (`item.pas`), which puts the variable back in memory and diff --git a/src/gen.pas b/src/gen.pas index 9f41b3d..a5d93a3 100644 --- a/src/gen.pas +++ b/src/gen.pas @@ -9,19 +9,30 @@ code for those calls, and nothing above it knows the machine: a port is a new gen.pas, with an encoder of its own. - The stack is kept in registers, as in Wirth's compilers: the value at - depth d in r8 to r11, register d mod 4, a deeper one's register taken - by spilling the shallower value it held to the frame. A constant, or - an address in the frame or of a chunk, is only noted until something - needs it in a register, so that it can be an instruction's operand. + The stack is kept in registers, as in Wirth's compilers (Niklaus + Wirth's Pascal and Oberon compilers): the value at depth d, depth 0 + being the bottom, is in r8 to r11, register d mod 4. A value that + needs a register a lower one holds spills that one: stores it in a + frame slot, to free the register. A constant, or an address in the + frame or of a chunk, is only noted until something needs it in a + register, so that it can be an instruction's operand. - Calls use the System V convention. Arguments are computed left to - right onto the stack, and moved into their registers just before the - call: a call in a later argument spills the earlier ones, as any call - spills the values under it, so that it can't disturb them. A slice goes as its two words, as System V passes a - 16-byte struct of two integers; a record, array or variant passed by - value goes as the address of a copy the caller makes; one returned goes through a hidden pointer, as C's - structs do, and so do several results. + A slice is two words, a pointer and then a length. + + Calls use the System V convention, which x86-64 Linux has for C: + arguments in rdi, rsi, rdx, rcx, r8, r9 and xmm0 to xmm7, the rest on + the machine's stack; rbx, rbp and r12 to r15 are callee-saved, which + is to say a called procedure gives them back as it found them. The + arguments are computed left to right onto the stack of values, and + moved into their registers just before the call: a call in a later + argument spills the earlier ones, as any call spills the values under + it, so that it can't disturb them. A slice goes as its two words, as + System V passes a 16-byte struct of two integers; a record, array or + variant passed by value goes as the address of a copy the caller + makes. A slice, or two results that are single values, come back in + rax and rdx (InTwoRegs); any other record, or several results, comes + back in memory the caller provides, through a hidden pointer + (BehindPointer), where C would send a small struct back in registers. A procedure's frame holds its parameters, its variables, and the temporaries of the statement running. The variables are zeroed on @@ -80,7 +91,7 @@ const { the registers a procedure keeps its busiest variables in: System V's - callee-saved ones, so they live through calls; a procedure saves + callee-saved ones, so they live through calls (a register variable); a procedure saves those it uses, and Rt finds them there for the trap report } VarRegs: array[0..4] of longint = (RBX, R12, R13, R14, R15); @@ -174,8 +185,9 @@ type { where a value on the stack is } TLoc = (lConst, { not loaded: val is the value } - lHeld, { not loaded: in register val, a variable's own, - which nothing in an expression can change } + lHeld, { not loaded: in register val, a register + variable's own (see VarRegs), read in place, which + nothing in an expression can change } lAdr, { not loaded: the address of chunk, or of the frame if chunk is -1, plus val } lReg, { in its register } @@ -183,8 +195,9 @@ TEntry = record loc: TLoc; - val: int64; - chunk: longint; + val: int64; { lConst: the value; lHeld: the register; lAdr: the + offset; lFrame: the frame slot } + chunk: longint; { lAdr: the chunk, or -1 for the frame } k: TKind; end; @@ -214,7 +227,7 @@ inObj: array[0..13] of PObj; numIn: longint; procParams: PObj; { the parameters, for EnterBody } - regMask: longint; { the registers of variables, as bits of VarRegs } + regMask: longint; { the registers of variables: bit i is VarRegs[i] } saveAt: int64; { where they are saved, a quadword each } frameAt: array[0..2] of int64; { frameTop, frameMax, permTop after the declarations } { the checks of the procedure, whose failures EndFails makes } @@ -234,10 +247,20 @@ end; { The stack, as in Wirth's compilers: the value at depth d is held in - register d, for as many registers as there are. A value deeper than - that, when its register is wanted, and every value in a register - when a call would clobber them, is spilled to a frame slot, and loaded - again where it is used. A constant is only noted. } + register d mod NumRegs. A value, when a higher one wants its register, + and every value in a register when a call would clobber them, is + spilled to a frame slot, and loaded again where it is used. A constant + is only noted. + + Drop emits no code, and a dropped value's register still holds it + until the next push claims it: Place (for bStack), Operands, + IndexSlice and JumpCmp read a register after dropping its value. + + Registers outside the stack, free within one operation: rax, rcx and + rdx for arithmetic; rsi and rdi for copying; and, where the stack holds + nothing in them, r10 for the prologue's zeroing loop and r11 for a call + through a procedure value. Reals are kept as their bits in the integer + registers, and moved to xmm0 and xmm1 for each operation (RealOp). } function RegOf(i: longint): longint; begin @@ -263,7 +286,7 @@ if (owner[r] >= 0) and (owner[r] < d) then Spill(owner[r]); end; -{ The register of value i, for it to hold: a deeper value in it is +{ The register of value i, for it to hold: a lower value in it is spilled. } function Claim(i: longint): longint; var r: longint; @@ -402,21 +425,25 @@ Drop; Place := Mem(ra, a.off) end; - else + else { bSlot: the address is in the frame slot a.chunk } Load(r, Mem(RBP, a.chunk), 8, false); Place := Mem(r, a.off); end; end; +{ The address a names, on top of the stack } procedure PushAdr(const a: TAdr); var m: TMem; r: longint; begin - if (a.base = bStack) and (a.off = 0) then exit; + if (a.base = bStack) and (a.off = 0) then exit; { it is on top already } if a.base in [bFrame, bGlobal] then begin NewEntry(kWord, lAdr, a.off); if a.base = bGlobal then stack[depth - 1].chunk := a.chunk; exit; end; + { The order matters. With the address on the stack, Place pops it and + must come first, so that Target may reuse its register; otherwise + Target comes first, since Place may need r to load a slot's pointer. } if a.base = bStack then begin m := Place(a, -1); r := Target end else begin r := Target; m := Place(a, r) end; Lea(r, m); @@ -430,6 +457,7 @@ NewEntry(k, lHeld, a.chunk); exit; end; + { in the order PushAdr explains } if a.base = bStack then begin m := Place(a, -1); r := Target end else begin r := Target; m := Place(a, r) end; Load(r, m, size, signed); @@ -539,6 +567,7 @@ { Operations } +{ n if v is 2^n, which is 0 for 1; -1 if v isn't a power of two } function ExactLog2(v: int64): longint; var n: longint; begin @@ -569,11 +598,16 @@ zero, so a negative dividend first gets 2^k - 1 added (the bias). } procedure DivPow2(op: TSym; r, k: longint; unsign: boolean); begin + { unsigned: div shifts right; mod keeps the low k bits, by shifting + them up to the top and back down } if unsign then begin if op = sDiv then ShiftI(shShr, r, k) else begin ShiftI(shShl, r, 64 - k); ShiftI(shShr, r, 64 - k) end; exit; end; + { signed: sar 63 makes the sign into all ones or all zeros, and shr + 64 - k keeps k of them, the bias 2^k - 1 or 0; with it added, sar k + rounds towards zero. The remainder is r less the quotient times 2^k. } MovRR(RCX, r); ShiftI(shSar, RCX, 63); ShiftI(shShr, RCX, 64 - k); @@ -618,10 +652,10 @@ MovqXR(0, r); MovqXR(1, y); case op of - sPlus: Sse($58, 0, 1, f); - sMinus: Sse($5C, 0, 1, f); - sTimes: Sse($59, 0, 1, f); - sSlash: Sse($5E, 0, 1, f); + sPlus: Sse($58, 0, 1, f); { addsd, or addss for an F32 } + sMinus: Sse($5C, 0, 1, f); { subsd, subss } + sTimes: Sse($59, 0, 1, f); { mulsd, mulss } + sSlash: Sse($5E, 0, 1, f); { divsd, divss } end; MovqRX(r, 0); end; @@ -672,10 +706,12 @@ sTimes: Imul(r, y); sDiv, sMod: begin MovRR(RAX, r); - if not signed then begin MovRI(RDX, 0); Unary(6, y) end + if not signed then begin MovRI(RDX, 0); Unary(6, y) end { div } else begin + { only -1 can make the division overflow, so a constant + divisor other than -1 needs no check } if (bits < 64) and (not c or (v = -1)) then DivTrap(bits, y); - Cqo; Unary(7, y) + Cqo; Unary(7, y) { idiv, of rdx:rax, which cqo made from rax } end; if op = sDiv then MovRR(r, RAX) else MovRR(r, RDX); end; @@ -704,6 +740,12 @@ r := Operands(y); MovqXR(0, r); MovqXR(1, y); + { ucomis sets the flags as an unsigned comparison would, but for an + unordered pair (a NaN) it sets zero, parity and carry all. So only + "above" can be tested straight: it is false for NaN, as every + comparison but <> must be. a < b is made b > a. = also asks for + no parity, as NaN = NaN sets the zero flag, and <> asks for + parity as well. } case op of sEql: begin Ucomis(0, 1, f); SetCC(ccE, r); SetCC(ccNP, RCX); Alu(aluAnd, r, RCX) end; sNeq: begin Ucomis(0, 1, f); SetCC(ccNE, r); SetCC(ccP, RCX); Alu(aluOr, r, RCX) end; @@ -728,7 +770,7 @@ kF32: Btc(r, 31); kF64: Btc(r, 63); else - Unary(3, r); + Unary(3, r); { neg } if size < 8 then Extend(r, size, signed); end; end; @@ -737,7 +779,7 @@ var r: longint; begin r := Top; - Unary(2, r); + Unary(2, r); { not } if size < 8 then Extend(r, size, signed); end; @@ -775,7 +817,7 @@ AluI(aluAnd, r, 1); Alu(aluOr, RCX, r); Cvtsi2s(0, RCX, f); - Sse($58, 0, 0, f); + Sse($58, 0, 0, f); { adds it to itself: doubles } FixLink(L2); end else Cvtsi2s(0, r, f); MovqRX(r, 0); @@ -798,14 +840,15 @@ begin r := Top; MovqXR(0, r); - Sse($5A, 0, 0, k = kF32); + Sse($5A, 0, 0, k = kF32); { cvtss2sd, or cvtsd2ss } MovqRX(r, 0); if k = kF32 then stack[depth - 1].k := kF64 else stack[depth - 1].k := kF32; end; -{ Whether the slices in the frame at a and b are equal (or not, if not - eq): the lengths, then the bytes, len shl shift of them, compared - right where the comparison stands. } +{ Whether the slices in the frame at a and b (the offsets of their + pointers, the lengths 8 bytes on) are equal (or not, if not eq): the + lengths, then the bytes, len shl shift of them, compared where the + comparison stands. } procedure CompareSeq(a, b: int64; shift: longint; eq: boolean); var differ, r: longint; begin @@ -817,15 +860,18 @@ Load(RSI, Mem(RBP, b), 8, false); Load(RDI, Mem(RBP, a), 8, false); if shift > 0 then ShiftI(shShl, RCX, shift); - Alu(aluCmp, RCX, RCX); { equal, if there are no bytes } + { repe cmpsb with rcx = 0 leaves the flags alone, so make them say + equal first, which is right if there are no bytes } + Alu(aluCmp, RCX, RCX); RepeCmpsb; FixLink(differ); if eq then SetCC(ccE, r) else SetCC(ccNE, r); Computed(kWord); end; -{ An error is the address of its length, followed by its message: pops - one, and makes the slice of its message at tmp, empty for nil. } +{ An error points at its message's length, an 8-byte word, with the + text after it; nil is no error. Pops one, and makes the slice of its + message at tmp, empty for nil. } procedure ErrorText(tmp: int64); var L: longint; begin @@ -893,7 +939,7 @@ var r, n: longint; begin if which = bCas then begin n := Top; Drop end; - PopTo(RAX); + PopTo(RAX); { cmpxchg compares with rax, so CAS's old value goes there } r := Top; case which of bCas: begin LockCmpxchg(Mem(r, 0), n); SetCC(ccE, r) end; @@ -903,8 +949,11 @@ stack[depth - 1].k := kWord; end; -{ The system call and its arguments, n values on the stack; every value - in a register is spilled first, as the arguments go in its registers } +{ The system call and its arguments, n values on the stack. Linux takes + the number in rax and the arguments in rdi, rsi, rdx, r10, r8 and r9, + and the syscall instruction clobbers rcx and r11. Every value in a + register is spilled first, as r8 to r11 are the stack's registers, + and the arguments are loaded from their slots. } procedure SysCall(n: longint); const SysRegs: array[0..6] of longint = (RAX, RDI, RSI, RDX, R10, R8, R9); var i: longint; @@ -960,15 +1009,19 @@ { JumpCmp out of an expression, past code that may spill: the values under the two compared are spilled first, so that they are where the - code after the landing place expects them, whichever way it came. } + code after the landing place expects them, whichever way it came. In + v + (a < b and f(x) = 0), a call to f spills v on the way through, so + v must be in its slot too where a < b jumps past the call. } procedure JumpOut(op: TSym; signed: boolean; var L: longint); begin SpillBelow(depth - 2); JumpCmp(op, signed, L); end; -{ The comparison of the two values on top, unless notOp holds, as a - BOOL; jumps on its false path (fj) and its true one (tj) land as well } +{ The two values on top, compared, as a BOOL: true unless notOp, the + opposite comparison, holds. fj and tj are the chains of jumps, made + earlier by and, or and not, that are taken when the whole condition is + false and when it is true; they land here, on the 0 and the 1. } procedure CondValue(notOp: TSym; signed: boolean; fj, tj: longint); var r, e: longint; begin @@ -984,6 +1037,10 @@ Computed(kWord); end; +{ JumpBack, Fix, FixTo and JoinJumps are gen's names for the encoder's, + so that a port can place jumps its own way. Fix(L) places label L here; + FixTo(L, top) makes every jump on chain L go to the earlier place top; + JoinJumps makes one chain of two. } procedure JumpBack(top: longint); begin JmpBack(top); @@ -1011,14 +1068,18 @@ { The program goes on if the condition cc holds, and otherwise stops in Rt.fail(what, a, b, len, at, name), which says what failed at p, - found by at, the address of the call: an index a (what = 0), a slice - a..b (1), each for a length len, a position a of the enumeration - called name (2), or a slice of a pointer a..b that runs backwards - (3). a is in register ra, b in RDX; len is in memory at m, or n if - m.base is NoBase. The failing code is out of the way, at the + found by at, which a stub works out from where it was called; what is + an index a (0), a slice a..b (1), each for a length len, a position a + of the enumeration called name (2), a slice of a pointer a..b that + runs backwards (3), or a nil pointer (4). Rt.fail knows 5 and 6, a + division fault and a stack overflow, which this machine catches + itself, so no check here has them. The arguments go in rdi, rsi, rdx, + rcx, r8 and r9: a is in register ra, b in RDX; len is in memory at m, + or n if m.base is NoBase. The failing code is out of the way, at the procedure's end (EndFails), so that a check that holds costs a jump - not taken; it has p for its place, never returns, and may use any - register once it has read what it needs. } + not taken; it has p for its place (at is p's offset in the source), + never returns, and may use any register once it has read what it + needs. } procedure Check(cc, what: longint; const p: TPos; ra: longint; const m: TMem; n: int64; name: longint); begin if numFails > High(fails) then Mark('more than ' + IntStr(High(fails) + 1) + ' checks in one procedure'); @@ -1126,6 +1187,8 @@ m := Place(a, RDI); ml := m; ml.disp := ml.disp + 8; if checked then begin + { two checks, both unsigned, so that a negative bound fails too: + hi against the length, then lo against hi } if isArray then begin CmpI(RDX, n); ml := NoMem end else AluM(aluCmp, RDX, ml); Check(ccBE, 1, p, RCX, ml, n, -1); @@ -1142,9 +1205,9 @@ end; { COPY: the elements of the slice in the frame at sOff, of size bytes - each, to the start of the one at dOff, which must be as long, as one - block; backwards when the destination is above the source, so that - an overlap comes out right. } + each, to the start of the one at dOff, which must be at least as long + (the source may be shorter), as one block; backwards when the + destination is above the source, so that an overlap comes out right. } procedure CopySlice(dOff, sOff, size: int64; checked: boolean; const p: TPos); var ml: TMem; L, E: longint; begin @@ -1161,7 +1224,9 @@ Load(RDI, Mem(RBP, dOff), 8, false); Alu(aluCmp, RDI, RSI); L := NoLabel; - Jcc(ccBE, L); + Jcc(ccBE, L); { the destination is not above: forwards, at L } + { backwards: std makes rep movsb run downward, so it starts at the + last byte of each } Lea(RSI, MemIdx(RSI, RCX, 1, -1)); Lea(RDI, MemIdx(RDI, RCX, 1, -1)); Std; @@ -1195,9 +1260,15 @@ { Calls } -{ The call c, its arguments already in their frame slots: they go to - registers or the stack, the procedure is called, and its result, if - any, is pushed on the value stack. } +{ The call c, its c.n arguments the values on top of the stack, in + registers, noted as constants or spilled. They go to registers or the + machine's stack, the procedure is called, and its result, if any, + comes back: one value is pushed, two results are pushed as two values, + a slice or a record is stored in the temporary c.ret. + + ni and nf count the integer and the real registers used so far, k the + arguments on the machine's stack, and pad is 1 when a padding quadword + is needed. } procedure Call(var c: TCall); var @@ -1229,8 +1300,11 @@ end; if onStack[i] then inc(k); end; - { System V wants rsp a multiple of 16 at the call: a quadword of - padding makes the count pushed since the frame began even } + { System V wants rsp a multiple of 16 at the call. A procedure's body + has it so (push rbp, and a frame size that is a multiple of 16), so + a quadword of padding makes the count pushed since even. The stack + arguments go right to left, so that the first is at the lowest + address. } pad := ord(odd(pushed + k)); if pad <> 0 then AluI(aluSub, RSP, 8); for i := c.n - 1 downto 0 do @@ -1242,7 +1316,9 @@ late[4] := -1; late[5] := -1; if (c.ret <> 0) and BehindPointer(res) then begin Lea(RDI, Mem(RBP, c.ret)); ni := 1 end; { rdi, rsi, rdx, rcx and the xmm registers first; r8 and r9 last, as - they may hold arguments still } + they are stack registers and may hold arguments not yet moved: late + is the value for each. The fifth goes through rax, so that writing r8 + doesn't destroy a value still wanted for r9. } for i := 0 to c.n - 1 do if not onStack[i] then if c.isF[i] then begin @@ -1293,6 +1369,9 @@ { Frames } +{ A slot of size bytes in the frame: its offset from rbp, negative, as + the frame grows down. A temporary is released at the end of its + statement (TempMark, ReleaseTemps); AllocPerm's lasts the procedure. } function AllocTemp(size, align: int64): int64; begin if align < 1 then align := 1; @@ -1312,6 +1391,8 @@ TempMark := frameTop; end; +{ The slots allocated since the mark m are free again, but those + AllocPerm made stay } procedure ReleaseTemps(m: int64); begin if m < permTop then m := permTop; @@ -1340,7 +1421,7 @@ resType := sig^.base; procParams := params; regMask := 0; - ni := 0; nf := 0; stackOff := 16; + ni := 0; nf := 0; stackOff := 16; { stackOff: above the saved rbp and the return address } if (resType <> nil) and BehindPointer(resType) then begin retSlot := AllocPerm(8, 8); inReg[0] := RDI; inSlot[0] := retSlot; inSize[0] := 8; inObj[0] := nil; @@ -1348,7 +1429,7 @@ end; p := params; while p <> nil do begin - p^.ind := p^.isVar or IsAggregate(p^.typ) and (p^.typ^.form <> fSlice); + p^.ind := p^.isVar or (IsAggregate(p^.typ) and (p^.typ^.form <> fSlice)); f := (p^.typ^.form = fReal) and not p^.isVar; if (p^.typ^.form = fSlice) and not p^.isVar then begin { its two words, in two registers or both on the stack } @@ -1365,6 +1446,8 @@ end; end else if (f and (nf < 8)) or (not f and (ni < 6)) then begin p^.val := AllocPerm(8, 8); + { a real's register, xmm nf, is told from an integer register by + a negative number (EnterBody decodes it) } if f then begin inReg[numIn] := -1 - nf; inc(nf) end else begin inReg[numIn] := IntRegs[ni]; inc(ni) end; inSlot[numIn] := p^.val; @@ -1434,22 +1517,25 @@ Push(RBP); MovRR(RBP, RSP); Say('sub rsp, frame'); - Put1($48); Put1($81); Put1($EC); { sub rsp, imm32 } + { sub rsp, imm32: always the form with a 32-bit field, so that EndProc + can patch the frame's size in } + Put1($48); Put1($81); Put1($EC); frameFix := pc; Put4(0); n := (AlignUp(zeroTop, 8) - paramTop) div 8; if n > 0 then MovRI(RAX, 0); if n <= 4 then for i := 1 to n do Store(Mem(RBP, -paramTop - 8 * i), RAX, 8) else begin - { a quadword at a time: r10 counts up to zero } + { a quadword at a time: r10 runs from -n up to 0, and the store's + address is scaled by it } MovRI(R10, -n); top := pc; Store(MemIdx(RBP, R10, 8, -paramTop), RAX, 8); AluI(aluAdd, R10, 1); JccBack(ccNE, top); end; - { the registers of variables: saved, as a variable starts at zero, - a parameter taken from where it came } + { each register that holds a variable is saved, for the caller, and + zeroed, as a variable starts at zero } chunks^[c].saveMask := regMask; chunks^[c].saveAt := saveAt; n := 0; @@ -1459,12 +1545,16 @@ MovRI(VarRegs[i], 0); inc(n); end; + { the parameters that came in registers, to their slots or, for a + register variable, to its register } for i := 0 to numIn - 1 do if inReg[i] < 0 then MovsdMX(Mem(RBP, inSlot[i]), -1 - inReg[i]) else if (inObj[i] <> nil) and (inObj[i]^.reg <> 0) then begin MovRR(inObj[i]^.reg, inReg[i]); if inSize[i] < 8 then Extend(inObj[i]^.reg, inSize[i], inObj[i]^.typ^.signed); end else Store(Mem(RBP, inSlot[i]), inReg[i], inSize[i]); + { a register variable's parameter that came on the stack, above the + frame (val > 0), is loaded from there } p := procParams; while p <> nil do begin if (p^.reg <> 0) and (p^.val > 0) then @@ -1555,7 +1645,8 @@ end; { A deferred statement is compiled where it stands, as a subroutine of - its procedure that the code jumps over; DeferBegin gives its address + its procedure that the code jumps over, in the procedure's own frame + (the same rbp), so that it sees all its variables; DeferBegin gives its address and starts it, with the return address pushed. The stack is empty where it is called, and where it begins. } function DeferBegin(var L, saved: longint): longint; @@ -1584,7 +1675,13 @@ main; and ends with Rt.exit, its status main's or 0. A dynamic program starts as C's crt1 does, through __libc_start_main(main, argc, argv, nil, nil, rtld_fini, stack_end), with rsp aligned; its main first - gives Rt C's exit, in cExit. } + gives Rt C's exit, in cExit. + + dynamic: the program uses C. first: the first module, whose chain + gives the order of the bodies. main: the program's main procedure, or + nil. cExit, placesVar and exitProc: the chunks of Rt's cExit, places + and exit. places: the chunk the linker fills with the places (the + address of each line of code, for Rt to say where a check failed). } function EntryPoint(dynamic: boolean; first: PModule; main: PObj; cExit, places, placesVar, exitProc: longint): longint; var entry, start, i: longint; m: PModule; begin @@ -1592,18 +1689,20 @@ if dynamic then begin start := NewChunk(secText, -1, Intern('main', 4)); BeginChunk(entry); - MovRI(RBP, 0); - MovRR(R9, RDX); - Pop(RSI); - MovRR(RDX, RSP); + { at the start rdx holds rtld_fini, from the dynamic loader, and the + stack argc, then argv } + MovRI(RBP, 0); { no frame above, where a trace stops } + MovRR(R9, RDX); { rtld_fini, the sixth argument } + Pop(RSI); { argc, the second } + MovRR(RDX, RSP); { argv, the third } AluI(aluAnd, RSP, -16); - Push(RAX); - Push(RSP); - MovRI(R8, 0); + Push(RAX); { padding, so that the next push, the seventh } + Push(RSP); { argument, stack_end, leaves rsp aligned } + MovRI(R8, 0); { fini and init: none } MovRI(RCX, 0); - Lea(RDI, MemRip(start, 0)); + Lea(RDI, MemRip(start, 0)); { main, the first argument } CallM(MemRip(ExternChunk(Intern('__libc_start_main', 17)), 0)); - Ud2; + Ud2; { it never returns } EndChunk(entry); BeginChunk(start); Push(RBP); { aligns the stack again } @@ -1629,10 +1728,13 @@ if main <> nil then CallChunk(main^.chunk); if (main <> nil) and (main^.typ^.base <> nil) then MovRR(RDI, RAX) else MovRI(RDI, 0); CallChunk(exitProc); - Ud2; + Ud2; { exit never returns: trap if it does } EndChunk(start); { Rt.fail, for the failures of each kind: the place is where the - check's call is, a byte before where it would return to } + check's call is. The return address is the next instruction's, which + may belong to another line; one byte back is inside the call, so the + lookup finds the call's line. rsp is aligned for the call, as the + check's code may have pushed an odd number of quadwords. } for i := 0 to High(failStubs) do if failStubs[i] >= 0 then begin BeginChunk(failStubs[i]); diff --git a/src/item.pas b/src/item.pas index f052432..ad42fd3 100644 --- a/src/item.pas +++ b/src/item.pas @@ -30,8 +30,10 @@ the stack, not yet made, as Wirth's compilers keep a condition } relSigned: boolean; - fj, tj: longint; { mCond: the jumps taken where it is false, and - where it is true, to land past it } + fj, tj: longint; { mCond: the chains of jumps already made that are + taken when the whole condition is false, and when + it is true, not yet given a place (and, or and + not make them); see gen's JumpOut } val: int64; { mConst: the value, an F64's bits; mStr: its length } base: TBase; { mVar: what the address is relative to } chunk: longint; { mVar with bGlobal, mStr: the chunk; bSlot: the slot } @@ -48,7 +50,8 @@ end; var - demoted: boolean; { Address wanted a register variable's address } + demoted: boolean; { Address wanted a register variable's address: its + procedure is compiled again, the variable in memory } checks: boolean; { the module's index and slice checks are made: it doesn't say check off } @@ -412,12 +415,14 @@ { Copying } +{ x, copied to a temporary } procedure CopyToTemp(var x: TItem); var t: int64; f, g: PObj; begin if x.vol then MarkAt(x.pos, 'can''t copy through a volatile pointer'); t := AllocTemp(x.typ^.size, x.typ^.align); if x.mode = mWords then begin + { the second result is on top, so it is popped first } f := x.typ^.fields; g := f^.next; PopVar(FrameAdr(t + g^.val), ScalarSize(g^.typ)); PopVar(FrameAdr(t + f^.val), ScalarSize(f^.typ)); @@ -1157,6 +1162,8 @@ var adr: TAdr; f: PObj; begin if x.mode = mWords then exit; { there already } + { copied to a temporary unless its two words are in memory at a place + that a later argument can't change } if (x.mode <> mVar) or x.vol or not (x.base in [bFrame, bGlobal, bSlot]) then CopyToTemp(x); adr := AdrOf(x); if x.typ^.form = fSlice then begin @@ -1223,6 +1230,9 @@ c.param := p^.next; end; +{ The call c made, with x its result as an item: none; a temporary, for a + slice or a record; two results on gen's stack (mWords); else one value + on the stack. } procedure EndCall(var c: TCall; var x: TItem); var res: PType; begin @@ -1343,15 +1353,17 @@ JumpCmp(op, o^.typ^.signed, L); end; -{ The end of a round of a for loop, as the report has it for a positive - step s: if v <= b and b - v < s, the loop ends; otherwise v becomes +{ The end of a round of a for loop, for a positive step s, as the report + has it: if v <= b and b - v < s, the loop ends; otherwise v becomes v + s and the loop goes on while v <= b. Counting the distance left, rather than comparing after the step, can't be fooled by v wrapping - around. So the loop goes on, to top, where v is stepped, if v < b for - a step of 1, or if v <= b and b - v >= s for another: then v + s <= b - needs no test. It ends if v = b, or b - v < s. Only where the body has - put v past b is it stepped here and tested, past. A negative step is - the same the other way round. } + around. A negative step is the same the other way round: Before, Past + and Within are indexed by up, whether the step is positive. + For a step of 1: v < b goes on to top, where v is stepped; v = b + ends; otherwise the body moved v past b. + For another step: v past b goes to past; else b - v (unsigned, as + v <= b) >= |step| goes on to top, and else the loop ends. + Past: v is stepped here and tested, going to body if within b. } procedure ForNext(o: PObj; const lim: TItem; step: int64; var exitL: longint; top, body: longint); const Before: array[boolean] of TSym = (sGtr, sLss); { by a negative step, by a positive } @@ -1385,6 +1397,8 @@ FixTo(L, body); end; +{ Jumps to L if the condition x is false. The jumps waiting in x.fj join + L; those in x.tj are placed here, as x is true past this. } procedure CondJump(var x: TItem; var L: longint); begin if x.typ^.form <> fBool then MarkAt(x.pos, 'a condition is a BOOL, found ' + What(x)); @@ -1398,7 +1412,8 @@ JumpIf(L, false); end; -{ As CondJump, but the jump is taken where the condition holds } +{ As CondJump, but the jump to L is taken where the condition is true; + x.tj joins L and x.fj is placed here } procedure CondJumpTrue(var x: TItem; var L: longint); begin if x.typ^.form <> fBool then MarkAt(x.pos, 'a condition is a BOOL, found ' + What(x)); diff --git a/src/parse.pas b/src/parse.pas index 5ec5446..ae5c2c8 100644 --- a/src/parse.pas +++ b/src/parse.pas @@ -1217,7 +1217,8 @@ end; { Whether what follows "then" is a lone "break;", with no deferred - statement to run on the way out of the loop } + statement to run on the way out of the loop: the break must be the + branch's last statement, so ";" and then end, elsif or else follow. } function LoneBreak: boolean; var st: TScanState; begin @@ -1238,11 +1239,11 @@ procedure ThenPart(var x: TItem; var L: longint); begin Expect(sThen); - L := NoLabel; + L := NoLabel; { stays so with a lone break: there is nothing to skip } if LoneBreak then begin - NoteLine(CurLine, CurCol); + NoteLine(CurLine, CurCol); { the jump gets the break's line } CondJumpTrue(x, curLoop^.brk); - Next; Next; { break; } + Next; Next; { skip "break" and ";" } ends := true; end else begin CondJump(x, L); @@ -1250,8 +1251,10 @@ end; end; -{ A branch that ends, in return or break, needs no jump past the - others. } +{ if, elsif and else: each condition's jump skips its branch to the + next; each branch that doesn't end jumps to the end. A branch that + ends, in return or break, needs no jump past the others, and all of + them ending is told to the caller in the global ends. } procedure IfStatement(const start: TPos; ind: longint); var x: TItem; L, endL: longint; all: boolean; begin @@ -1548,7 +1551,8 @@ end; { a, b := f(x): the variables first, left to right, then the call; - then each result to its variable, in order. } + then each result to its variable, in order. x is the first variable, + first its name, blank whether it is _. } procedure MultiAssign(var x: TItem; first: longint; blank: boolean); var d: array[0..15] of TItem; dn: array[0..15] of longint; blanks: array[0..15] of boolean; @@ -1562,7 +1566,7 @@ if not blanks[n] then begin NotReadOnly(d[n]); Assignable(d[n], dn[n]); - Pin(d[n]); + Pin(d[n]); { works out the address now, so that the call can't change it } end; inc(n); if tok <> sComma then break; @@ -1833,8 +1837,8 @@ { Puts the busiest variables of the procedure, whose parameters are params and whose locals follow before, in registers: read ahead from - its "begin" to its end, a use counts 1, in a loop 4, in two 16, and - a variable ADR is taken of can't have one. A register costs a save + its "begin" to its end, a use counts 1, in a loop 4, in two 16, in + three or more 64, and a variable ADR is taken of can't have one. A register costs a save and a restore, so a variable used less than three times keeps its place in memory. } procedure ChooseRegs(params, before: PObj); @@ -1882,17 +1886,21 @@ if id = nameAdr then begin Next; if tok = sLparen then Next; + { a hugely negative weight bars it from a register, whatever + its uses add } if (tok = sIdent) and (Candidate(id) >= 0) then weight[Candidate(id)] := low(longint) div 2; end else if not afterDot and (Candidate(id) >= 0) then begin k := Candidate(id); if loops > 2 then inc(weight[k], 64) else inc(weight[k], 1 shl (2 * loops)); end; end; - afterDot := tok = sPeriod; + afterDot := tok = sPeriod; { a name after a dot is a field, not a variable } if (d > 0) and (tok <> sEof) then Next; until (d = 0) or (tok = sEof); RestoreScan(st); skipping := wasSkipping; + { the five heaviest, each used at least three times, take the + registers in turn } for k := 0 to 4 do begin best := -1; for i := 0 to n - 1 do diff --git a/src/sym.pas b/src/sym.pas index 0ca538a..f6f61e5 100644 --- a/src/sym.pas +++ b/src/sym.pas @@ -411,9 +411,10 @@ InTwoRegs := t^.tuple and (t^.len = 2) and OneWord(t^.fields) and OneWord(t^.fields^.next); end; -{ Whether a procedure's result t comes back in the caller's memory, in - a place a hidden pointer, passed first, says: any result that is - neither one value, in rax or xmm0, nor two words, in rax and rdx. } +{ Whether a procedure's result t comes back in memory the caller + provides, whose address the caller passes as a hidden first argument, + in rdi: any result that is neither one value, in rax or xmm0, nor two + words, in rax and rdx. } function BehindPointer(t: PType): boolean; begin BehindPointer := IsAggregate(t) and not InTwoRegs(t); diff --git a/src/x64.pas b/src/x64.pas index 3adaad5..4a2c5ab 100644 --- a/src/x64.pas +++ b/src/x64.pas @@ -709,9 +709,12 @@ { If the last instruction made is a jmp to L, it is taken back, since L is to be placed just after it: a return at the end of a procedure - needn't jump to the code that returns. The caller must place L next, - before anything can have noted where the jmp ended. A jcc's field - follows the bytes 0F 8x, never E9. } + needn't jump to the code that returns. L is the place of the latest + jump's 4-byte field, so the last instruction is that jump when L is + 4 bytes back and an E9 byte (jmp) is before it; a jcc's field follows + the bytes 0F 8x, never E9. L then becomes the next jump on the chain, + which the field held. The caller must place L next, before anything + can have noted where the jmp ended. } procedure DropJumpTo(var L: longint); begin if (L = NoLabel) or (L <> pc - 4) or (code^[L - 1] <> $E9) then exit;