From 6d1c72190d14a67855098c6ccf7c6b6677d86ccf Mon Sep 17 00:00:00 2001 From: Luis <42945842+ldiaz94@users.noreply.github.com> Date: Sun, 15 Nov 2026 15:59:31 +0000 Subject: [PATCH] src: Gen.x86_64, Exe.linux and Host.linux, the target's units; src/cross.sh PLAN.md 5, step 3. A second target's files go beside these, chosen by section 3's suffixes in src/ as in lib/. Elf is Exe, the executable, and its writeElf is write. The target's name comes from Gen.Arch and Exe.Os (Parse.setTarget), no longer a fixed list. -S's listing goes through Gen, so only Gen knows X64. src/cross.sh stages a compiler for another target. What the compiler makes is unchanged: 202 programs compared byte for byte with HEAD's; the fixpoint holds. --- diff --git a/CLAUDE.md b/CLAUDE.md index 477330a..88b7d65 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -208,7 +208,8 @@ written in it. A name that is taken is renamed, and nothing is said of it. -The parser reaches the machine only through `Gen.raz`. Keep +The parser reaches the machine only through `Gen` (`src/Gen.x86_64.raz`), +and the executable's format only through `Exe` (`src/Exe.linux.raz`). Keep `doc/compiler.md`'s table of lines and its routine names true when the compiler changes. diff --git a/PLAN.md b/PLAN.md index b05d525..893b2b2 100644 --- a/PLAN.md +++ b/PLAN.md @@ -158,14 +158,14 @@ it and changes no language (section 3, appendix A). **The shape.** `Gen` is the only unit that knows the machine, and -`Elf` the only one that knows the executable, so the port is new +`Exe` (`Exe.linux.raz`, once `Elf`) the only one that knows the executable, so the port is new units beside them, not a change to `Parse` or `Item`: - `A64.raz`, beside `X64.raz`: arm64's instructions encoded, branches within a procedure, and the assembler for code procedures (Arm's syntax, the instructions the library's code procedures use; `db` for any other). -- `Gen.arm64.raz`, beside `Gen.raz` (to be `Gen.x86_64.raz`): the same +- `Gen.arm64.raz`, beside `Gen.x86_64.raz`: the same calls, the stack machine kept in arm64's registers; Apple's calling convention (x18 never touched, a frame record in x29, the arguments past a variadic C procedure's own on the stack); every address by @@ -176,7 +176,7 @@ program (arm64's `sdiv` gives 0), so it is checked; a real out of an `I64`'s range, or a NaN, gives the smallest `I64` (arm64's `fcvtzs` saturates), so it is mended after. -- `MachO.raz`, beside `Elf.raz`: a Mach-O executable for dyld, linked +- `Exe.darwin.raz`, beside `Exe.linux.raz`: a Mach-O executable for dyld, linked to libSystem, as every macOS program must be; C's symbols bound into a table of quadwords, as GLOB_DAT does now; every address in data rebased, since the program is position-independent; its symbol table @@ -187,7 +187,7 @@ `_NSGetExecutablePath`, C always, a program run from a file written and made executable (no `memfd_create`). - `Link`: the places in data that hold an address, listed for - `MachO`'s rebasing. + `Exe.darwin.raz`'s rebasing. A compiler compiles for the system it runs on, as now: its target is the one it was built for, its back end and executable chosen at its @@ -217,13 +217,14 @@ the budget raised to 18,000 in `CLAUDE.md` and `doc/compiler.md`, and the Makefile and scripts made to run on BSD's tools as on GNU's (`sed -i`, `stat`, `sha256sum`). -3. `Gen.raz` to `Gen.x86_64.raz`, `Elf` behind a unit of the target's - (`Exe`), `src/cross.sh`: Linux's compiler unchanged, byte for byte. +3. Done. `Gen.raz` to `Gen.x86_64.raz`, `Elf.raz` to `Exe.linux.raz` (the + unit `Exe`), `Host.raz` to `Host.linux.raz`, `src/cross.sh`: what + Linux's compiler makes unchanged, byte for byte. 4. `A64.raz`, its encoder checked against `llvm-mc`'s bytes. 5. `Gen.arm64.raz`, in pieces: values and operations; jumps and checks; calls and frames; reals; atomics, deferred statements, the entry point. -6. `MachO.raz` and `Link`'s rebases, its line numbers for lldb; +6. `Exe.darwin.raz` and `Link`'s rebases, its line numbers for lldb; `Host.darwin.raz`. 7. The library: `CAbi`, `Sys`, `Rt`, `Thread`, `Bytes`, `Math`, `Str`. 8. `test/` and `conform/` passing on the Mac; what differs by target @@ -242,10 +243,10 @@ d. The port is v0.26.0; the clean-up and 1.0 move one on. e. Line numbers for lldb are in v0.26.0 (below). -**Line numbers on the Mac.** `Elf` writes DWARF 4 already: the line +**Line numbers on the Mac.** `Exe.linux.raz` writes DWARF 4 already: the line table `makeLines` makes, target-blind, and the one compile unit `putDebug` writes. lldb reads DWARF from an executable's `__DWARF` -segment, as it does Go's, so `MachO` writes the same three sections, +segment, as it does Go's, so `Exe.darwin.raz` writes the same three sections, `__debug_line`, `__debug_info` and `__debug_abbrev`, there, unloaded, before `__LINKEDIT`; `make gdb`'s twin drives `lldb --batch`. About 50 lines, `makeLines` and `putDebug` shared by the two writers. diff --git a/doc/compiler.md b/doc/compiler.md index b924f1b..e5d3e7b 100644 --- a/doc/compiler.md +++ b/doc/compiler.md @@ -1,6 +1,6 @@ # Reading the raz compiler -The compiler is twelve files of raz, about 13,100 lines of code (the +The compiler is twelve files of raz, about 13,200 lines of code (the budget is 18,000). It is its own compiler: a release of it, the one `BOOT` names, builds `src/`, and `make fixpoint` checks that what it makes makes itself again, byte for byte. Each release was built by the @@ -21,13 +21,13 @@ | `src/Sym.raz` | 866 | 689 | Types, objects, scopes, layout | | `src/Chunk.raz` | 364 | 280 | The compiled program: chunks, fixups, line notes | | `src/X64.raz` | 1,777 | 1,450 | The instruction encoder, jumps within a procedure, the assembler | -| `src/Gen.raz` | 2,846 | 1,989 | The stack machine, for x86-64: values, operations, checks, calls, frames | +| `src/Gen.x86_64.raz` | 2,860 | 1,998 | The stack machine, for x86-64: values, operations, checks, calls, frames | | `src/Item.raz` | 2,553 | 2,051 | Items: types, constants, variables, operators, conversions, calls | -| `src/Parse.raz` | 4,922 | 4,179 | Declarations, statements, expressions, built-ins, recovery, warnings | +| `src/Parse.raz` | 4,938 | 4,191 | Declarations, statements, expressions, built-ins, recovery, warnings | | `src/Link.raz` | 411 | 317 | Tree shaking, layout, patching, the places | -| `src/Elf.raz` | 450 | 356 | Static and dynamic ELF, symbol table, line numbers | -| `src/Host.raz` | 103 | 52 | The system running the compiler | -| `src/Raz.raz` | 492 | 384 | The command line, and `-q` for an editor | +| `src/Exe.linux.raz` | 455 | 358 | The executable, ELF: static and dynamic, symbol table, line numbers | +| `src/Host.linux.raz` | 103 | 52 | The system running the compiler | +| `src/Raz.raz` | 493 | 385 | The command line, and `-q` for an editor | Every file opens with a comment that says what it is, what it depends on and what it leaves out. Read those first; they are the map. @@ -46,12 +46,18 @@ knows what the program means: each operand is an *item*, as in Wirth's compilers, and the routines there check the items' types, fold constants and work out where variables are. Neither knows the machine: -they drive a stack machine, `Gen.raz`, by its calls (push a value, +they drive a stack machine, `Gen.x86_64.raz`, by its calls (push a value, add the two on top, store the top in a variable, jump if it is false), each with the kind of the value (a word, a 64-bit integer, an `F32`, -an `F64`). `Gen.raz` is the only one that knows x86-64; a port to -another machine is a new `Gen.raz`, with an encoder of its own in place -of `X64.raz`. +an `F64`). `Gen` is the only one that knows x86-64; a port to +another machine is a new `Gen`, with an encoder of its own in place +of `X64.raz`. Likewise `Exe` is the only one that knows the executable's +format, and `Host` the host's services. Each is a unit with a file per +target, which the suffixes of the report's section 3 choose +(`Gen.x86_64.raz`, `Exe.linux.raz`, `Host.linux.raz`); `Gen.Arch` and +`Exe.Os` name the target, `"x86_64"` and `"linux"`, and `Raz` gives them +to `Parse`, whose lookup of a module's file is by them. `src/cross.sh` +builds a compiler for another target by staging (see Host below). 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`, @@ -102,11 +108,11 @@ 4. Each procedure becomes a chunk of code; `Out.str("hello, world\n")` becomes a string chunk, a call, and a fixup to `Out.str`'s chunk. 5. Back in `Raz.raz`, `use` marks the modules the program uses; the - entry point, `_start`, is written by `Gen.raz`'s `entryPoint` as one + entry point, `_start`, is written by `Gen.x86_64.raz`'s `entryPoint` as one more chunk: save `argc` and `argv` and the address of the places (below), call every used module's body, call `main`, call `Rt.exit`. 6. `markLive` (`Link.raz`) marks what `_start` reaches; then - `writeElf` (`Elf.raz`) has `Link.linkAll` place it and patch it, and + `Exe.write` (`Exe.linux.raz`) has `Link.linkAll` place it and patch it, and writes headers, code, data, symbols and line numbers. ## A procedure, compiled @@ -137,7 +143,7 @@ `scale` calls nothing, so its parameters stay in `rdi` and `rsi`, where they arrive (`keepArrived`): they are register variables that cost nothing to keep. Every line of it can be traced to a routine in -`Gen.raz`: the moves are `loaded`'s, the shift and the add `op`'s, the +`Gen.x86_64.raz`: the moves are `loaded`'s, the shift and the add `op`'s, the result `returnJump`'s, and the frame is `enterBody`'s and `endProc`'s. It is not the fastest code. It is code whose every instruction you can account for, which is the point. @@ -1529,7 +1535,7 @@ field of a `nil` pointer past that page: an item reached through `^` is `deref` until `nilTest` (`Item.raz`) has it used, and Gen's `checkNil` tests the pointer only if the use reaches past `NilPage`. A port whose -machine catches less tests for more, in its own `Gen.raz`: `Rt.fail` +machine catches less tests for more, in its own `Gen.x86_64.raz`: `Rt.fail` stops for a nil pointer, a division by zero and a stack overflow as the signals would. @@ -1826,7 +1832,7 @@ ## Parse.raz: the parser A recursive descent parser, one routine for each rule of the grammar in -the report, calling `Item.raz`, and for jumps `Gen.raz`, as it goes. +the report, calling `Item.raz`, and for jumps `Gen.x86_64.raz`, as it goes. Like the other modules it is written in raz: the Free Pascal seed built it the first time, and it builds itself now. Its routines begin in lower case, and each one that can find an error ends in an `ERROR` @@ -2199,7 +2205,7 @@ address is, and the profiler's start. What it isn't given, nothing reaches, so the linker leaves it out: `raz -noprofile` gives no profiler, and `raz -s` none of them, whose failures say only their -address (and `Elf.raz` writes no symbols or line numbers). Hello is 28 +address (and `Exe.linux.raz` writes no symbols or line numbers). Hello is 28 KB, 21 KB without the profiler, and 7 KB stripped. The layout is chosen so the file can be mapped as it lies, with no @@ -2209,9 +2215,11 @@ segments, with their different permissions, share a page. bss follows the loader's table, or begins a page of its own. -## Elf.raz: the executable +## Exe.linux.raz: the executable -`writeElf` writes the ELF header, the program headers, the text and +`Exe`, the executable, is the one unit that knows the file format of +the target's system; this is Linux's, ELF. A macOS `Exe.darwin.raz` +will be Mach-O. `Exe.write` writes the ELF header, the program headers, the text and rodata images, and then what isn't loaded: section headers, a symbol table with every live procedure and variable by `Module.name`, and the compile unit that names the line table. The line table is in the @@ -2226,7 +2234,7 @@ loader and the first library are glibc's, `/lib64/ld-linux-x86-64.so.2` and `libc.so.6`, or musl's, `/lib/ld-musl-x86_64.so.1` and `libc.so`, which musl's loader, being -the library itself, takes to mean itself (`Elf.setMusl`). `-libc` +the library itself, takes to mean itself (`Exe.setMusl`). `-libc` chooses; left out, `Host.cLibrary` does: musl where the machine has its loader and not glibc's, as Alpine does. A symbol that isn't live gets no relocation, so a program runs over a C library that lacks a @@ -2238,11 +2246,11 @@ it, which `putDebug` writes. There are no types or variables in it; gdb can stop at a line and show where it is, not print a variable. -## Host.raz: the system running the compiler +## Host.linux.raz: the system running the compiler The host is the system running raz; the target is the system its program will run on. Everything the compiler asks of its host that the -library doesn't give is in `Host.raz`, five procedures, each a real +library doesn't give is in `Host` (`Host.linux.raz`), five procedures, each a real difference between hosts. Nothing else in `src/` makes a system call, reads `argv`, opens `/proc` or sets a file's mode; it reads, writes and lists files, the environment and the working directory through the @@ -2258,9 +2266,9 @@ host can't make such a program, and `Raz` refuses one when it finds the program uses C. Linux's is glibc, or musl where only its loader is there. -- `writeExecutable`: the bytes `Elf` made, written as an executable. +- `writeExecutable`: the bytes `Exe` made, written as an executable. Linux's writes the file and sets mode 755. It returns false on any - failure, which `Elf` reports. + failure, which `Exe` reports. - `prepareRun`: the path `raz run` writes to, or an error, which is the refusal of a host that can't run a program. Linux's is a memfd, `/proc/self/fd/N`, kept open until `execute`. @@ -2268,11 +2276,18 @@ arguments are the compiler's from number `first` on (so its argument 0 is `Main.raz`), and the environment. It returns only on failure. -**Building for another host.** Stage the sources: copy `src/` to a -directory, put that host's `Host.raz` there in place of raz's, and -build `Raz.raz` from the copy with that host's library. This is the one -way; raz knows no host but Linux. A module in the main file's -directory is found first, so `-I` alone can't replace `Host.raz`, which +**Building for another host, or another target.** Stage the sources: +copy `src/` to a directory with only plain names, a target's file under +the name of its unit (`Gen.x86_64.raz` as `Gen.raz`, `Exe.linux.raz` as +`Exe.raz`) and the host's `Host.linux.raz`, or another host's, as +`Host.raz`, and build `Raz.raz` from the copy with that host's library. +`src/cross.sh TARGET` does it for a target (`darwin-arm64`) and the +host's Host: the compiler it makes runs here and compiles for TARGET, +and it names the files that are missing for one that has none. With +`TARGET` the one raz is built for, its compiler is `./raz`'s but for +the paths it holds. This is the one way; raz knows no target or host +but the files it was built from. A module in the main file's +directory is found first, so `-I` alone can't replace `Host`, which is right: a module is never replaced silently. The new file keeps every export, `CLib` too, and opens with what it is, as raz's does. `test/host/Host.raz` is such a file (its library from the environment, @@ -2518,9 +2533,9 @@ above `rsp`. **The code never writes below `rsp`**, no red zone: where it looked, `rsp`-relative operands are in only two places, `[rsp]` and `[rsp + 8]` read by the entry point and by the fail - stubs (`Gen.entryPoint`, all `X.mem(RSP, ...)` in `Gen.raz`), and + stubs (`Gen.entryPoint`, all `X.mem(RSP, ...)` in `Gen.x86_64.raz`), and `X64.raz` and the assembler address only through the operands - `Gen.raz` gives them. Every other use of the stack is a `push` or + `Gen.x86_64.raz` gives them. Every other use of the stack is a `push` or a `sub rsp`, which move `rsp` first, and a procedure with no calls still makes its frame. An interrupt, then, needs no stack of its own (IST) for that reason; it still needs room above the frame for its @@ -2724,7 +2739,7 @@ | `Sys.stdin` | `Scan`: `raz -q`'s source, read from standard input | | `Sys.readLink` | `Host.libraryDir`: `/proc/self/exe`, to find the library beside the compiler | | `Sys.stderr`, `Sys.stdout`, `Sys.write` | `Diag`: its messages, or `raz -q check`'s rows on standard output | -| `Sys.workDir` | `Diag`: shows a path relative to the working directory; `Elf`: the compilation directory of the line table | +| `Sys.workDir` | `Diag`: shows a path relative to the working directory; `Exe`: the compilation directory of the line table | `Rt`, the run time, besides `fail`, `exit` and the places (above): @@ -2790,7 +2805,7 @@ | | report's least | this compiler | |---|---|---| | statements, expressions and types nested | 63 levels of statements, 63 of parentheses and calls | 256 together (`MaxNest`) | - | values waiting in one expression | none given | 1,024 (`MaxStack`, `Gen.raz`) | + | values waiting in one expression | none given | 1,024 (`MaxStack`, `Gen.x86_64.raz`) | | chain of imports | 15 modules | 63 (`MaxPending`) | | names declared together | 31 | 64 (`MaxNames`) | | variables assigned together | 15 | 16 | @@ -2900,17 +2915,18 @@ ## Where to start changing it - **A built-in procedure:** an entry in `Sym.raz`'s universe (`enter`), - a case in `builtin` in `Parse.raz`, and the code, in `Gen.raz` if it is an + a case in `builtin` in `Parse.raz`, and the code, in `Gen.x86_64.raz` if it is an instruction, or of calls to gen right there. - **An instruction:** a routine in `X64.raz` built on `opM` or `opR`, its encoding checked against `objdump -d` once, and a program in `conform/` or `test/` that uses it. -- **A machine:** a new `Gen.raz`, answering the same calls, and an - encoder and assembler for it in place of `X64.raz`. +- **A machine:** a new `Gen.ARCH.raz`, answering the same calls, and an + encoder and assembler for it in place of `X64.raz`; and `Exe.OS.raz` if + the system's executable differs. - **A statement:** a reserved word in `Scan.raz` (in `Sym` and `words`, in the same order), a case in `oneStatement`, and a routine beside the others. -- **A check that fails:** `check` in `Gen.raz`, and the message in +- **A check that fails:** `check` in `Gen.x86_64.raz`, and the message in `lib/Rt.raz`'s `fail`; a reason a signal gives, `onSignal` there. The compiler is in raz. `make raz` builds it with the release `BOOT` diff --git a/src/Elf.raz b/src/Elf.raz deleted file mode 100644 index 2ac06e9..0000000 --- a/src/Elf.raz +++ /dev/null @@ -1,450 +0,0 @@ -(* Elf: the executable file. - - Writes an ELF64 executable for x86-64 Linux: the ELF header, the - program headers, the linked text and rodata, and section headers - with a symbol table, so that objdump and gdb can name each procedure - and variable. For gdb's line numbers there is DWARF 4: a line table - (.debug_line), and the one compile unit that points to it - (.debug_info, .debug_abbrev). There are no types or variables. - - A program that uses C is linked dynamically, in the least way the - loader accepts: it names its loader and libraries, and each C symbol - it uses is a quadword the loader fills in with the symbol's address - (a GLOB_DAT relocation), which the code calls or reads through. - There is no PLT and no lazy binding, and the program exports nothing. - - Depends on: Link for the images and addresses, Chunk for the chunks, - Scan for names and memory, Diag for errors, Sys for the working - directory, and Host to write the file. - Leaves out: position independent executables, symbol versions, the - rest of DWARF. - - The C library is glibc's or musl's, as setMusl says: the loader the - program names, and the library it needs first. - - Exported variables can't be set from outside, so needLib, setMusl, - setMainPath and setStripped do it. *) -module Elf; -import Sys, Host, Fmt, Diag, Scan, Chunk, Link; -import SYSTEM; - -var - needed: [32]INT; (* the libraries to load, names interned *) - numNeeded*: INT; (* none: a static program *) - mainPath: []const U8; (* the main module's file, for gdb *) - stripped*: BOOL; (* -s: no symbols and no line numbers; the sections are there, empty *) - interp: []const U8; (* the loader a program that uses C names *) - libc*: []const U8; (* and the C library it needs *) - - buf: ^U8; - len, cap: INT; - -(* The library name, to be loaded, unless it is already: false if there - are too many *) -proc needLib*(name: INT): BOOL; -var i: INT; -begin - for i := 0 to numNeeded - 1 do - if needed[i] = name then return true; end; - end; - if numNeeded = 32 then return false; end; - needed[numNeeded] := name; - INC(numNeeded); - return true; -end; - -(* A static program again *) -proc noLibs*; -begin - numNeeded := 0; -end; - -(* A program that uses C is linked against musl, if yes, or glibc. - musl's library is its own loader, which takes libc.so to mean - itself, whatever file the system keeps it in. *) -proc setMusl*(yes: BOOL); -begin - if yes then - interp := "/lib/ld-musl-x86_64.so.1"; - libc := "libc.so"; - else - interp := "/lib64/ld-linux-x86-64.so.2"; - libc := "libc.so.6"; - end; -end; - -proc setMainPath*(path: []const U8); -begin - mainPath := path; -end; - -proc setStripped*(yes: BOOL); -begin - stripped := yes; -end; - -proc room(n: INT); -begin - if len + n > cap then - buf := Scan.regrab(buf, len, cap * 2 + n); - cap := cap * 2 + n; - end; -end; - -(* The n low bytes of v, least significant first *) -proc putN(v: INT; n: INT); -var i: INT; -begin - room(n); - for i := 0 to n - 1 do - buf[len] := U8(v & 0FFH); - v := v shr 8; - INC(len); - end; -end; - -proc putBytes(p: ^U8; n: INT); -begin - room(n); - if n > 0 then COPY(buf[len..len + n], p[0..n]); end; - len := len + n; -end; - -proc padTo(off: INT); -begin - while len < off do putN(0, 1); end; -end; - -proc patch(at: INT; v: INT; n: INT); -var i: INT; -begin - for i := 0 to n - 1 do - buf[at + i] := U8(v & 0FFH); - v := v shr 8; - end; -end; - -proc phdr(typ, flags: INT; off, adr, filesz, memsz, align: INT); -begin - putN(typ, 4); - putN(flags, 4); - putN(off, 8); - putN(adr, 8); - putN(adr, 8); - putN(filesz, 8); - putN(memsz, 8); - putN(align, 8); -end; - -const - (* the section names, in .shstrtab; a section header names its own *) - ShNames = "\0.text\0.rodata\0.bss\0.symtab\0.strtab\0.shstrtab\0.dynamic\0.dynstr\0.dynsym\0.debug_line\0.debug_info\0.debug_abbrev\0"; - -(* Where in ShNames the name is: the byte after a zero that starts it and - is followed by one; the empty name, found nowhere, is 0 *) -proc nameAt(name: []const U8): INT; -var i, k: INT; same: BOOL; -begin - for i := 1 to LEN(ShNames) - LEN(name) - 1 do - if ShNames[i - 1] = 0 then - same := ShNames[i + LEN(name)] = 0; - for k := 0 to LEN(name) - 1 do - if ShNames[i + k] # name[k] then same := false; end; - end; - if same and (LEN(name) > 0) then return i; end; - end; - end; - return 0; -end; - -(* A section header. Its name is stored as its offset in ShNames. *) -proc shdr(name: []const U8; typ: INT; flags, adr, off, size: INT; lnk, info: INT; align, entsize: INT); -begin - putN(nameAt(name), 4); putN(typ, 4); putN(flags, 8); putN(adr, 8); - putN(off, 8); putN(size, 8); putN(lnk, 4); putN(info, 4); - putN(align, 8); putN(entsize, 8); -end; - -proc putStr(s: []const U8); -begin - putBytes(SYSTEM.PTR(s), LEN(s)); - putN(0, 1); -end; - -(* LEB128, unsigned *) -proc putU(v: INT); -begin - while v >= 80H do - putN(v & 7FH | 80H, 1); - v := v shr 7; - end; - putN(v, 1); -end; - -(* The compile unit, which names the line table, and its abbreviation; - the table itself is in the places, in rodata (Link). Section - offsets go in off, sizes in size: line, info, abbrev. *) -proc putDebug(off, size: []INT); -var cwd: []const U8; err: INT; -begin - off[0] := Chunk.chunks[Link.placesChunk].adr - Link.roAdr + Link.roOff + Link.linesOff; - size[0] := Link.linesSize; - off[1] := len; - putN(0, 4); putN(4, 2); putN(0, 4); putN(8, 1); (* length, version, abbrev, address size *) - putU(1); - putStr(mainPath); - cwd, err := Sys.workDir(); - if err # 0 then cwd := ""; end; - putStr(cwd); - putStr("raz"); - putN(0, 4); (* the line table, at 0 *) - putN(Link.base + Link.textOff, 8); putN(Link.textSize, 8); (* the code, all of it *) - patch(off[1], len - off[1] - 4, 4); - size[1] := len - off[1]; - - off[2] := len; - putU(1); putU(11H); putN(0, 1); (* 1: a compile unit, no children *) - putU(03H); putU(08H); (* name, a string *) - putU(1BH); putU(08H); (* comp_dir, a string *) - putU(25H); putU(08H); (* producer, a string *) - putU(10H); putU(17H); (* stmt_list, a section offset *) - putU(11H); putU(01H); (* low_pc, an address *) - putU(12H); putU(07H); (* high_pc, a length in 8 bytes *) - putN(0, 2); putN(0, 1); - size[2] := len - off[2]; -end; - -const - (* program header types *) - PtLoad = 1; PtDynamic = 2; PtInterp = 3; PtGnuStack = 6474E551H; - -var - (* in the room at the end of rodata: where each of the loader's - tables starts, from extraAdr *) - symAt, relaAt, hashAt, strAt: INT; - nsym, strLen: INT; - -(* Whether chunk c is a C symbol the program uses *) -proc isExt(c: INT): BOOL; -begin - return Chunk.chunks[c].live and Chunk.chunks[c].ext; -end; - -(* The sizes of the loader's tables: what linkAll must leave room for. *) -proc sizeTables(var roExtra, dynSize: INT); -var c, i: INT; -begin - nsym := 1; - strLen := 1; - for i := 0 to numNeeded - 1 do strLen := strLen + LEN(Scan.nameOf(needed[i])) + 1; end; - for c := 0 to Chunk.numChunks - 1 do - if isExt(c) then - INC(nsym); - strLen := strLen + LEN(Scan.nameOf(Chunk.chunks[c].name)) + 1; - end; - end; - symAt := (LEN(interp) + 1 + 7) div 8 * 8; - relaAt := symAt + nsym * 24; - hashAt := relaAt + (nsym - 1) * 24; - strAt := hashAt + 4 * (3 + nsym); - roExtra := strAt + strLen; - dynSize := (numNeeded + 10) * 16; -end; - -(* The loader's tables in the room at the end of rodata, which the - buffer already holds as zeros: the loader's name; the symbols, one - for each C symbol used; a GLOB_DAT relocation for each, at its - quadword; a hash table of one bucket; and their names. *) -proc putTables; -var c, k, i, at, name: INT; -begin - len := Link.extraAdr - Link.roAdr + Link.roOff; - putStr(interp); - padTo(Link.extraAdr - Link.roAdr + Link.roOff + symAt); - putN(0, 24); - name := strLen; - for c := Chunk.numChunks - 1 to 0 by -1 do (* names go last in the string table *) - if isExt(c) then name := name - LEN(Scan.nameOf(Chunk.chunks[c].name)) - 1; end; - end; - for c := 0 to Chunk.numChunks - 1 do - if isExt(c) then - putN(name, 4); putN(10H, 1); putN(0, 1); putN(0, 2); (* global, undefined *) - putN(0, 8); putN(0, 8); - name := name + LEN(Scan.nameOf(Chunk.chunks[c].name)) + 1; - end; - end; - k := 1; - for c := 0 to Chunk.numChunks - 1 do - if isExt(c) then - putN(Chunk.chunks[c].adr, 8); - putN((k shl 32) | 6, 8); (* R_X86_64_GLOB_DAT *) - putN(0, 8); - INC(k); - end; - end; - putN(1, 4); putN(nsym, 4); putN(nsym - 1, 4); (* the bucket chains every symbol *) - putN(0, 4); - for i := 1 to nsym - 1 do putN(i - 1, 4); end; - putN(0, 1); - for i := 0 to numNeeded - 1 do putStr(Scan.nameOf(needed[i])); end; - for c := 0 to Chunk.numChunks - 1 do - if isExt(c) then putStr(Scan.nameOf(Chunk.chunks[c].name)); end; - end; - len := Link.roOff + Link.roSize; - - (* the dynamic table, at the start of the writable segment *) - padTo(Link.bssOff); - at := 1; - for i := 0 to numNeeded - 1 do - putN(1, 8); putN(at, 8); (* DT_NEEDED *) - at := at + LEN(Scan.nameOf(needed[i])) + 1; - end; - putN(4, 8); putN(Link.extraAdr + hashAt, 8); (* DT_HASH *) - putN(5, 8); putN(Link.extraAdr + strAt, 8); (* DT_STRTAB *) - putN(6, 8); putN(Link.extraAdr + symAt, 8); (* DT_SYMTAB *) - putN(10, 8); putN(strLen, 8); (* DT_STRSZ *) - putN(11, 8); putN(24, 8); (* DT_SYMENT *) - putN(7, 8); putN(Link.extraAdr + relaAt, 8); (* DT_RELA *) - putN(8, 8); putN((nsym - 1) * 24, 8); (* DT_RELASZ *) - putN(9, 8); putN(24, 8); (* DT_RELAENT *) - putN(21, 8); putN(0, 8); (* DT_DEBUG, for gdb *) - putN(0, 16); (* DT_NULL *) -end; - -proc writeElf*(path: []const U8; entry: INT); -var - nph, nsh, c, nsyms, sec, strsCap: INT; - roExtra, dynSize, symOff, strOff, shstrOff, shOff, strsLen: INT; - dbgOff, dbgSize: [3]INT; - strs: ^U8; - s: []const U8; - dyn: BOOL; -begin - cap := 1 shl 16; - buf := Scan.grab(cap); - len := 0; - dyn := numNeeded > 0; - roExtra := 0; dynSize := 0; - if dyn then sizeTables(roExtra, dynSize); end; - (* room for the most program headers either kind of program has *) - Link.linkAll(64 + 6 * 56, roExtra, dynSize); - if dyn then - nph := 6; - else - nph := 2; - if Link.roSize > 0 then INC(nph); end; - if Link.bssSize > 0 then INC(nph); end; - end; - - (* ELF header *) - putN(464C457FH, 4); (* #127 'ELF' *) - putN(2, 1); putN(1, 1); putN(1, 1); putN(0, 9); (* 64-bit, little-endian, version 1 *) - putN(2, 2); (* ET_EXEC *) - putN(62, 2); (* EM_X86_64 *) - putN(1, 4); - putN(Chunk.chunks[entry].adr, 8); - putN(64, 8); (* program headers follow *) - putN(0, 8); (* section headers: patched below *) - putN(0, 4); - nsh := 10; - if dyn then nsh := 13; end; - putN(64, 2); putN(56, 2); putN(nph, 2); - putN(64, 2); putN(nsh, 2); putN(6, 2); (* .shstrtab is section 6 *) - - (* flags: 4 read, 5 read and run, 6 read and write *) - if dyn then - phdr(PtInterp, 4, Link.extraAdr - Link.roAdr + Link.roOff, Link.extraAdr, LEN(interp) + 1, LEN(interp) + 1, 1); - end; - (* the first segment maps the headers too, so text can follow them *) - phdr(PtLoad, 5, 0, Link.base, Link.textOff + Link.textSize, Link.textOff + Link.textSize, Link.Page); - if Link.roSize > 0 then phdr(PtLoad, 4, Link.roOff, Link.roAdr, Link.roSize, Link.roSize, Link.Page); end; - if dyn then - phdr(PtLoad, 6, Link.bssOff, Link.bssAdr, dynSize, Link.bssSize, Link.Page); - phdr(PtDynamic, 6, Link.bssOff, Link.bssAdr, dynSize, dynSize, 8); - elsif Link.bssSize > 0 then - phdr(PtLoad, 6, 0, Link.bssAdr, 0, Link.bssSize, Link.Page); - end; - phdr(PtGnuStack, 6, 0, 0, 0, 0, 16); (* a stack that can't run code *) - - padTo(Link.textOff); - putBytes(Link.textImg, Link.textSize); - padTo(Link.roOff); (* even when empty, so that every section lies in the file *) - putBytes(Link.roImg, Link.roSize); - if dyn then putTables; end; - - (* the symbol table: one local symbol for each named live chunk *) - padTo((len + 7) div 8 * 8); - symOff := len; - strsCap := 1 shl 16; - strs := Scan.grab(strsCap); - strsLen := 1; - strs[0] := 0; - putN(0, 24); - nsyms := 1; - for c := 0 to Chunk.numChunks - 1 do - if not stripped and Chunk.chunks[c].live and (Chunk.chunks[c].name >= 0) and not Chunk.chunks[c].ext then - s := Chunk.chunkName(c); - if strsLen + LEN(s) + 1 > strsCap then - strs := Scan.regrab(strs, strsLen, strsLen * 2 + 256); - strsCap := strsLen * 2 + 256; - end; - COPY(strs[strsLen..strsLen + LEN(s)], s); - strs[strsLen + LEN(s)] := 0; - if Chunk.chunks[c].sec = Chunk.secText then (* the section's index in the headers below *) - sec := 1; - elsif Chunk.chunks[c].sec = Chunk.secRodata then - sec := 2; - else - sec := 3; - end; - putN(strsLen, 4); - if sec = 1 then putN(2, 1); else putN(1, 1); end; (* STT_FUNC, STT_OBJECT *) - putN(0, 1); - putN(sec, 2); - putN(Chunk.chunks[c].adr, 8); - putN(Chunk.chunks[c].size, 8); - strsLen := strsLen + LEN(s) + 1; - INC(nsyms); - end; - end; - strOff := len; - putBytes(strs, strsLen); - shstrOff := len; - putBytes(SYSTEM.PTR(ShNames), LEN(ShNames)); - if stripped or (Link.placesChunk < 0) then - for c := 0 to 2 do dbgOff[c] := len; dbgSize[c] := 0; end; - else - putDebug(dbgOff, dbgSize); - end; - - padTo((len + 7) div 8 * 8); - shOff := len; - patch(40, shOff, 8); - (* types: 1 PROGBITS, 2 SYMTAB, 3 STRTAB, 6 DYNAMIC, 8 NOBITS, 11 DYNSYM; - flags: 2 ALLOC, 3 WRITE+ALLOC, 6 ALLOC+EXECINSTR. A symbol table's - link is its string table's index: 5 .strtab, 8 .dynstr. The order - here is the index the code above relies on. *) - shdr("", 0, 0, 0, 0, 0, 0, 0, 0, 0); - shdr(".text", 1, 6, Link.base + Link.textOff, Link.textOff, Link.textSize, 0, 0, 16, 0); - shdr(".rodata", 1, 2, Link.roAdr, Link.roOff, Link.roSize, 0, 0, 16, 0); - shdr(".bss", 8, 3, Link.bssAdr + dynSize, Link.roOff + Link.roSize, Link.bssSize - dynSize, 0, 0, 16, 0); - shdr(".symtab", 2, 0, 0, symOff, nsyms * 24, 5, nsyms, 8, 24); - shdr(".strtab", 3, 0, 0, strOff, strsLen, 0, 0, 1, 0); - shdr(".shstrtab", 3, 0, 0, shstrOff, LEN(ShNames), 0, 0, 1, 0); - if dyn then (* the loader's tables, for readelf and objdump *) - shdr(".dynamic", 6, 3, Link.bssAdr, Link.bssOff, dynSize, 8, 0, 8, 16); - shdr(".dynstr", 3, 2, Link.extraAdr + strAt, Link.extraAdr + strAt - Link.roAdr + Link.roOff, strLen, 0, 0, 1, 0); - shdr(".dynsym", 11, 2, Link.extraAdr + symAt, Link.extraAdr + symAt - Link.roAdr + Link.roOff, nsym * 24, 8, 1, 8, 24); - end; - shdr(".debug_line", 1, 0, 0, dbgOff[0], dbgSize[0], 0, 0, 1, 0); - shdr(".debug_info", 1, 0, 0, dbgOff[1], dbgSize[1], 0, 0, 1, 0); - shdr(".debug_abbrev", 1, 0, 0, dbgOff[2], dbgSize[2], 0, 0, 1, 0); - - if not Host.writeExecutable(path, buf[0..len]) then - Diag.fatal(Diag.say("can't write {}", [Fmt.str(path)])); - end; -end; - -begin - mainPath := ""; -end Elf. diff --git a/src/Exe.linux.raz b/src/Exe.linux.raz new file mode 100644 index 0000000..94c8693 --- /dev/null +++ b/src/Exe.linux.raz @@ -0,0 +1,455 @@ +(* Exe: the executable file, for Linux: ELF. + + Exe.darwin.raz, for macOS, will be Mach-O; a target has one Exe, chosen + by the suffix of its file (doc/raz.md, 3), and no other unit knows the + format. This one writes an ELF64 executable: the ELF header, the + program headers, the linked text and rodata, and section headers + with a symbol table, so that objdump and gdb can name each procedure + and variable. For gdb's line numbers there is DWARF 4: a line table + (.debug_line), and the one compile unit that points to it + (.debug_info, .debug_abbrev). There are no types or variables. + + A program that uses C is linked dynamically, in the least way the + loader accepts: it names its loader and libraries, and each C symbol + it uses is a quadword the loader fills in with the symbol's address + (a GLOB_DAT relocation), which the code calls or reads through. + There is no PLT and no lazy binding, and the program exports nothing. + + Depends on: Link for the images and addresses, Chunk for the chunks, + Scan for names and memory, Diag for errors, Sys for the working + directory, and Host to write the file. + Leaves out: position independent executables, symbol versions, the + rest of DWARF. + + The C library is glibc's or musl's, as setMusl says: the loader the + program names, and the library it needs first. + + Exported variables can't be set from outside, so needLib, setMusl, + setMainPath and setStripped do it. *) +module Exe; +import Sys, Host, Fmt, Diag, Scan, Chunk, Link; +import SYSTEM; + +const + Os* = "linux"; (* the target's operating system, as a file's suffix says it *) + +var + needed: [32]INT; (* the libraries to load, names interned *) + numNeeded*: INT; (* none: a static program *) + mainPath: []const U8; (* the main module's file, for gdb *) + stripped*: BOOL; (* -s: no symbols and no line numbers; the sections are there, empty *) + interp: []const U8; (* the loader a program that uses C names *) + libc*: []const U8; (* and the C library it needs *) + + buf: ^U8; + len, cap: INT; + +(* The library name, to be loaded, unless it is already: false if there + are too many *) +proc needLib*(name: INT): BOOL; +var i: INT; +begin + for i := 0 to numNeeded - 1 do + if needed[i] = name then return true; end; + end; + if numNeeded = 32 then return false; end; + needed[numNeeded] := name; + INC(numNeeded); + return true; +end; + +(* A static program again *) +proc noLibs*; +begin + numNeeded := 0; +end; + +(* A program that uses C is linked against musl, if yes, or glibc. + musl's library is its own loader, which takes libc.so to mean + itself, whatever file the system keeps it in. *) +proc setMusl*(yes: BOOL); +begin + if yes then + interp := "/lib/ld-musl-x86_64.so.1"; + libc := "libc.so"; + else + interp := "/lib64/ld-linux-x86-64.so.2"; + libc := "libc.so.6"; + end; +end; + +proc setMainPath*(path: []const U8); +begin + mainPath := path; +end; + +proc setStripped*(yes: BOOL); +begin + stripped := yes; +end; + +proc room(n: INT); +begin + if len + n > cap then + buf := Scan.regrab(buf, len, cap * 2 + n); + cap := cap * 2 + n; + end; +end; + +(* The n low bytes of v, least significant first *) +proc putN(v: INT; n: INT); +var i: INT; +begin + room(n); + for i := 0 to n - 1 do + buf[len] := U8(v & 0FFH); + v := v shr 8; + INC(len); + end; +end; + +proc putBytes(p: ^U8; n: INT); +begin + room(n); + if n > 0 then COPY(buf[len..len + n], p[0..n]); end; + len := len + n; +end; + +proc padTo(off: INT); +begin + while len < off do putN(0, 1); end; +end; + +proc patch(at: INT; v: INT; n: INT); +var i: INT; +begin + for i := 0 to n - 1 do + buf[at + i] := U8(v & 0FFH); + v := v shr 8; + end; +end; + +proc phdr(typ, flags: INT; off, adr, filesz, memsz, align: INT); +begin + putN(typ, 4); + putN(flags, 4); + putN(off, 8); + putN(adr, 8); + putN(adr, 8); + putN(filesz, 8); + putN(memsz, 8); + putN(align, 8); +end; + +const + (* the section names, in .shstrtab; a section header names its own *) + ShNames = "\0.text\0.rodata\0.bss\0.symtab\0.strtab\0.shstrtab\0.dynamic\0.dynstr\0.dynsym\0.debug_line\0.debug_info\0.debug_abbrev\0"; + +(* Where in ShNames the name is: the byte after a zero that starts it and + is followed by one; the empty name, found nowhere, is 0 *) +proc nameAt(name: []const U8): INT; +var i, k: INT; same: BOOL; +begin + for i := 1 to LEN(ShNames) - LEN(name) - 1 do + if ShNames[i - 1] = 0 then + same := ShNames[i + LEN(name)] = 0; + for k := 0 to LEN(name) - 1 do + if ShNames[i + k] # name[k] then same := false; end; + end; + if same and (LEN(name) > 0) then return i; end; + end; + end; + return 0; +end; + +(* A section header. Its name is stored as its offset in ShNames. *) +proc shdr(name: []const U8; typ: INT; flags, adr, off, size: INT; lnk, info: INT; align, entsize: INT); +begin + putN(nameAt(name), 4); putN(typ, 4); putN(flags, 8); putN(adr, 8); + putN(off, 8); putN(size, 8); putN(lnk, 4); putN(info, 4); + putN(align, 8); putN(entsize, 8); +end; + +proc putStr(s: []const U8); +begin + putBytes(SYSTEM.PTR(s), LEN(s)); + putN(0, 1); +end; + +(* LEB128, unsigned *) +proc putU(v: INT); +begin + while v >= 80H do + putN(v & 7FH | 80H, 1); + v := v shr 7; + end; + putN(v, 1); +end; + +(* The compile unit, which names the line table, and its abbreviation; + the table itself is in the places, in rodata (Link). Section + offsets go in off, sizes in size: line, info, abbrev. *) +proc putDebug(off, size: []INT); +var cwd: []const U8; err: INT; +begin + off[0] := Chunk.chunks[Link.placesChunk].adr - Link.roAdr + Link.roOff + Link.linesOff; + size[0] := Link.linesSize; + off[1] := len; + putN(0, 4); putN(4, 2); putN(0, 4); putN(8, 1); (* length, version, abbrev, address size *) + putU(1); + putStr(mainPath); + cwd, err := Sys.workDir(); + if err # 0 then cwd := ""; end; + putStr(cwd); + putStr("raz"); + putN(0, 4); (* the line table, at 0 *) + putN(Link.base + Link.textOff, 8); putN(Link.textSize, 8); (* the code, all of it *) + patch(off[1], len - off[1] - 4, 4); + size[1] := len - off[1]; + + off[2] := len; + putU(1); putU(11H); putN(0, 1); (* 1: a compile unit, no children *) + putU(03H); putU(08H); (* name, a string *) + putU(1BH); putU(08H); (* comp_dir, a string *) + putU(25H); putU(08H); (* producer, a string *) + putU(10H); putU(17H); (* stmt_list, a section offset *) + putU(11H); putU(01H); (* low_pc, an address *) + putU(12H); putU(07H); (* high_pc, a length in 8 bytes *) + putN(0, 2); putN(0, 1); + size[2] := len - off[2]; +end; + +const + (* program header types *) + PtLoad = 1; PtDynamic = 2; PtInterp = 3; PtGnuStack = 6474E551H; + +var + (* in the room at the end of rodata: where each of the loader's + tables starts, from extraAdr *) + symAt, relaAt, hashAt, strAt: INT; + nsym, strLen: INT; + +(* Whether chunk c is a C symbol the program uses *) +proc isExt(c: INT): BOOL; +begin + return Chunk.chunks[c].live and Chunk.chunks[c].ext; +end; + +(* The sizes of the loader's tables: what linkAll must leave room for. *) +proc sizeTables(var roExtra, dynSize: INT); +var c, i: INT; +begin + nsym := 1; + strLen := 1; + for i := 0 to numNeeded - 1 do strLen := strLen + LEN(Scan.nameOf(needed[i])) + 1; end; + for c := 0 to Chunk.numChunks - 1 do + if isExt(c) then + INC(nsym); + strLen := strLen + LEN(Scan.nameOf(Chunk.chunks[c].name)) + 1; + end; + end; + symAt := (LEN(interp) + 1 + 7) div 8 * 8; + relaAt := symAt + nsym * 24; + hashAt := relaAt + (nsym - 1) * 24; + strAt := hashAt + 4 * (3 + nsym); + roExtra := strAt + strLen; + dynSize := (numNeeded + 10) * 16; +end; + +(* The loader's tables in the room at the end of rodata, which the + buffer already holds as zeros: the loader's name; the symbols, one + for each C symbol used; a GLOB_DAT relocation for each, at its + quadword; a hash table of one bucket; and their names. *) +proc putTables; +var c, k, i, at, name: INT; +begin + len := Link.extraAdr - Link.roAdr + Link.roOff; + putStr(interp); + padTo(Link.extraAdr - Link.roAdr + Link.roOff + symAt); + putN(0, 24); + name := strLen; + for c := Chunk.numChunks - 1 to 0 by -1 do (* names go last in the string table *) + if isExt(c) then name := name - LEN(Scan.nameOf(Chunk.chunks[c].name)) - 1; end; + end; + for c := 0 to Chunk.numChunks - 1 do + if isExt(c) then + putN(name, 4); putN(10H, 1); putN(0, 1); putN(0, 2); (* global, undefined *) + putN(0, 8); putN(0, 8); + name := name + LEN(Scan.nameOf(Chunk.chunks[c].name)) + 1; + end; + end; + k := 1; + for c := 0 to Chunk.numChunks - 1 do + if isExt(c) then + putN(Chunk.chunks[c].adr, 8); + putN((k shl 32) | 6, 8); (* R_X86_64_GLOB_DAT *) + putN(0, 8); + INC(k); + end; + end; + putN(1, 4); putN(nsym, 4); putN(nsym - 1, 4); (* the bucket chains every symbol *) + putN(0, 4); + for i := 1 to nsym - 1 do putN(i - 1, 4); end; + putN(0, 1); + for i := 0 to numNeeded - 1 do putStr(Scan.nameOf(needed[i])); end; + for c := 0 to Chunk.numChunks - 1 do + if isExt(c) then putStr(Scan.nameOf(Chunk.chunks[c].name)); end; + end; + len := Link.roOff + Link.roSize; + + (* the dynamic table, at the start of the writable segment *) + padTo(Link.bssOff); + at := 1; + for i := 0 to numNeeded - 1 do + putN(1, 8); putN(at, 8); (* DT_NEEDED *) + at := at + LEN(Scan.nameOf(needed[i])) + 1; + end; + putN(4, 8); putN(Link.extraAdr + hashAt, 8); (* DT_HASH *) + putN(5, 8); putN(Link.extraAdr + strAt, 8); (* DT_STRTAB *) + putN(6, 8); putN(Link.extraAdr + symAt, 8); (* DT_SYMTAB *) + putN(10, 8); putN(strLen, 8); (* DT_STRSZ *) + putN(11, 8); putN(24, 8); (* DT_SYMENT *) + putN(7, 8); putN(Link.extraAdr + relaAt, 8); (* DT_RELA *) + putN(8, 8); putN((nsym - 1) * 24, 8); (* DT_RELASZ *) + putN(9, 8); putN(24, 8); (* DT_RELAENT *) + putN(21, 8); putN(0, 8); (* DT_DEBUG, for gdb *) + putN(0, 16); (* DT_NULL *) +end; + +proc write*(path: []const U8; entry: INT); +var + nph, nsh, c, nsyms, sec, strsCap: INT; + roExtra, dynSize, symOff, strOff, shstrOff, shOff, strsLen: INT; + dbgOff, dbgSize: [3]INT; + strs: ^U8; + s: []const U8; + dyn: BOOL; +begin + cap := 1 shl 16; + buf := Scan.grab(cap); + len := 0; + dyn := numNeeded > 0; + roExtra := 0; dynSize := 0; + if dyn then sizeTables(roExtra, dynSize); end; + (* room for the most program headers either kind of program has *) + Link.linkAll(64 + 6 * 56, roExtra, dynSize); + if dyn then + nph := 6; + else + nph := 2; + if Link.roSize > 0 then INC(nph); end; + if Link.bssSize > 0 then INC(nph); end; + end; + + (* ELF header *) + putN(464C457FH, 4); (* #127 'ELF' *) + putN(2, 1); putN(1, 1); putN(1, 1); putN(0, 9); (* 64-bit, little-endian, version 1 *) + putN(2, 2); (* ET_EXEC *) + putN(62, 2); (* EM_X86_64 *) + putN(1, 4); + putN(Chunk.chunks[entry].adr, 8); + putN(64, 8); (* program headers follow *) + putN(0, 8); (* section headers: patched below *) + putN(0, 4); + nsh := 10; + if dyn then nsh := 13; end; + putN(64, 2); putN(56, 2); putN(nph, 2); + putN(64, 2); putN(nsh, 2); putN(6, 2); (* .shstrtab is section 6 *) + + (* flags: 4 read, 5 read and run, 6 read and write *) + if dyn then + phdr(PtInterp, 4, Link.extraAdr - Link.roAdr + Link.roOff, Link.extraAdr, LEN(interp) + 1, LEN(interp) + 1, 1); + end; + (* the first segment maps the headers too, so text can follow them *) + phdr(PtLoad, 5, 0, Link.base, Link.textOff + Link.textSize, Link.textOff + Link.textSize, Link.Page); + if Link.roSize > 0 then phdr(PtLoad, 4, Link.roOff, Link.roAdr, Link.roSize, Link.roSize, Link.Page); end; + if dyn then + phdr(PtLoad, 6, Link.bssOff, Link.bssAdr, dynSize, Link.bssSize, Link.Page); + phdr(PtDynamic, 6, Link.bssOff, Link.bssAdr, dynSize, dynSize, 8); + elsif Link.bssSize > 0 then + phdr(PtLoad, 6, 0, Link.bssAdr, 0, Link.bssSize, Link.Page); + end; + phdr(PtGnuStack, 6, 0, 0, 0, 0, 16); (* a stack that can't run code *) + + padTo(Link.textOff); + putBytes(Link.textImg, Link.textSize); + padTo(Link.roOff); (* even when empty, so that every section lies in the file *) + putBytes(Link.roImg, Link.roSize); + if dyn then putTables; end; + + (* the symbol table: one local symbol for each named live chunk *) + padTo((len + 7) div 8 * 8); + symOff := len; + strsCap := 1 shl 16; + strs := Scan.grab(strsCap); + strsLen := 1; + strs[0] := 0; + putN(0, 24); + nsyms := 1; + for c := 0 to Chunk.numChunks - 1 do + if not stripped and Chunk.chunks[c].live and (Chunk.chunks[c].name >= 0) and not Chunk.chunks[c].ext then + s := Chunk.chunkName(c); + if strsLen + LEN(s) + 1 > strsCap then + strs := Scan.regrab(strs, strsLen, strsLen * 2 + 256); + strsCap := strsLen * 2 + 256; + end; + COPY(strs[strsLen..strsLen + LEN(s)], s); + strs[strsLen + LEN(s)] := 0; + if Chunk.chunks[c].sec = Chunk.secText then (* the section's index in the headers below *) + sec := 1; + elsif Chunk.chunks[c].sec = Chunk.secRodata then + sec := 2; + else + sec := 3; + end; + putN(strsLen, 4); + if sec = 1 then putN(2, 1); else putN(1, 1); end; (* STT_FUNC, STT_OBJECT *) + putN(0, 1); + putN(sec, 2); + putN(Chunk.chunks[c].adr, 8); + putN(Chunk.chunks[c].size, 8); + strsLen := strsLen + LEN(s) + 1; + INC(nsyms); + end; + end; + strOff := len; + putBytes(strs, strsLen); + shstrOff := len; + putBytes(SYSTEM.PTR(ShNames), LEN(ShNames)); + if stripped or (Link.placesChunk < 0) then + for c := 0 to 2 do dbgOff[c] := len; dbgSize[c] := 0; end; + else + putDebug(dbgOff, dbgSize); + end; + + padTo((len + 7) div 8 * 8); + shOff := len; + patch(40, shOff, 8); + (* types: 1 PROGBITS, 2 SYMTAB, 3 STRTAB, 6 DYNAMIC, 8 NOBITS, 11 DYNSYM; + flags: 2 ALLOC, 3 WRITE+ALLOC, 6 ALLOC+EXECINSTR. A symbol table's + link is its string table's index: 5 .strtab, 8 .dynstr. The order + here is the index the code above relies on. *) + shdr("", 0, 0, 0, 0, 0, 0, 0, 0, 0); + shdr(".text", 1, 6, Link.base + Link.textOff, Link.textOff, Link.textSize, 0, 0, 16, 0); + shdr(".rodata", 1, 2, Link.roAdr, Link.roOff, Link.roSize, 0, 0, 16, 0); + shdr(".bss", 8, 3, Link.bssAdr + dynSize, Link.roOff + Link.roSize, Link.bssSize - dynSize, 0, 0, 16, 0); + shdr(".symtab", 2, 0, 0, symOff, nsyms * 24, 5, nsyms, 8, 24); + shdr(".strtab", 3, 0, 0, strOff, strsLen, 0, 0, 1, 0); + shdr(".shstrtab", 3, 0, 0, shstrOff, LEN(ShNames), 0, 0, 1, 0); + if dyn then (* the loader's tables, for readelf and objdump *) + shdr(".dynamic", 6, 3, Link.bssAdr, Link.bssOff, dynSize, 8, 0, 8, 16); + shdr(".dynstr", 3, 2, Link.extraAdr + strAt, Link.extraAdr + strAt - Link.roAdr + Link.roOff, strLen, 0, 0, 1, 0); + shdr(".dynsym", 11, 2, Link.extraAdr + symAt, Link.extraAdr + symAt - Link.roAdr + Link.roOff, nsym * 24, 8, 1, 8, 24); + end; + shdr(".debug_line", 1, 0, 0, dbgOff[0], dbgSize[0], 0, 0, 1, 0); + shdr(".debug_info", 1, 0, 0, dbgOff[1], dbgSize[1], 0, 0, 1, 0); + shdr(".debug_abbrev", 1, 0, 0, dbgOff[2], dbgSize[2], 0, 0, 1, 0); + + if not Host.writeExecutable(path, buf[0..len]) then + Diag.fatal(Diag.say("can't write {}", [Fmt.str(path)])); + end; +end; + +begin + mainPath := ""; +end Exe. diff --git a/src/Gen.raz b/src/Gen.raz deleted file mode 100644 index 72a1d1d..0000000 --- a/src/Gen.raz +++ /dev/null @@ -1,2846 +0,0 @@ -(* Gen: the code generator, for x86-64. - - Item and Parse drive a stack machine: they push constants, addresses - and the values of variables, operate on the values on top, store - them and jump on them. Every value has a kind: a word, which is an - integer as big as an address, a pointer, a BOOL, a set or a narrower - integer; a long, a 64-bit integer on a machine whose word is smaller - (never here); an F32; an F64. This unit makes the machine's code for - those calls, and nothing above it knows the machine: a port is a new - Gen, with an encoder of its own. - - 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, or in xmm8 to - xmm11 if it is a real. 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. - - 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, and the results of its calls - that hold an array (report 8). The variables are zeroed on - entry. - - Depends on: Scan and Diag for errors, Sym for types, Chunk for code - and data, X64 for instructions. - Leaves out: what the program means, its types and their checks; that - is Item. - - The seed's `Mark` in the middle of a push or a check can't give an - error back, so it is shown and the call goes on without doing what - it could not (see newEntry and check): the compile ends with the - message, and the parser's recovery makes the stack right again with - resetStack. A full stack (newEntry) ends the compile at once: the pops - after it would go below the stack. endProc returns its error, for the - parser to pass up. - - What the parser sets, `inPlace`, has a setter, as the exported - variables can't be set from outside. The seed's types lose their T - (`TAdr` is `Adr`), and its `Call` record, which the procedure `call` - takes, is `CallInfo`. *) -module Gen; -import Fmt, Diag, Scan, Sym, Chunk, X := X64; -import SYSTEM; - -const - NoLabel* = -1; - WordSize* = 8; (* the size of an address, and of INT *) - (* What the machine catches by itself, which the code needn't test for - (report section 10): on x86-64 Linux, a division by zero, a stack - overflow (at the guard page under the stack), a call to nil, and - a load or store within NilPage bytes of address 0, which is never - mapped. *) - NilPage* = 4096; - - RAX = X.RAX; RCX = X.RCX; RDX = X.RDX; RSP = X.RSP; RBP = X.RBP; - RSI = X.RSI; RDI = X.RDI; R8 = X.R8; R9 = X.R9; R10 = X.R10; R11 = X.R11; - -type - Kind* = (kWord, kLong, kF32, kF64); - - (* Where a variable is: its address is relative to the frame, to a - chunk, to an address on the stack, or to one held in a frame slot *) - Base* = (bFrame, bGlobal, bStack, bSlot, bReg, bPtr); - Adr* = record - base*: Base; - chunk*: INT; (* bGlobal: the chunk; bSlot: the frame slot; bReg: the register; - bPtr: the register that holds the address *) - off*: I64; (* added to the address; for bReg, which word, 0 or 8 *) - hi*: INT; (* bReg, a slice: the register of its length, the - second word; chunk is that of its pointer *) - end; - - (* The code made so far, to go back to for a second try at a body *) - CodeMark* = record pc*, fixups*, lines*, said*, fails*, exit*: INT; end; - - (* For entryPoint: the address of chunk, put in the variable whose - chunk is into before the program starts; or, for C's symbols, the - address in chunk, the quadword the loader fills in *) - Link* = record chunk*, into*: INT; end; - - CallInfo* = record - sig*: ^Sym.Type; - param*: ^Sym.Obj; (* the parameter the next argument is for *) - obj*: ^Sym.Obj; (* the procedure called, if it has a name *) - n*: INT; (* the arguments *) - isF*: [64]BOOL; (* ... goes in an xmm register *) - pair*: [64]BOOL; (* ... is a slice's first word, the next its second *) - target*: I64; (* the frame slot of a procedure value, if chunk < 0 *) - chunk*: INT; (* else the procedure's chunk *) - ext*: BOOL; (* C's: called through the chunk holding its address *) - ret*: I64; (* set by call: the temporary a slice or a record result is in *) - end; - -const - (* the registers a procedure keeps its busiest variables in: System V's - 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*: [5]INT = [X.RBX, X.R12, X.R13, X.R14, X.R15]; - (* the registers the trap report can show a variable in: VarRegs, then - rdi and rsi, where a procedure that calls nothing keeps the - parameters that arrive in them (keptIn) *) - ShownRegs*: [7]INT = [X.RBX, X.R12, X.R13, X.R14, X.R15, X.RDI, X.RSI]; - (* the registers a procedure keeps its busiest reals in, xmm12 to - xmm15, numbered from XmmVar up so that they aren't taken for r12 to - r15 (regAt); and in a procedure that calls nothing, which has no - real parameter in them, xmm4 to xmm7 too, as nothing else uses - them there. Each has a slot too, written as it is, where the trap - report finds it, and from which it is loaded again after a call, as - System V has no callee-saved xmm register (xHome). *) - XmmVar* = 16; - XVarRegs*: [8]INT = [XmmVar + 12, XmmVar + 13, XmmVar + 14, XmmVar + 15, - XmmVar + 4, XmmVar + 5, XmmVar + 6, XmmVar + 7]; - (* a procedure's registers of variables, as bits: bit i is VarRegs[i], - bit XBit + i XVarRegs[i] *) - XBit* = 5; - -var - rtFail*, argcChunk*, argvChunk*: INT; - (* the stubs that check's code calls, one for each kind of failure, - made by entryPoint for those used *) - failStubs: [8]INT; - lost*: BOOL; (* a parameter kept where it arrived was wanted - for other work: the procedure is compiled again, - the parameter in memory *) - inPlace: INT; (* the register of a variable that the statement - being compiled assigns, x := x + e, where the - value can be worked out in the variable's own - register, from its first push on (lInto) *) - depth*: INT; (* the values on the stack *) - pushed*: INT; (* quadwords pushed on the machine's stack *) - codeChunk*: INT; (* the procedure or body being compiled, or -1 *) - -type - (* where a value on the stack is *) - Loc = (lConst, (* not loaded: val is the value *) - 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 *) - lIdx, (* not loaded: the address m, an element of an array - or of a slice in registers: the array's or the - pointer's register, or rbp, as the base, and the - index in a register variable's or the value's - own register (indexSlice, indexArray) *) - lMem, (* not loaded: the value of size bytes at m, in the - frame, a chunk, or at an address lAdr or lIdx - noted, read where it is used (pushVar) *) - lInto, (* in register val, a register variable's own, which - is what the value goes to (inPlace): so it is - changed in place *) - lReg, (* in its register *) - lFrame); (* spilled: in the frame slot val *) - - Entry = record - loc: Loc; - val: I64; (* lConst: the value; lHeld: the register; lAdr: the - offset; lFrame: the frame slot *) - chunk: INT; (* lAdr: the chunk, or -1 for the frame *) - m: X.Mem; (* lIdx, lMem *) - size: INT; (* lMem *) - signed: BOOL; (* lMem *) - k: Kind; - off: I64; (* lHeld, lReg: a word, its register plus off, the - constant of x + 1 not yet added (op), so that an - operand that uses it can take it as its - displacement: [r13 + r9 * 8 - 8] *) - end; - - (* a check of the procedure, whose failure endFails makes *) - Fail = record - L, what, ra, name: INT; - path, line, col: INT; (* the place, told now: an inlined procedure's - is in its own file (Parse's inlined) *) - m: X.Mem; - n: I64; - end; - -const - MaxStack = 1024; (* values waiting in one expression: 63 nested calls of up to 15 arguments each *) - StubNames: [8][]const U8 = ["check0", "check1", "check2", "check3", "check4", "check5", "check6", "check7"]; - (* the registers of the stack: the value at depth d is in Regs[d mod - NumRegs]. rax, rdx and rcx, which division and shifts need, and rsi - and rdi, which copying needs, aren't among them. *) - NumRegs = 4; - Regs: [NumRegs]INT = [R8, R9, R10, R11]; - XRegs: [NumRegs]INT = [8, 9, 10, 11]; (* xmm8 to xmm11 *) - IntRegs: [6]INT = [RDI, RSI, RDX, RCX, R8, R9]; - -var - stack: [MaxStack]Entry; - owner: [NumRegs]INT; (* the value in each register, or -1 *) - frameTop, frameMax, permTop: I64; - frameFix: INT; (* where the frame size is patched in *) - paramTop: I64; (* the parameters' slots end here *) - zeroTop: I64; (* the locals the prologue zeroes end here *) - retSlot: I64; (* holds the hidden result pointer *) - resType: ^Sym.Type; (* the procedure's result, or nil *) - exitL: INT; - (* parameters arriving in registers: where each is stored on entry *) - inReg: [14]INT; - inSlot: [14]I64; - inSize: [14]INT; - inObj: [14]^Sym.Obj; - numIn: INT; - procParams: ^Sym.Obj; (* the parameters, for enterBody *) - regMask: INT; (* the registers of variables, as bits (XBit) *) - kept: INT; (* bit r: register r holds a parameter, as it arrived *) - saveAt: I64; (* where they are saved, a quadword each *) - homes: [8]I64; (* the slots of the variables in XVarRegs *) - frameAt: [3]I64; (* frameTop, frameMax, permTop after the declarations *) - fails: [4096]Fail; - numFails: INT; - -proc setInPlace*(r: INT); -begin - inPlace := r; -end; - -proc kindOf*(t: ^Sym.Type): Kind; -begin - if t^.form = Sym.fReal then - if t^.size = 4 then return kF32; end; - return kF64; - end; - if t^.size > WordSize then return kLong; end; - return kWord; -end; - -(* The stack, as in Wirth's compilers: the value at depth d is held in - 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; xmm0 and xmm1 for reals. - - A real, an F32 or an F64, is held in xmm8 to xmm11 (XRegs), where the - machine computes with reals, the value at depth d in XRegs[d mod - NumRegs]: so each depth has two registers, and holds its value in the - one of its kind, which owner doesn't tell apart. The xmm registers - from xmm8 up carry no arguments, so that call can move a real into - xmm0 to xmm7 without overwriting another still to go. *) - -proc fits32(v: I64): BOOL; -begin - return (v >= -2147483648) and (v <= 2147483647); -end; - -(* The register of kind k for the value at depth i *) -proc regIn(k: Kind; i: INT): INT; -begin - if k in {kF32, kF64} then return XRegs[i mod NumRegs]; end; - return Regs[i mod NumRegs]; -end; - -proc regOf(i: INT): INT; -begin - return regIn(stack[i].k, i); -end; - -proc isReal(i: INT): BOOL; -begin - return stack[i].k in {kF32, kF64}; -end; - -(* A real constant, its bits v, as an operand: 8 bytes in read-only - data, as the machine has no instruction that holds one *) -proc realConst(v: I64): X.Mem; -var c: INT; -begin - c := Chunk.newChunk(Chunk.secRodata, -1, -1); - Chunk.setData(c, ^U8(SYSTEM.ADR(v)), 8, 8); - return X.memRip(c, 0); -end; - -(* The real i into xmm register x, from wherever it is, as valueTo does - for an integer register *) -proc xValueTo(i, x: INT); -begin - match stack[i].loc of - | lConst: X.movsXM(x, realConst(stack[i].val), stack[i].k = kF32); - | lMem: X.movsXM(x, stack[i].m, stack[i].size = 4); - | lHeld: if INT(stack[i].val) # x then X.movX(x, INT(stack[i].val)); end; - | lInto: if INT(stack[i].val) # x then X.movX(x, INT(stack[i].val)); end; - | lReg: if regOf(i) # x then X.movX(x, regOf(i)); end; - | else: X.movsXM(x, X.mem(RBP, stack[i].val), false); (* spilled, as 8 bytes *) - end; -end; - -proc loaded(i: INT): INT; forward; -proc allocPerm*(size, align: I64): I64; forward; -proc allocTemp*(size, align: I64): I64; forward; - -(* The value i, in a register, goes to a frame slot; one noted that - holds its register, as an index, is worked out in it first *) -proc spill(i: INT); -var s: I64; -begin - if (stack[i].loc # lReg) or (stack[i].off # 0) then _ := loaded(i); end; - s := allocTemp(8, 8); - if isReal(i) then X.movsMX(X.mem(RBP, s), regOf(i), false); - else X.store(X.mem(RBP, s), regOf(i), 8); end; - stack[i].loc := lFrame; - stack[i].val := s; - owner[i mod NumRegs] := -1; -end; - -(* Each value below depth d read from memory now, as what comes next - may change it *) -proc readMems(d: INT); -var i: INT; -begin - for i := 0 to d - 1 do - if stack[i].loc = lMem then _ := loaded(i); end; - end; -end; - -(* Every value below depth d in a register, spilled; one noted in memory - is read first, as a call may change it *) -proc spillBelow(d: INT); -var r: INT; -begin - readMems(d); - for r := 0 to NumRegs - 1 do - if (owner[r] >= 0) and (owner[r] < d) then spill(owner[r]); end; - end; -end; - -(* The register of kind k of value i, for it to hold: a lower value at - its depth's registers is spilled. *) -proc claim(i: INT; k: Kind): INT; -var r: INT; -begin - r := i mod NumRegs; - if (owner[r] >= 0) and (owner[r] # i) then spill(owner[r]); end; - owner[r] := i; - return regIn(k, i); -end; - -(* The memory at the noted address i, plus off *) -proc adrMem(i: INT; off: I64): X.Mem; -begin - if stack[i].chunk < 0 then return X.mem(RBP, stack[i].val + off); end; - return X.memRip(stack[i].chunk, INT(stack[i].val + off)); -end; - -(* The value i, in its register *) -proc loaded(i: INT): INT; -var r: INT; -begin - if stack[i].loc = lInto then return INT(stack[i].val); end; - if (stack[i].loc # lReg) and isReal(i) then - xValueTo(i, claim(i, stack[i].k)); - stack[i].loc := lReg; - elsif stack[i].loc # lReg then - r := claim(i, kWord); - match stack[i].loc of - | lConst: X.movRI(r, stack[i].val); - | lHeld: X.movRR(r, INT(stack[i].val)); - | lAdr: X.lea(r, adrMem(i, 0)); - | lIdx: X.lea(r, stack[i].m); - | lMem: X.load(r, stack[i].m, stack[i].size, stack[i].signed); - | else: X.load(r, X.mem(RBP, stack[i].val), 8, false); - end; - stack[i].loc := lReg; - end; - if stack[i].off # 0 then - X.lea(regOf(i), X.mem(regOf(i), stack[i].off)); - stack[i].off := 0; - end; - return regOf(i); -end; - -(* The register value i is in, only to be read: a variable's own, or - its register *) -proc peek(i: INT): INT; -begin - if (stack[i].loc = lHeld) and (stack[i].off = 0) then return INT(stack[i].val); end; - return loaded(i); -end; - -(* The offset of value i, taken from it, for the caller to add or to - make a displacement of *) -proc takeOff(i: INT): I64; -var o: I64; -begin - o := stack[i].off; - stack[i].off := 0; - return o; -end; - -(* The word on top, in a register, has o added: noted, if o can be a - displacement, else added now *) -proc putOff(o: I64); -begin - if fits32(stack[depth - 1].off + o) then - stack[depth - 1].off := stack[depth - 1].off + o; - else - X.movRI(RCX, o); - X.alu(X.aluAdd, loaded(depth - 1), RCX); - end; -end; - -proc top: INT; -begin - if depth = 0 then Diag.fatal("internal error: the stack is empty"); end; - return loaded(depth - 1); -end; - -(* A value on the stack's top. At the stack's last place the error is shown - and the compile ends there: with nothing pushed, the pops after it would - go below the stack. See the head of this unit. *) -proc newEntry(k: Kind; loc: Loc; v: I64); -begin - if depth > LEN(stack) - 1 then - _ := Scan.mark(Diag.say("more than {} values waiting in one expression", [Fmt.int(MaxStack)])); - Diag.finish(); (* ends the compile: an error was counted *) - return; - end; - stack[depth].k := k; - stack[depth].loc := loc; - stack[depth].val := v; - stack[depth].chunk := -1; - stack[depth].off := 0; - INC(depth); -end; - -(* An address, lIdx, or a value at it, lMem, noted as the operand m. Its - index may be in the register of the value just dropped, at this - depth: it is the new value's own, then. *) -proc newMem(loc: Loc; m: X.Mem; k: Kind; size: INT; signed: BOOL); -begin - newEntry(k, loc, 0); - stack[depth - 1].m := m; - stack[depth - 1].size := size; - stack[depth - 1].signed := signed; - if m.index = Regs[(depth - 1) mod NumRegs] then owner[(depth - 1) mod NumRegs] := depth - 1; end; -end; - -(* The register a new value on top is to be computed in *) -proc target: INT; -begin - return claim(depth, kWord); -end; - -(* The xmm register a new real on top is to be computed in *) -proc xTarget: INT; -begin - return claim(depth, kF64); -end; - -(* The value just computed in target goes on top *) -proc computed(k: Kind); -begin - newEntry(k, lReg, 0); -end; - -proc drop*; -begin - DEC(depth); - if owner[depth mod NumRegs] = depth then owner[depth mod NumRegs] := -1; end; -end; - -(* rsi and rdi are about to be used for other work, as in copying: a - parameter kept in either must go to memory (lost). *) -proc clobberArgs; -begin - if kept # 0 then lost := true; end; -end; - -(* The value i into register r, from wherever it is: a constant or an - address is made there, a variable's register or the value's own - register copied, a spilled value loaded. Unlike loaded, it leaves the - value where it was, so r is its only new copy. *) -proc valueTo(i, r: INT); -begin - if isReal(i) and (stack[i].loc in {lHeld, lInto}) then - X.movqRX(r, INT(stack[i].val)); - else - match stack[i].loc of - | lConst: X.movRI(r, stack[i].val); - | lHeld: X.movRR(r, INT(stack[i].val)); - | lInto: X.movRR(r, INT(stack[i].val)); - | lAdr: X.lea(r, adrMem(i, 0)); - | lIdx: X.lea(r, stack[i].m); - | lMem: X.load(r, stack[i].m, stack[i].size, stack[i].signed); - | lReg: - if isReal(i) then X.movqRX(r, regOf(i)); - elsif regOf(i) # r then X.movRR(r, regOf(i)); end; - | else: X.load(r, X.mem(RBP, stack[i].val), 8, false); - end; - end; - if stack[i].off # 0 then X.lea(r, X.mem(r, stack[i].off)); end; -end; - -(* The value on top, popped into register r *) -proc popTo(r: INT); -begin - valueTo(depth - 1, r); - drop(); -end; - -(* Whether the value on top is a constant, and if so, which *) -proc topConst: (BOOL, I64); -begin - return stack[depth - 1].loc = lConst, stack[depth - 1].val; -end; - -proc resetStack*(d, p: INT); -var r: INT; -begin - depth := d; - pushed := p; - for r := 0 to NumRegs - 1 do owner[r] := -1; end; -end; - -proc pushConst*(k: Kind; v: I64); -begin - newEntry(k, lConst, v); -end; - -(* The register of the word at a, a variable in registers: the variable's - own, or for a slice its pointer's (off 0) or its length's (off 8) *) -proc regAt(a: Adr): INT; -var r: INT; -begin - if a.off = 0 then r := a.chunk; else r := a.hi; end; - if r >= XmmVar then r := r - XmmVar; end; (* an xmm register, XVarRegs *) - return r; -end; - -(* The memory a names. An address on the stack is popped, and is in its - register still; one in a slot is loaded into r. *) -proc place(a: Adr; r: INT): X.Mem; -var m: X.Mem; ra: INT; o: I64; -begin - if a.base = bReg then Diag.fatal("internal error: a register has no address"); end; - match a.base of - | bFrame: return X.mem(RBP, a.off); - | bGlobal: return X.memRip(a.chunk, INT(a.off)); - | bStack: - if stack[depth - 1].loc = lAdr then - m := adrMem(depth - 1, a.off); - drop(); - return m; - elsif stack[depth - 1].loc = lIdx then - m := stack[depth - 1].m; - m.disp := m.disp + INT(a.off); - drop(); - return m; - end; - (* an offset noted on the address is the operand's, as - p^.f + 8: [r8 + 8] *) - if fits32(a.off + stack[depth - 1].off) then o := takeOff(depth - 1); else o := 0; end; - ra := peek(depth - 1); - drop(); - return X.mem(ra, a.off + o); - | bPtr: return X.mem(a.chunk, a.off); - | else: (* bSlot: the address is in the frame slot a.chunk *) - X.load(r, X.mem(RBP, a.chunk), 8, false); - return X.mem(r, a.off); - end; -end; - -(* The address a names, on top of the stack *) -proc pushAdr*(a: Adr); -var m: X.Mem; r: INT; -begin - if (a.base = bStack) and (a.off = 0) then return; end; (* it is on top already *) - if a.base in {bFrame, bGlobal} then - newEntry(kWord, lAdr, a.off); - if a.base = bGlobal then stack[depth - 1].chunk := a.chunk; end; - return; - 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 - m := place(a, -1); r := target(); - else - r := target(); m := place(a, r); - end; - (* an address that is already in r, [r], needs no instruction *) - if (m.base # r) or (m.index # X.NoIndex) or (m.disp # 0) then X.lea(r, m); end; - computed(kWord); -end; - -proc pushVar*(a: Adr; size: INT; signed: BOOL; k: Kind); -var m: X.Mem; r: INT; -begin - r := inPlace; - inPlace := -1; - if r >= XmmVar then r := r - XmmVar; end; - if (a.base = bReg) and (regAt(a) = r) then - newEntry(k, lInto, r); - return; - end; - if a.base = bReg then - newEntry(k, lHeld, regAt(a)); - return; - end; - (* a variable in the frame or a chunk, or at an address only noted, is - only noted too: read where it is used, as an operand if it can be *) - if (a.base in {bFrame, bGlobal, bPtr}) or (a.base = bStack) and (stack[depth - 1].loc in {lAdr, lIdx}) then - m := place(a, -1); - newMem(lMem, m, k, size, signed); - return; - end; - (* in the order pushAdr explains *) - if a.base = bStack then - m := place(a, -1); r := target(); - else - r := target(); m := place(a, r); - end; - if k in {kF32, kF64} then X.movsXM(xTarget(), m, size = 4); - else X.load(r, m, size, signed); end; - computed(k); -end; - -proc pushProc*(c: INT; ext: BOOL); -var r: INT; -begin - r := target(); - if ext then X.load(r, X.memRip(c, 0), 8, false); - else X.lea(r, X.memRip(c, 0)); end; - computed(kWord); -end; - -(* Where xmm register r is in XVarRegs *) -proc xIndex(r: INT): INT; -begin - if r >= XVarRegs[0] then return r - XVarRegs[0]; end; - return r - XVarRegs[4] + 4; -end; - -(* The slot of the variable in xmm register x *) -proc homeOf(x: INT): X.Mem; -begin - return X.mem(RBP, homes[xIndex(x + XmmVar)]); -end; - -(* Pops a value into the variable at a; an address on the stack is under - the value. *) -proc popVar*(a: Adr; size: INT); -var r: INT; v: I64; c, fl: BOOL; -begin - if (a.base = bReg) and isReal(depth - 1) then - xValueTo(depth - 1, regAt(a)); - drop(); - X.movsMX(homeOf(regAt(a)), regAt(a), false); (* written through, as xHome says *) - return; - end; - if a.base = bReg then - c, v := topConst(); - if c then X.movRI(regAt(a), v); - elsif peek(depth - 1) # regAt(a) then X.movRR(regAt(a), peek(depth - 1)); end; (* else it is there, lInto *) - drop(); - return; - end; - c, v := topConst(); - if c and fits32(v) then - drop(); - X.storeI(place(a, RCX), INT(v), size); - return; - end; - if c then r := RAX; X.movRI(RAX, v); - else r := peek(depth - 1); end; - fl := (stack[depth - 1].loc # lConst) and isReal(depth - 1); - drop(); - if fl then X.movsMX(place(a, RCX), r, size = 4); - else X.store(place(a, RCX), r, size); end; -end; - -(* Register src to dst, an xmm register's if fl *) -proc movReg(fl: BOOL; dst, src: INT); -begin - if fl then X.movX(dst, src); else X.movRR(dst, src); end; -end; - -(* The two values on top, of one kind, change places. *) -proc swap*; -var e: Entry; x, y, t: INT; rx, ry, fl: BOOL; -begin - x := depth - 2; y := depth - 1; - (* a value noted at an address that uses its register is worked out, - so that its register moves with it *) - if stack[x].loc in {lIdx, lMem} then _ := loaded(x); end; - if stack[y].loc in {lIdx, lMem} then _ := loaded(y); end; - rx := stack[x].loc = lReg; - ry := stack[y].loc = lReg; - fl := isReal(y); - if fl then t := 0; else t := RAX; end; (* xmm0, or rax *) - if rx and ry then - movReg(fl, t, regOf(x)); - movReg(fl, regOf(x), regOf(y)); - movReg(fl, regOf(y), t); - elsif rx then - owner[x mod NumRegs] := -1; - movReg(fl, claim(y, stack[y].k), regOf(x)); - elsif ry then - owner[y mod NumRegs] := -1; - movReg(fl, claim(x, stack[x].k), regOf(y)); - end; - e := stack[x]; stack[x] := stack[y]; stack[y] := e; -end; - -(* Copying *) - -(* The most that copyBytes and zeroBytes do with moves, in place of rep - movsb and rep stosb, which take some twenty cycles to start, longer - than the few moves take. *) -const MaxMoves = 256; - -(* Up to this size a copy goes as words: a record just made field by - field is read back by loads as wide as its stores, and a 16-byte - load across two 8-byte stores waits for them to reach the cache. *) -const MaxWordMoves = 64; - -(* size bytes from [rsi] to [rdi], through xmm0 and rcx; rsi and rdi are - left as they fall. Up to MaxMoves bytes, as a record or a small array - mostly is, they go as moves: of 16 bytes from MaxWordMoves up, then - of 8, 4, 2 and 1. *) -proc copyBytes(size: I64); -var o, n: I64; -begin - if size > MaxMoves then - X.movRI(RCX, size); - X.repMovsb(); - return; - end; - o := 0; - while (size > MaxWordMoves) and (o + 16 <= size) do - X.movdquXM(0, X.mem(RSI, o)); - X.movdquMX(X.mem(RDI, o), 0); - INC(o, 16); - end; - while o < size do - n := 8; - while n > size - o do n := n div 2; end; - X.load(RCX, X.mem(RSI, o), INT(n), false); - X.store(X.mem(RDI, o), RCX, INT(n)); - INC(o, n); - end; -end; - -(* Pops a source's address, and a destination's under it, and copies - size bytes to off bytes past the destination. *) -proc copyBlock*(size, off: I64); -begin - clobberArgs(); - popTo(RSI); - popTo(RDI); - if off # 0 then X.lea(RDI, X.mem(RDI, off)); end; - copyBytes(size); -end; - -(* Pops a source's address, and copies size bytes to a: for a slice in - registers, its two words into them. *) -proc copyTo*(a: Adr; size: I64); -begin - clobberArgs(); - popTo(RSI); - if a.base = bReg then - X.load(a.chunk, X.mem(RSI, 0), 8, false); - X.load(a.hi, X.mem(RSI, 8), 8, false); - return; - end; - X.lea(RDI, place(a, RDI)); - copyBytes(size); -end; - -(* size zero bytes at [rdi], through xmm0 and rax; rdi is left as it - falls. Up to MaxMoves bytes they go as stores of 16, then of 8, 4, 2 - and 1 bytes, as copyBytes does. *) -proc zeroBytes(size: I64); -var o, n: I64; -begin - if size > MaxMoves then - X.movRI(RAX, 0); - X.movRI(RCX, size); - X.repStos(1); - return; - end; - o := 0; - if size >= 16 then X.pxorXX(0); end; - while o + 16 <= size do - X.movdquMX(X.mem(RDI, o), 0); - INC(o, 16); - end; - if o < size then X.movRI(RAX, 0); end; - while o < size do - n := 8; - while n > size - o do n := n div 2; end; - X.store(X.mem(RDI, o), RAX, INT(n)); - INC(o, n); - end; -end; - -proc zeroVar*(a: Adr; size: I64); -begin - clobberArgs(); - X.lea(RDI, place(a, RDI)); - zeroBytes(size); -end; - -(* Operations *) - -(* n if v is 2^n, which is 0 for 1; -1 if v isn't a power of two *) -proc exactLog2(v: I64): INT; -var n: INT; -begin - n := 0; - while (v > 1) and ((v & 1) = 0) do v := v shr 1; INC(n); end; - if v # 1 then n := -1; end; - return n; -end; - -(* r times v, a size: by a shift where v is a power of two, as it - mostly is, since a shift takes one cycle and imul three *) -proc mulI(r: INT; v: I64); -begin - if exactLog2(v) > 0 then X.shiftI(X.shShl, r, exactLog2(v)); - elsif v # 1 then X.imulI(r, INT(v)); end; -end; - -(* r compared with v, through rdx if v needs more than 32 bits; with - zero by test, which sets the flags as cmp would and is shorter *) -proc cmpI(r: INT; v: I64); -begin - if v = 0 then X.testRR(r, r); - elsif fits32(v) then X.aluI(X.aluCmp, r, INT(v)); - else X.movRI(RDX, v); X.alu(X.aluCmp, r, RDX); end; -end; - -(* r div or mod 2^k, 1 <= k <= 62, with shifts: div truncates towards - zero, so a negative dividend first gets 2^k - 1 added (the bias). *) -proc divPow2(sy: Scan.Sym; r, k: INT; unsign: BOOL); -begin - (* unsigned: div shifts right; mod keeps the low k bits, by shifting - them up to the top and back down *) - if unsign then - if sy = Scan.sDiv then X.shiftI(X.shShr, r, k); - else X.shiftI(X.shShl, r, 64 - k); X.shiftI(X.shShr, r, 64 - k); end; - return; - 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. *) - X.movRR(RCX, r); - X.shiftI(X.shSar, RCX, 63); - X.shiftI(X.shShr, RCX, 64 - k); - X.alu(X.aluAdd, RCX, r); - X.shiftI(X.shSar, RCX, k); - if sy = Scan.sDiv then X.movRR(r, RCX); - else X.shiftI(X.shShl, RCX, k); X.alu(X.aluSub, r, RCX); end; -end; - -(* Before rax div y, of a signed type of bits < 64: its smallest value - divided by -1 overflows it, which must stop the program as it does for - an I64 (report section 6.1). idiv on the 64-bit values wouldn't fault, - so then rax is made the smallest I64, and it does. *) -proc divTrap(bits, y: INT); -var L: INT; -begin - L := NoLabel; - cmpI(y, -1); - X.jcc(X.ccNE, L); - cmpI(RAX, I64(-1) shl (bits - 1)); - X.jcc(X.ccNE, L); - X.shiftI(X.shShl, RAX, 64 - bits); - X.fixLink(L); -end; - -(* Whether the value on top is a word in memory that can be the right - operand of an instruction as it is: add r, [m] *) -proc topInMem: BOOL; -begin - return (stack[depth - 1].loc = lMem) and (stack[depth - 1].size = 8); -end; - -(* The right operand of the two values on top, popped, in register y: - its own, or rcx for a constant; the left one stays, in its register, - which is returned with y. *) -proc operands: (INT, INT); -var v: I64; c: BOOL; y: INT; -begin - c, v := topConst(); - if c then X.movRI(RCX, v); y := RCX; else y := peek(depth - 1); end; - drop(); - return top(), y; -end; - -(* The two reals on top, the left op the right, worked out in the left's - xmm register. The right is taken from memory where it is, as a - constant, a variable or a spilled value is: mulsd xmm8, [rbp - 16]. *) -proc realOp(sy: Scan.Sym; k: Kind); -var f: BOOL; c, x, y: INT; m: X.Mem; -begin - f := k = kF32; - match sy of - | sPlus: c := 58H; (* addsd, or addss for an F32 *) - | sMinus: c := 5CH; (* subsd, subss *) - | sTimes: c := 59H; (* mulsd, mulss *) - | else: c := 5EH; (* divsd, divss *) - end; - if stack[depth - 1].loc in {lConst, lMem, lFrame} then - match stack[depth - 1].loc of - | lConst: m := realConst(stack[depth - 1].val); - | lMem: m := stack[depth - 1].m; - | else: m := X.mem(RBP, stack[depth - 1].val); - end; - drop(); - X.sseM(c, top(), m, f); - else - y := peek(depth - 1); - drop(); - x := top(); - X.sse(c, x, y, f); - end; -end; - -(* The group 1 operation of +, -, &, | and xor *) -proc aluOf(sy: Scan.Sym): INT; -begin - match sy of - | sPlus: return X.aluAdd; - | sMinus: return X.aluSub; - | sAmp: return X.aluAnd; - | sBar: return X.aluOr; - | else: return X.aluXor; - end; -end; - -const - (* the condition codes of the comparisons, from sEql: = # < <= > >= *) - CcSigned: [6]INT = [X.ccE, X.ccNE, X.ccL, X.ccLE, X.ccG, X.ccGE]; - CcUnsigned: [6]INT = [X.ccE, X.ccNE, X.ccB, X.ccBE, X.ccA, X.ccAE]; - -(* The two values on top, the left op the right, an integer of size - bytes, signed or not, brought back to its width. *) -proc op*(sy: Scan.Sym; k: Kind; size: INT; signed: BOOL); -var v, o: I64; r, y, sh, bits: INT; c: BOOL; m: X.Mem; -begin - if k in {kF32, kF64} then realOp(sy, k); return; end; - bits := size * 8; - (* a constant on the left of an operation whose order doesn't matter - goes right, where it can be an immediate or a shift *) - 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) - and (stack[depth - 1].loc # lConst) then swap(); end; - c, v := topConst(); - (* A word's offset (see Entry) is carried through + and -, and - through * by a constant, as (x + a) * k is x * k + a * k: the - operation is done on the registers, the offsets worked out here, - and put on the result. x + 1 is only noted. A value changed in - place, lInto, has no offset. *) - o := 0; - if (bits = 64) and (stack[depth - 2].loc # lInto) - and ((((sy = Scan.sPlus) or (sy = Scan.sMinus))) or ((sy = Scan.sTimes) and c and fits32(v))) then - o := takeOff(depth - 2); - if sy = Scan.sTimes then o := o * v; - elsif c and fits32(v) then - if sy = Scan.sPlus then o := o + v; else o := o - v; end; - drop(); - if not (stack[depth - 1].loc in {lReg, lHeld}) then _ := top(); end; - putOff(o); - return; - elsif sy = Scan.sPlus then o := o + takeOff(depth - 1); - else o := o - takeOff(depth - 1); end; - end; - sh := -1; - if c and (((sy = Scan.sTimes) or (sy = Scan.sDiv) or (sy = Scan.sMod))) then sh := exactLog2(v); end; - if c and (sh >= 1) then - drop(); - r := top(); - if sy = Scan.sTimes then X.shiftI(X.shShl, r, sh); else divPow2(sy, r, sh, not signed); end; - 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 - drop(); - r := top(); - match sy of - | sTimes: X.imulI(r, INT(v)); - | sShl: X.shiftI(X.shShl, r, INT(v & I64(bits - 1))); - | sShr: - if signed then X.shiftI(X.shSar, r, INT(v & I64(bits - 1))); - else X.shiftI(X.shShr, r, INT(v & I64(bits - 1))); end; - | else: X.aluI(aluOf(sy), r, INT(v)); - end; - elsif topInMem() and (((sy = Scan.sPlus) or (sy = Scan.sMinus) or (sy = Scan.sAmp) or (sy = Scan.sBar) or (sy = Scan.sXor))) then - m := stack[depth - 1].m; - drop(); - r := top(); - X.aluM(aluOf(sy), r, m); - else - r, y := operands(); - if ((sy = Scan.sPlus) or (sy = Scan.sMinus) or (sy = Scan.sAmp) or (sy = Scan.sBar) or (sy = Scan.sXor)) then - X.alu(aluOf(sy), r, y); - elsif sy = Scan.sTimes then - X.imul(r, y); - elsif ((sy = Scan.sDiv) or (sy = Scan.sMod)) then - X.movRR(RAX, r); - if not signed then - X.movRI(RDX, 0); X.unary(6, y); (* div *) - else - (* 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); end; - X.cqo(); X.unary(7, y); (* idiv, of rdx:rax, which cqo made from rax *) - end; - if sy = Scan.sDiv then X.movRR(r, RAX); else X.movRR(r, RDX); end; - else (* sShl, sShr *) - (* the count modulo the width: the machine takes it modulo 64 *) - if y # RCX then X.movRR(RCX, y); end; - if bits < 64 then X.aluI(X.aluAnd, RCX, bits - 1); end; - if sy = Scan.sShl then X.shift(X.shShl, r); - elsif signed then X.shift(X.shSar, r); - else X.shift(X.shShr, r); end; - end; - end; - if bits < 64 then X.extend(r, size, signed); end; - stack[depth - 1].k := k; - if o # 0 then putOff(o); end; -end; - -(* ROL or ROR, by left, of the two values on top: an unsigned integer of - size bytes, under the count (report section 6.1). x86 takes the count - of rol and ror modulo 32, or 64 for a quadword, and a byte's or a - word's rotation then goes round modulo 8 or 16 itself: as 8 and 16 - divide 32, that is the count modulo the width, as the report has it, - with no mask of the count's own, which a shift needs. A constant - count is cut to the width here, an imm8; 0 rotates nothing. The bits - above the width are zero and stay so: rol al and rol ax leave them, - rol eax clears them. *) -proc rotate*(left: BOOL; size: INT); -var c: BOOL; v: I64; r, y, op: INT; -begin - if left then op := X.shRol; else op := X.shRor; end; - c, v := topConst(); - if c then - drop(); - r := top(); - v := v & I64(size * 8 - 1); - if v # 0 then X.rotate(op, r, size, INT(v)); end; - else - r, y := operands(); - if y # RCX then X.movRR(RCX, y); end; - X.rotate(op, r, size, -1); - end; - stack[depth - 1].k := kWord; -end; - -(* CLZ, if leading, or CTZ of the unsigned integer of size bytes on top - (report section 6.1). bsr finds the place h of its highest one bit, - and the zeros above it are the width less 1 less h; bsf finds the - place of its lowest, which is the zeros below it. Neither finds a - place in 0, the one value with no one bit, and both say so by ZF: - then the count is the whole width, as if h were -1, or the lowest - one at the width. The bits above size bytes are zero, so a scan of - all 64 sees the value's own. The baseline x86-64 lacks lzcnt and - tzcnt, which would count 0 by themselves. For a U32: - - bsr r, r bsf r, r - jnz L jnz L - mov r, -1 mov r, 32 - L: neg r L: - add r, 31 *) -proc countZeros*(leading: BOOL; size: INT); -var r, w, L: INT; -begin - r := top(); - w := size * 8; - L := NoLabel; - X.bitScan(leading, r); - X.jcc(X.ccNE, L); - if leading then X.movRI(r, -1); else X.movRI(r, w); end; - X.fixLink(L); - if leading then - X.unary(3, r); (* neg *) - X.aluI(X.aluAdd, r, w - 1); - end; - stack[depth - 1].k := kWord; -end; - -(* POPCOUNT of the integer or set on top (report section 6.1), counted - as lib/Bytes.raz counts bytes, without a loop: each two bits are - made the sum of their ones, then each four, then each byte, and a - multiplication by 0101...H adds the eight bytes' sums into the top - byte. The baseline x86-64 lacks popcnt. rax and rdx are - free between the stack machine's operations. - - mov rax, r; shr rax, 1; mov rdx, 5555...H; and rax, rdx; sub r, rax - mov rax, r; shr rax, 2; mov rdx, 3333...H; and rax, rdx; and r, rdx; add r, rax - mov rax, r; shr rax, 4; add r, rax; mov rdx, 0F0F...H; and r, rdx - mov rdx, 0101...H; imul r, rdx; shr r, 56 *) -proc popCount*; -var r: INT; -begin - r := top(); - (* each two bits: their value less its upper bit, which is its ones *) - X.movRR(RAX, r); - X.shiftI(X.shShr, RAX, 1); - X.movRI(RDX, 5555555555555555H); - X.alu(X.aluAnd, RAX, RDX); - X.alu(X.aluSub, r, RAX); - (* each four bits: the sums of its two pairs *) - X.movRR(RAX, r); - X.shiftI(X.shShr, RAX, 2); - X.movRI(RDX, 3333333333333333H); - X.alu(X.aluAnd, RAX, RDX); - X.alu(X.aluAnd, r, RDX); - X.alu(X.aluAdd, r, RAX); - (* each byte: the sums of its two halves, at most 8, which fits four bits *) - X.movRR(RAX, r); - X.shiftI(X.shShr, RAX, 4); - X.alu(X.aluAdd, r, RAX); - X.movRI(RDX, 0F0F0F0F0F0F0F0FH); - X.alu(X.aluAnd, r, RDX); - (* the top byte of r times 0101...H is the sum of all eight *) - X.movRI(RDX, 0101010101010101H); - X.imul(r, RDX); - X.shiftI(X.shShr, r, 56); - stack[depth - 1].k := kWord; -end; - -(* ABS of the real, or the signed integer of size bytes, on top (report - section 6.1); an unsigned one needs no code. A real's sign bit is - cleared, in rax, as neg flips it. An integer is negated, and its copy - in rax taken back if the negation is negative (SF), as it is for a - positive one. The smallest value negates to itself, negative, and so - gives itself, as -x does, with no branch and no check. A narrow - value is negated on all 64 bits, where its smallest is not the - smallest, so it is cut back to its width after, as neg does: - -128 in an I8 negates to 128, which is -128 again in 8 bits. - - movq rax, x; btr rax, 63; movq x, rax (F64; 31 for an F32) - mov rax, r; neg r; cmovs r, rax (I64; then movsx r, r for a narrow one) *) -proc abs*(k: Kind; size: INT); -var r: INT; -begin - r := top(); - if k in {kF32, kF64} then - X.movqRX(RAX, r); - if k = kF32 then X.btr(RAX, 31); else X.btr(RAX, 63); end; - X.movqXR(r, RAX); - else - X.movRR(RAX, r); - X.unary(3, r); (* neg *) - X.cmov(X.ccS, r, RAX); - if size < 8 then X.extend(r, size, true); end; - end; -end; - -(* The left op the right of the two values on top, as a BOOL *) -proc compare*(sy: Scan.Sym; k: Kind; signed: BOOL); -var f: BOOL; r, x, y, i: INT; v: I64; c: BOOL; m: X.Mem; -begin - i := INT(sy) - INT(Scan.sEql); - if k in {kF32, kF64} then - f := k = kF32; - y := peek(depth - 1); - drop(); - x := peek(depth - 1); - drop(); - r := target(); (* the BOOL, in the left's integer register *) - (* 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. *) - match sy of - | sEql: X.ucomis(x, y, f); X.setCC(X.ccE, r); X.setCC(X.ccNP, RCX); X.alu(X.aluAnd, r, RCX); - | sNeq: X.ucomis(x, y, f); X.setCC(X.ccNE, r); X.setCC(X.ccP, RCX); X.alu(X.aluOr, r, RCX); - | sLss: X.ucomis(y, x, f); X.setCC(X.ccA, r); - | sLeq: X.ucomis(y, x, f); X.setCC(X.ccAE, r); - | sGtr: X.ucomis(x, y, f); X.setCC(X.ccA, r); - | else: X.ucomis(x, y, f); X.setCC(X.ccAE, r); - end; - computed(kWord); - else - c, v := topConst(); - if c then - drop(); r := top(); cmpI(r, v); - elsif topInMem() then - m := stack[depth - 1].m; drop(); r := top(); X.aluM(X.aluCmp, r, m); - else - r, y := operands(); X.alu(X.aluCmp, r, y); - end; - if signed then X.setCC(CcSigned[i], r); else X.setCC(CcUnsigned[i], r); end; - end; - stack[depth - 1].k := kWord; -end; - -(* A real is negated by flipping its sign bit, in rax *) -proc neg*(k: Kind; size: INT; signed: BOOL); -var r: INT; -begin - r := top(); - if k in {kF32, kF64} then - X.movqRX(RAX, r); - if k = kF32 then X.btc(RAX, 31); else X.btc(RAX, 63); end; - X.movqXR(r, RAX); - else - X.unary(3, r); (* neg *) - if size < 8 then X.extend(r, size, signed); end; - end; -end; - -proc complement*(size: INT; signed: BOOL); -var r: INT; -begin - r := top(); - X.unary(2, r); (* not *) - if size < 8 then X.extend(r, size, signed); end; -end; - -proc notBool*; -begin - X.aluI(X.aluXor, top(), 1); -end; - -(* The integer on top, brought to size bytes *) -proc narrow*(size: INT; signed: BOOL); -var r: INT; -begin - r := top(); - if size < 8 then X.extend(r, size, signed); end; - stack[depth - 1].k := kWord; -end; - -(* The integer on top, as a real of kind k; big if it may be a U64 above - high(I64), which the machine would take as negative *) -proc intToReal*(k: Kind; big: BOOL); -var L1, L2, r, x: INT; f: BOOL; -begin - f := k = kF32; - r := top(); - x := regIn(k, depth - 1); (* its xmm register *) - if big then - (* above high(I64): halve, keeping the low bit, and double *) - L1 := NoLabel; L2 := NoLabel; - X.testRR(r, r); - X.jcc(X.ccS, L1); - X.cvtsi2s(x, r, f); - X.jmp(L2); - X.fixLink(L1); - X.movRR(RCX, r); - X.shiftI(X.shShr, RCX, 1); - X.aluI(X.aluAnd, r, 1); - X.alu(X.aluOr, RCX, r); - X.cvtsi2s(x, RCX, f); - X.sse(58H, x, x, f); (* adds it to itself: doubles *) - X.fixLink(L2); - else - X.cvtsi2s(x, r, f); - end; - stack[depth - 1].k := k; -end; - -(* The real of kind k on top, truncated to an integer *) -proc realToInt*(k: Kind); -var x: INT; -begin - x := top(); - X.cvtts2si(regIn(kWord, depth - 1), x, k = kF32); - stack[depth - 1].k := kWord; -end; - -(* The real of kind k on top, as the other kind *) -proc realToReal*(k: Kind); -var x: INT; -begin - x := top(); - X.sse(5AH, x, x, k = kF32); (* cvtss2sd, or cvtsd2ss *) - if k = kF32 then stack[depth - 1].k := kF64; else stack[depth - 1].k := kF32; end; -end; - -(* 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. *) -proc compareSeq*(a, b: I64; shift: INT; eq: BOOL); -var differ, r: INT; -begin - clobberArgs(); - r := target(); - X.load(RCX, X.mem(RBP, b + 8), 8, false); - X.aluM(X.aluCmp, RCX, X.mem(RBP, a + 8)); - differ := NoLabel; - X.jcc(X.ccNE, differ); - X.load(RSI, X.mem(RBP, b), 8, false); - X.load(RDI, X.mem(RBP, a), 8, false); - if shift > 0 then X.shiftI(X.shShl, RCX, shift); end; - (* repe cmpsb with rcx = 0 leaves the flags alone, so make them say - equal first, which is right if there are no bytes *) - X.alu(X.aluCmp, RCX, RCX); - X.repeCmpsb(); - X.fixLink(differ); - if eq then X.setCC(X.ccE, r); else X.setCC(X.ccNE, r); end; - computed(kWord); -end; - -(* 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. *) -proc errorText*(tmp: I64); -var L: INT; -begin - popTo(RAX); - X.movRI(RCX, 0); - L := NoLabel; - X.testRR(RAX, RAX); - X.jcc(X.ccE, L); - X.load(RCX, X.mem(RAX, 0), 8, false); - X.lea(RAX, X.mem(RAX, 8)); - X.fixLink(L); - X.store(X.mem(RBP, tmp), RAX, 8); - X.store(X.mem(RBP, tmp + 8), RCX, 8); -end; - -(* Pops a step and an integer variable's address, and adds the step to - it, or takes it away. *) -proc incDec*(size: INT; signed, dec: BOOL); -var r, y, o: INT; v: I64; a: Adr; c: BOOL; -begin - c, v := topConst(); - if dec then o := X.aluSub; else o := X.aluAdd; end; - if c and fits32(v) then - drop(); - a.base := bStack; a.off := 0; - X.aluMI(o, place(a, RCX), INT(v), size); - return; - end; - r, y := operands(); - drop(); - X.load(RAX, X.mem(r, 0), size, signed); - X.alu(o, RAX, y); - X.store(X.mem(r, 0), RAX, size); -end; - -(* INC or DEC of the variable in register r, by the value on top; a - narrow one wraps at its width *) -proc incDecReg*(r, size: INT; signed, dec: BOOL); -var y, o: INT; v: I64; c: BOOL; -begin - if dec then o := X.aluSub; else o := X.aluAdd; end; - c, v := topConst(); - if c and fits32(v) then X.aluI(o, r, INT(v)); - else y := top(); X.alu(o, r, y); end; - drop(); - if size < 8 then X.extend(r, size, signed); end; -end; - -(* The pointer on top, which NEW got, to size zero bytes unless nil *) -proc zeroNew*(size: I64); -var L, r: INT; -begin - clobberArgs(); - r := top(); - L := NoLabel; - X.testRR(r, r); - X.jcc(X.ccE, L); - X.movRR(RDI, r); - X.movRI(RCX, size); - X.movRI(RAX, 0); - X.repStos(1); - X.fixLink(L); -end; - -(* CAS(p, old, new), XCHG(p, v) or XADD(p, v), from the stack: the - result where p was *) -proc atomic*(which: INT); -var r, n: INT; -begin - if which = Sym.bCas then readMems(depth - 3); else readMems(depth - 2); end; (* what it writes may be one *) - if which = Sym.bCas then n := top(); drop(); end; - popTo(RAX); (* cmpxchg compares with rax, so CAS's old value goes there *) - r := top(); - match which of - | Sym.bCas: X.lockCmpxchg(X.mem(r, 0), n); X.setCC(X.ccE, r); - | Sym.bXchg: X.xchg(X.mem(r, 0), RAX); X.movRR(r, RAX); - | else: X.lockXadd(X.mem(r, 0), RAX); X.movRR(r, RAX); - end; - stack[depth - 1].k := kWord; -end; - -(* 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. *) -proc sysCall*(n: INT); -const SysRegs: [7]INT = [RAX, RDI, RSI, RDX, R10, R8, R9]; -var i: INT; -begin - clobberArgs(); - spillBelow(depth); - for i := 0 to n - 1 do valueTo(depth - n + i, SysRegs[i]); end; - for i := 1 to n do drop(); end; - X.syscall(); - X.movRR(target(), RAX); - computed(kWord); -end; - -proc fence*; -begin - X.mfence(); -end; - -(* Jumps. A label is the chain of the jumps to it, until it is placed. *) - -proc jump*(var L: INT); -begin - X.jmp(L); -end; - -(* Pops a BOOL, and jumps if it is when *) -proc jumpIf*(var L: INT; when: BOOL); -var r: INT; -begin - r := peek(depth - 1); - drop(); - X.testRR(r, r); - if when then X.jcc(X.ccNE, L); else X.jcc(X.ccE, L); end; -end; - -(* Pops two integers, and jumps if the left op the right *) -proc jumpCmp*(sy: Scan.Sym; signed: BOOL; var L: INT); -var r, y, i: INT; v: I64; c: BOOL; m: X.Mem; -begin - i := INT(sy) - INT(Scan.sEql); - (* a comparison changes neither: a variable's register will do *) - c, v := topConst(); - if c then - drop(); r := peek(depth - 1); cmpI(r, v); - elsif topInMem() then - m := stack[depth - 1].m; drop(); r := peek(depth - 1); X.aluM(X.aluCmp, r, m); - else - y := peek(depth - 1); drop(); r := peek(depth - 1); X.alu(X.aluCmp, r, y); - end; - drop(); - if signed then X.jcc(CcSigned[i], L); else X.jcc(CcUnsigned[i], L); end; -end; - -(* 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. 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. *) -proc jumpOut*(sy: Scan.Sym; signed: BOOL; var L: INT); -begin - spillBelow(depth - 2); - jumpCmp(sy, signed, L); -end; - -(* 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. *) -proc condValue*(notOp: Scan.Sym; signed: BOOL; fj, tj: INT); -var r, e: INT; -begin - jumpOut(notOp, signed, fj); - X.fixLink(tj); - r := target(); - X.movRI(r, 1); - e := NoLabel; - X.jmp(e); - X.fixLink(fj); - X.movRI(r, 0); - X.fixLink(e); - 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. *) -proc jumpBack*(top: INT); -begin - X.jmpBack(top); -end; - -proc fix*(L: INT); -begin - X.fixLink(L); -end; - -(* A jump table, for a match on the integer in frame slot slot, whose - labels run from lo up for n values. The selector less lo, compared - unsigned (so below lo is above n too), is out of the table if it - isn't below n, and goes to the else arm at elseAt, or, if there is - none, to endL, the end of the match. Else it indexes a table of - 4-byte offsets, each from the start of the lea, that follows the - jump, and the code jumps to its start plus the entry: - - mov rax, [slot] - sub rax, lo - cmp rax, n - 1 - ja else - lea rcx, [rip + start] start: this very lea - movsxd rax, [rcx + rax*4 + 17] - add rax, rcx - jmp rax - table: .long arm0 - start, arm1 - start, ... - - The four instructions after the compare are 7, 5, 3 and 2 bytes, so - the table is 17 bytes on, which jumpTable checks. It returns start; - the caller then makes the n entries with tableEntry. *) -proc jumpTable*(slot, lo: I64; n, elseAt: INT; var endL: INT): INT; -const TableAt = 17; -var start: INT; -begin - X.load(RAX, X.mem(RBP, slot), 8, false); - if lo # 0 then X.aluI(X.aluSub, RAX, INT(lo)); end; - X.aluI(X.aluCmp, RAX, n - 1); - if elseAt # NoLabel then X.jccBack(X.ccA, elseAt); else X.jcc(X.ccA, endL); end; - start := Chunk.pc; - X.lea(RCX, X.here()); - X.load(RAX, X.memIdx(RCX, RAX, 4, TableAt), 4, true); - X.alu(X.aluAdd, RAX, RCX); - X.jmpR(RAX); - if Chunk.pc # start + TableAt then Diag.fatal("internal error: the jump table is not where it was said"); end; - return start; -end; - -(* The next entry of the table that jumpTable started at table: the - code at target *) -proc tableEntry*(table, target: INT); -begin - Chunk.put4(target - table); -end; - -proc alignLoop*; -begin - X.align(32); -end; - -proc joinJumps*(L1, L2: INT): INT; -begin - return X.joinLinks(L1, L2); -end; - -proc fixTo*(L, top: INT); -begin - X.fixLinkTo(L, top); -end; - -(* Checks *) - -const - NoBase = -2; (* a Mem that is no memory *) - ARegister = -3; (* a Mem that is no memory but a register, its index *) - -(* The name s, interned *) -proc internStr(s: []const U8): INT; -begin - return Scan.intern(SYSTEM.PTR(s), LEN(s)); -end; - -(* 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, 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), a nil pointer (4), or a view at index a that runs - past a length len (7). 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, or in register m.index if it is ARegister. - rdi and rsi are passed on as they were, since a parameter may be kept - in them, for the trap report to show: so a goes to the stub in rax. - 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 (its line and column, worked out - now, while the source read is p's), never returns, and may use any - register once it has read what it needs. *) -proc check(cc, what: INT; p: Diag.Pos; ra: INT; m: X.Mem; n: I64; name: INT); -begin - if numFails > LEN(fails) - 1 then - _ := Scan.mark(Diag.say("more than {} checks in one procedure", [Fmt.int(LEN(fails))])); - return; - end; - fails[numFails].L := NoLabel; - X.jcc(cc xor 1, fails[numFails].L); (* x86's conditions come in pairs, the other one its last bit flipped *) - fails[numFails].what := what; - fails[numFails].ra := ra; - fails[numFails].m := m; - fails[numFails].n := n; - fails[numFails].name := name; - fails[numFails].path := Chunk.curFilePath(); - fails[numFails].line, fails[numFails].col := Scan.lineCol(p.a); - INC(numFails); -end; - -(* The failures of the procedure's checks: each gives Rt.fail its values - and the place of the offending expression, through a stub for its - kind, which takes the place from where it was called *) -proc endFails; -var i, path: INT; f: Fail; -begin - path := Chunk.curFilePath(); - for i := 0 to numFails - 1 do - f := fails[i]; - X.fixLink(f.L); - Chunk.setCurFile(f.path); - Chunk.noteLine(f.line, f.col); - Chunk.setCurFile(path); - if f.ra # RAX then X.movRR(RAX, f.ra); end; - if f.m.base = NoBase then X.movRI(RCX, f.n); - elsif f.m.base = ARegister then X.movRR(RCX, f.m.index); - else X.load(RCX, f.m, 8, false); end; - if f.name >= 0 then X.lea(R9, X.memRip(f.name, 0)); end; - if failStubs[f.what] < 0 then - failStubs[f.what] := Chunk.newChunk(Chunk.secText, internStr("Rt"), internStr(StubNames[f.what])); - end; - X.callChunk(failStubs[f.what]); - end; - numFails := 0; -end; - -(* For check: a length known here, not in memory *) -proc noMem: X.Mem; -begin - return X.mem(NoBase, 0); -end; - -(* For check: a length in register r, a slice's in registers *) -proc inRegister(r: INT): X.Mem; -var m: X.Mem; -begin - m := X.mem(ARegister, 0); - m.index := r; - return m; -end; - -(* The index on top is below n, unsigned *) -proc checkIndex*(n: I64; p: Diag.Pos); -var r: INT; -begin - r := peek(depth - 1); - cmpI(r, n); - check(X.ccB, 0, p, r, noMem(), n, -1); -end; - -(* The index on top is the element a view starts at, in an array of n - elements: the view needs k elements from there, so the index must be - below n - k + 1, which is below. A negative index is a huge one, - unsigned, so one comparison does (report section 6.9). *) -proc checkView*(n, below: I64; p: Diag.Pos); -var r: INT; -begin - r := peek(depth - 1); - cmpI(r, below); - check(X.ccB, 7, p, r, noMem(), n, -1); -end; - -(* What a failed index check is: an index past the length (0), or a - view that runs past it (7), when the view needs room elements more - than the one indexed. *) -proc kindOfIndex(room: I64): INT; -begin - if room > 0 then return 7; end; - return 0; -end; - -(* A view of a slice's element, at the index in r, needs room elements - after it: rdx holds the slice's length, which r is below already, - so length - r, at least 1, can't wrap, and must be more than room. - The length is at m for the message. *) -proc checkRoom(r: INT; room: I64; p: Diag.Pos; m: X.Mem); -begin - X.alu(X.aluSub, RDX, r); - X.aluI(X.aluCmp, RDX, INT(room)); - check(X.ccA, 7, p, r, m, 0, -1); -end; - -(* The integer on top is a position of an enumeration of n names *) -proc checkEnum*(n: I64; name: INT; p: Diag.Pos); -var r: INT; -begin - r := top(); - cmpI(r, n); - check(X.ccB, 2, p, r, noMem(), n, name); -end; - -(* The address on top, from a pointer, which is to be used reach bytes - past: the program stops if it is nil, unless the machine would stop - it, as for a reach within NilPage. *) -proc checkNil*(reach: I64; p: Diag.Pos); -var r: INT; -begin - if reach <= NilPage then return; end; - r := top(); - X.testRR(r, r); - check(X.ccNE, 4, p, r, noMem(), 0, -1); -end; - -(* The displacement disp of an element of size bytes, with the offset of - the index on top taken into it if it fits: s[k - 1] is [r13 + r9 * 8 - - 8] *) -proc indexOff(size, disp: I64): I64; -begin - if fits32(disp + stack[depth - 1].off * size) then return disp + takeOff(depth - 1) * size; end; - return disp; -end; - -(* Pops an index, and the address of the slice at a if it is on the - stack, and pushes the address of its element of size bytes: the - index, checked against the length, times size, plus the pointer. - It is worked out in the index's own register, which then holds the - address; but if the slice's address is on the stack, under the - index, the element's register is the one that holds that, still - needed, so the work is done in rax. A slice in registers is - compared with and added to them; for an element of 1, 2, 4 or 8 - bytes, its address is only noted, as the operand [pointer + index * - size], to be read or written where it is used (lIdx). *) -proc indexSlice*(a: Adr; size, room: I64; checked: BOOL; p: Diag.Pos); -var m, ml: X.Mem; r: INT; inRax: BOOL; o: I64; -begin - if (a.base = bReg) and (((size = 1) or (size = 2) or (size = 4) or (size = 8))) then - o := 0; - if not checked then o := indexOff(size, 0); end; - r := peek(depth - 1); - if checked then - X.alu(X.aluCmp, r, a.hi); - check(X.ccB, kindOfIndex(room), p, r, inRegister(a.hi), 0, -1); - if room > 0 then X.movRR(RDX, a.hi); checkRoom(r, room, p, inRegister(a.hi)); end; - end; - drop(); - newMem(lIdx, X.memIdx(a.chunk, r, INT(size), o), kWord, 8, false); - return; - end; - inRax := a.base = bStack; - if inRax then r := RAX; popTo(RAX); - else r := top(); drop(); end; - if a.base = bReg then - if checked then - X.alu(X.aluCmp, r, a.hi); - check(X.ccB, kindOfIndex(room), p, r, inRegister(a.hi), 0, -1); - if room > 0 then X.movRR(RDX, a.hi); checkRoom(r, room, p, inRegister(a.hi)); end; - end; - mulI(r, size); - X.alu(X.aluAdd, r, a.chunk); - else - m := place(a, RCX); - ml := m; ml.disp := ml.disp + 8; - if checked then - X.aluM(X.aluCmp, r, ml); - check(X.ccB, kindOfIndex(room), p, r, ml, 0, -1); - if room > 0 then X.load(RDX, ml, 8, false); checkRoom(r, room, p, ml); end; - end; - mulI(r, size); - X.aluM(X.aluAdd, r, m); - end; - if inRax then X.movRR(target(), RAX); - else _ := claim(depth, kWord); end; (* the index's register again, now for the address *) - computed(kWord); -end; - -(* Whether r is one of the stack's registers, not a variable's *) -proc isStackReg(r: INT): BOOL; -var i: INT; -begin - for i := 0 to NumRegs - 1 do - if Regs[i] = r then return true; end; - end; - return false; -end; - -(* Pops an index and the pointer under it, and pushes the address of - the element of size bytes: p + i * size. For an element of 1, 2, 4 - or 8 bytes it is only noted, as the operand [p + i * size] (lIdx), to - be read or written where it is used, when at most one of the two is - in a stack register, the register the new value owns. Otherwise lea - adds them up, in one instruction in place of a multiplication and an - addition. *) -proc indexPtr*(size: I64); -var b, x, own: INT; o: I64; -begin - o := 0; - if fits32(stack[depth - 2].off + stack[depth - 1].off * size) then - o := takeOff(depth - 2) + takeOff(depth - 1) * size; - end; - b := peek(depth - 2); - x := peek(depth - 1); - own := Regs[(depth - 2) mod NumRegs]; - drop(); - drop(); - if (not isStackReg(b) or (b = own)) and (not isStackReg(x) or (x = own)) then - newMem(lIdx, X.memIdx(b, x, INT(size), o), kWord, 8, false); - if b = own then owner[(depth - 1) mod NumRegs] := depth - 1; end; - else - X.lea(target(), X.memIdx(b, x, INT(size), o)); - computed(kWord); - end; -end; - -(* Pops an index, checked, and makes the address of the element it - picks of the array at a. An element of 1, 2, - 4 or 8 bytes is only noted, as the operand [base + index * size] - (lIdx): an array in the frame has rbp as its base, one reached - through a pointer in a register (a var or const parameter) that - register, and one in a chunk its address as the displacement - (X.memAbs), with no lea. Any other is added up. *) -proc indexArray*(a: Adr; size: I64); -var r: INT; o: I64; -begin - if (((size = 1) or (size = 2) or (size = 4) or (size = 8))) and (a.base in {bFrame, bGlobal, bPtr}) then - o := indexOff(size, a.off); - r := peek(depth - 1); - drop(); - if a.base = bFrame then - newMem(lIdx, X.memIdx(RBP, r, INT(size), o), kWord, 8, false); - elsif a.base = bPtr then - newMem(lIdx, X.memIdx(a.chunk, r, INT(size), o), kWord, 8, false); - else - newMem(lIdx, X.memAbs(a.chunk, r, INT(size), INT(o)), kWord, 8, false); - end; - else - mulI(top(), size); - pushAdr(a); - op(Scan.sPlus, kWord, 8, false); - end; -end; - -(* Pops lo and hi, and the address of the array or slice at a if it is - on the stack, and makes the slice lo..hi of it, with elements of size - bytes, in the frame at tmp; the array has n elements. *) -proc slice*(a: Adr; isArray: BOOL; n, size, tmp: I64; checked: BOOL; p: Diag.Pos); -var m, ml: X.Mem; -begin - popTo(RDX); - popTo(RCX); - if a.base = bSlot then clobberArgs(); end; (* place loads its slot into rdi *) - if a.base = bReg then - ml := inRegister(a.hi); (* a slice in registers *) - else - m := place(a, RDI); - ml := m; ml.disp := ml.disp + 8; - end; - if checked then - (* two checks, both unsigned, so that a negative bound fails too: - hi against the length, then lo against hi *) - if isArray then cmpI(RDX, n); ml := noMem(); - elsif a.base = bReg then X.alu(X.aluCmp, RDX, a.hi); - else X.aluM(X.aluCmp, RDX, ml); end; - check(X.ccBE, 1, p, RCX, ml, n, -1); - X.alu(X.aluCmp, RCX, RDX); - check(X.ccBE, 1, p, RCX, ml, n, -1); - end; - X.movRR(RAX, RDX); - X.alu(X.aluSub, RAX, RCX); - X.store(X.mem(RBP, tmp + 8), RAX, 8); - mulI(RCX, size); - if isArray then X.lea(RAX, m); - elsif a.base = bReg then X.movRR(RAX, a.chunk); - else X.load(RAX, m, 8, false); end; - X.alu(X.aluAdd, RAX, RCX); - X.store(X.mem(RBP, tmp), RAX, 8); -end; - -(* The rcx bytes below rsi to those below rdi, n at a time while rcx - holds n or more, through rax, moving rsi, rdi and rcx down: COPY's - backward copy, as a loop, since rep movsb going down (std) moves a - byte at a time. *) -proc copyDown(n: INT); -var top, out: INT; -begin - top := Chunk.pc; - X.aluI(X.aluCmp, RCX, n); - out := NoLabel; - X.jcc(X.ccB, out); - X.aluI(X.aluSub, RSI, n); - X.aluI(X.aluSub, RDI, n); - X.aluI(X.aluSub, RCX, n); - X.load(RAX, X.mem(RSI, 0), n, false); - X.store(X.mem(RDI, 0), RAX, n); - X.jmpBack(top); - X.fixLink(out); -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 at least as long - (the source may be shorter), as one block. It goes forwards, by rep - movsb, but backwards when the destination starts inside the source, - so that an overlap comes out right: by words from the ends, then the - last few bytes one by one. *) -proc copySlice*(dOff, sOff, size: I64; checked: BOOL; p: Diag.Pos); -var ml: X.Mem; L, E: INT; -begin - clobberArgs(); - X.load(RDX, X.mem(RBP, sOff + 8), 8, false); - if checked then - ml := X.mem(RBP, dOff + 8); - X.movRI(RAX, 0); - X.aluM(X.aluCmp, RDX, ml); - check(X.ccBE, 1, p, RAX, ml, 0, -1); - end; - X.movRR(RCX, RDX); - mulI(RCX, size); - X.load(RSI, X.mem(RBP, sOff), 8, false); - X.load(RDI, X.mem(RBP, dOff), 8, false); - L := NoLabel; - X.alu(X.aluCmp, RDI, RSI); - X.jcc(X.ccBE, L); (* the destination is not above: forwards, at L *) - X.lea(RAX, X.memIdx(RSI, RCX, 1, 0)); - X.alu(X.aluCmp, RDI, RAX); - X.jcc(X.ccAE, L); (* nor does it start inside the source *) - X.alu(X.aluAdd, RSI, RCX); (* backwards, from the ends *) - X.alu(X.aluAdd, RDI, RCX); - copyDown(8); - copyDown(1); - E := NoLabel; - X.jmp(E); - X.fixLink(L); - X.repMovsb(); - X.fixLink(E); -end; - -(* The most elements FILL stores one by one: as for MaxMoves, a store - each costs less than rep stos takes to start, which at 10 elements - is twice the time. *) -const FewFills = 16; - -(* rax, an element of size bytes, 1, 2, 4 or 8, into each of the - elements of the slice in the frame at dOff, of which there are n if - n isn't -1. Few, as of a short array, are a store each; else, at run - time, a loop of stores for fewer than FewFills, or rep stos of the - element's width: - - mov rdi, [rbp + dOff] - mov rcx, [rbp + dOff + 8] - cmp rcx, 16 - jae many - test rcx, rcx - jz out - top: mov [rdi], eax ; for a U32 - add rdi, 4 - sub rcx, 1 - jne top - jmp out - many: rep stosd - out: *) -proc fillScalar(dOff, size, n: I64); -var i: I64; many, out, top: INT; -begin - X.load(RDI, X.mem(RBP, dOff), 8, false); - if (n >= 0) and (n <= FewFills) then - for i := 0 to n - 1 do X.store(X.mem(RDI, i * size), RAX, INT(size)); end; - return; - end; - X.load(RCX, X.mem(RBP, dOff + 8), 8, false); - many := NoLabel; - out := NoLabel; - X.aluI(X.aluCmp, RCX, FewFills); - X.jcc(X.ccAE, many); - X.testRR(RCX, RCX); - X.jcc(X.ccE, out); - top := Chunk.pc; - X.store(X.mem(RDI, 0), RAX, INT(size)); - X.aluI(X.aluAdd, RDI, INT(size)); - X.aluI(X.aluSub, RCX, 1); - X.jccBack(X.ccNE, top); - X.jmp(out); - X.fixLink(many); - X.repStos(INT(size)); - X.fixLink(out); -end; - -(* The size bytes at rsi into each element of the slice in the frame at - dOff: into the first by copyBytes, and from there forward by rep - movsb, from d[0] on to d[1] on. A forward copy reads each byte after it has written it, size - bytes before, so the first element repeats through the rest: - - mov rdi, [rbp + dOff] - mov rdx, [rbp + dOff + 8] - test rdx, rdx - jz out ; nothing to fill - ... ; copyBytes(size): d[0] := x - mov rsi, [rbp + dOff] - lea rdi, [rsi + size] - lea rcx, [rdx - 1] - imul rcx, size ; the bytes of d[1..n] - rep movsb - out: *) -proc fillCopy(dOff, size: I64); -var out: INT; -begin - X.load(RDI, X.mem(RBP, dOff), 8, false); - X.load(RDX, X.mem(RBP, dOff + 8), 8, false); - X.testRR(RDX, RDX); - out := NoLabel; - X.jcc(X.ccE, out); - copyBytes(size); - X.load(RSI, X.mem(RBP, dOff), 8, false); - X.lea(RDI, X.mem(RSI, size)); - X.lea(RCX, X.mem(RDX, -1)); - mulI(RCX, size); - X.repMovsb(); - X.fixLink(out); -end; - -(* FILL: every element of the slice in the frame at dOff, of size bytes - each, set to the value on top of the stack if the element is a - scalar, or else to the size bytes at the address on top. n is how - many elements the slice has if that is known, as for an array, else - -1. A scalar goes into rax and is stored as it is, a real's bits as - an integer's (fillScalar); but a constant zero into an array of n - elements is n * size zero bytes, as NEW's zeroing is: by moves, or - rep stosb (zeroBytes). Any other element is copied (fillCopy). *) -proc fillSlice*(dOff, size, n: I64; scalar: BOOL); -var isConst: BOOL; v: I64; -begin - clobberArgs(); - isConst, v := topConst(); - if scalar and isConst and (v = 0) and (n >= 0) then - drop(); - X.load(RDI, X.mem(RBP, dOff), 8, false); - zeroBytes(n * size); - elsif scalar then - popTo(RAX); - fillScalar(dOff, size, n); - else - popTo(RSI); - fillCopy(dOff, size); - end; -end; - -(* Pops a pointer, lo and hi, and makes the slice p[lo..hi] at tmp. Its - bounds can't be known, but it can't run backwards. *) -proc slicePtr*(size, tmp: I64; checked: BOOL; p: Diag.Pos); -begin - clobberArgs(); - popTo(RDX); - popTo(RCX); - popTo(RDI); - if checked then - X.alu(X.aluCmp, RCX, RDX); - check(X.ccLE, 3, p, RCX, noMem(), 0, -1); - end; - X.movRR(RAX, RDX); - X.alu(X.aluSub, RAX, RCX); - X.store(X.mem(RBP, tmp + 8), RAX, 8); - mulI(RCX, size); - X.alu(X.aluAdd, RCX, RDI); - X.store(X.mem(RBP, tmp), RCX, 8); -end; - -(* Calls *) - -(* 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. *) - -proc call*(var c: CallInfo); -var - res: ^Sym.Type; i, ni, nf, k, pad, r, first: INT; - onStack: [64]BOOL; late: [2]INT; (* late: the values for r8 and r9 *) -begin - (* the arguments are the c.n values on top, where computing them left - them; the registers in use under them are saved around the call *) - clobberArgs(); - first := depth - c.n; - spillBelow(first); - res := c.sig^.base; - c.ret := 0; - ni := 0; nf := 0; - if (res # nil) and Sym.holdsArray(res) then - (* a slice of it may be kept for the rest of the procedure - (report 8), so its slot lasts as long *) - c.ret := allocPerm(res^.size, res^.align); - ni := 1; - elsif (res # nil) and (Sym.behindPointer(res) or (res^.form = Sym.fSlice)) then - c.ret := allocTemp(res^.size, res^.align); - if Sym.behindPointer(res) then ni := 1; end; - end; - (* the System V classes: each argument in the next free register of - its kind, or else on the stack *) - k := 0; - for i := 0 to c.n - 1 do - if c.isF[i] then - onStack[i] := nf >= 8; - if nf < 8 then INC(nf); end; - else - (* a slice's words both go in registers, or both on the stack *) - if (i > 0) and c.pair[i - 1] then onStack[i] := onStack[i - 1]; - elsif c.pair[i] then onStack[i] := ni > 4; - else onStack[i] := ni >= 6; end; - if not onStack[i] then INC(ni); end; - end; - if onStack[i] then INC(k); end; - end; - (* 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 := 0; - if ((pushed + k) & 1) # 0 then pad := 1; end; - if pad # 0 then X.aluI(X.aluSub, RSP, 8); end; - for i := c.n - 1 to 0 by -1 do - if onStack[i] then - valueTo(first + i, RAX); - X.push(RAX); - end; - end; - ni := 0; nf := 0; - late[0] := -1; late[1] := -1; - if (c.ret # 0) and Sym.behindPointer(res) then X.lea(RDI, X.mem(RBP, c.ret)); ni := 1; end; - (* rdi, rsi, rdx, rcx and the xmm registers first; r8 and r9 last, as - 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 - xValueTo(first + i, nf); - INC(nf); - else - if ni < 4 then valueTo(first + i, IntRegs[ni]); else late[ni - 4] := first + i; end; - INC(ni); - end; - end; - end; - if late[0] >= 0 then valueTo(late[0], RAX); end; - if late[1] >= 0 then valueTo(late[1], R9); end; - if late[0] >= 0 then X.movRR(R8, RAX); end; - for i := 1 to c.n do drop(); end; - (* a procedure taking ... is told in al how many xmm registers it got *) - if c.sig^.variadic then X.movRI(RAX, nf); end; - if c.ext then X.callM(X.memRip(c.chunk, 0)); - elsif c.chunk >= 0 then X.callChunk(c.chunk); - else - (* r11 is scratch: caller-saved, carrying no argument, and free, - as the value stack was spilled above *) - X.load(R11, X.mem(RBP, c.target), 8, false); - X.callR(R11); - end; - if k + pad > 0 then X.aluI(X.aluAdd, RSP, 8 * (k + pad)); end; - (* the variables in xmm registers, which the call may have changed, - from their slots *) - for i := 0 to LEN(XVarRegs) - 1 do - if (regMask & (1 shl (XBit + i))) # 0 then - X.movsXM(XVarRegs[i] - XmmVar, X.mem(RBP, homes[i]), false); - end; - end; - (* the result: a slice in rax and rdx goes to the caller's temporary, - two results on the stack, the first under the second, and a single - value on top *) - if res # nil then - if res^.form = Sym.fSlice then - X.store(X.mem(RBP, c.ret), RAX, 8); - X.store(X.mem(RBP, c.ret + 8), RDX, 8); - elsif Sym.inTwoRegs(res) then - X.movRR(target(), RAX); computed(kWord); - X.movRR(target(), RDX); computed(kWord); - elsif (c.ret = 0) and (res^.form = Sym.fReal) then - X.movX(xTarget(), 0); - computed(kindOf(res)); - elsif c.ret = 0 then - r := target(); - X.movRR(r, RAX); - if res^.form = Sym.fBool then X.extend(r, 1, false); - elsif (res^.form = Sym.fInt) and (res^.size < 8) then X.extend(r, INT(res^.size), res^.signed); end; - computed(kindOf(res)); - end; - end; -end; - -(* 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. *) -proc allocTemp*(size, align: I64): I64; -begin - if align < 1 then align := 1; end; - frameTop := Sym.alignUp(frameTop + size, align); - if frameTop > frameMax then frameMax := frameTop; end; - return -frameTop; -end; - -proc allocPerm*(size, align: I64): I64; -var s: I64; -begin - s := allocTemp(size, align); - permTop := frameTop; - return s; -end; - -proc tempMark*: I64; -begin - return frameTop; -end; - -(* The slots allocated since the mark m are free again, but those - allocPerm made stay *) -proc releaseTemps*(m: I64); -begin - if m < permTop then m := permTop; end; - frameTop := m; -end; - -(* Every slot used so far stays reserved for the rest of the procedure: - a deferred statement's temporaries live until it runs. *) -proc keepTemps*; -begin - frameTop := frameMax; - permTop := frameMax; -end; - -(* The parameters' places: each in a frame slot of its own, stored there - from its register on entry, or above the frame where the caller - pushed it. A var parameter, and a record or array passed by value, - holds an address (ind). *) -proc beginProc*(sig: ^Sym.Type; params: ^Sym.Obj); -var p: ^Sym.Obj; ni, nf, k: INT; stackOff: I64; f: BOOL; -begin - frameTop := 0; frameMax := 0; permTop := 0; - resetStack(0, 0); - exitL := NoLabel; - numIn := 0; - lost := false; - kept := 0; - resType := sig^.base; - procParams := params; - regMask := 0; - ni := 0; nf := 0; stackOff := 16; (* stackOff: above the saved rbp and the return address *) - if (resType # nil) and Sym.behindPointer(resType) then - retSlot := allocPerm(8, 8); - inReg[0] := RDI; inSlot[0] := retSlot; inSize[0] := 8; inObj[0] := nil; - numIn := 1; ni := 1; - end; - p := params; - while p # nil do - p^.ind := p^.isVar or (Sym.isAggregate(p^.typ) and (p^.typ^.form # Sym.fSlice)); - f := (p^.typ^.form = Sym.fReal) and not p^.isVar; - if (p^.typ^.form = Sym.fSlice) and not p^.isVar then - (* its two words, in two registers or both on the stack *) - if ni <= 4 then - p^.val := allocPerm(16, 8); - for k := 0 to 1 do - inReg[numIn] := IntRegs[ni]; inSlot[numIn] := p^.val + I64(8 * k); - inSize[numIn] := 8; inObj[numIn] := p; - INC(numIn); INC(ni); - end; - else - p^.val := stackOff; - INC(stackOff, 16); - end; - elsif (f and (nf < 8)) or (not f and (ni < 6)) then - 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 - inReg[numIn] := -1 - nf; INC(nf); - else - inReg[numIn] := IntRegs[ni]; INC(ni); - end; - inSlot[numIn] := p^.val; - inObj[numIn] := p; - if p^.ind then inSize[numIn] := 8; - elsif p^.typ^.form in {Sym.fInt, Sym.fBool, Sym.fEnum, Sym.fSet, Sym.fReal} then inSize[numIn] := INT(p^.typ^.size); - else inSize[numIn] := 8; end; - INC(numIn); - else - p^.val := stackOff; - INC(stackOff, 8); - end; - p := p^.next; - end; - paramTop := frameTop; -end; - -(* The frame as beginProc left it, with the parameters' slots only: the - locals are given theirs again once their registers are chosen. *) -proc resetLocals*; -begin - frameTop := paramTop; frameMax := paramTop; permTop := paramTop; -end; - -(* The register the word (0, or 1 for a slice's second) of parameter o - arrives in, or -1 if it comes on the stack or in an xmm register *) -proc arrivesIn(o: ^Sym.Obj; word: INT): INT; -var i, r: INT; -begin - r := -1; - for i := 0 to numIn - 1 do - if (inObj[i] = o) and (inSlot[i] = o^.val + I64(8 * word)) and (inReg[i] >= 0) then r := inReg[i]; end; - end; - return r; -end; - -(* Parameter o, of a procedure that calls nothing, stays in the register - it arrives in if that is rdi or rsi, which only a call or a copy needs: - no register is saved for it, and nothing is moved. A slice stays only - if it has both. If the procedure turns out to copy after all, lost is - set, and it is compiled again with o in memory. *) -proc keepArrived*(o: ^Sym.Obj); -var r: INT; -begin - r := arrivesIn(o, 0); - if o^.typ^.form = Sym.fSlice then - if (r = RDI) and (arrivesIn(o, 1) = RSI) then o^.reg := RDI; o^.reg2 := RSI; end; - elsif (r = RDI) or (r = RSI) then o^.reg := r; end; -end; - -(* Whether parameter o is kept where it arrived *) -proc keptIn*(o: ^Sym.Obj): BOOL; -begin - return (o^.reg = RDI) or (o^.reg = RSI); -end; - -(* The locals in memory have their slots: the prologue zeroes those and - nothing below. The procedure keeps variables in the registers of - mask, which are saved next, a quadword each, in slots that need no - zeroing; the frame as it then stands is where a second try at the - body starts. *) -proc useRegs*(mask: INT); -var i, k: INT; p: ^Sym.Obj; -begin - zeroTop := permTop; - regMask := mask; - (* the parameters left in rdi and rsi, as they arrived *) - kept := 0; - p := procParams; - while p # nil do - if ((p^.reg = RDI) or (p^.reg = RSI)) then kept := kept | (1 shl p^.reg); end; - if ((p^.reg2 = RDI) or (p^.reg2 = RSI)) then kept := kept | (1 shl p^.reg2); end; - p := p^.next; - end; - k := 0; - for i := 0 to 4 do - if (mask & (1 shl i)) # 0 then INC(k); end; - end; - if k > 0 then saveAt := allocPerm(8 * k, 8); end; - frameAt[0] := frameTop; frameAt[1] := frameMax; frameAt[2] := permTop; -end; - -(* The variable in xmm register r of XVarRegs has a slot of 8 bytes at - slot, kept as it changes *) -proc xHome*(r: INT; slot: I64); -begin - homes[xIndex(r)] := slot; -end; - -proc markCode*(var m: CodeMark); -begin - m.pc := Chunk.pc; m.fixups := Chunk.numFixups; m.lines := Chunk.numLines; m.said := X.saidCount(); - m.fails := numFails; m.exit := exitL; -end; - -(* The code made since m taken back, as if it had never been made; the - frame is left as it is *) -proc rewind*(m: CodeMark); -begin - Chunk.rewindTo(m.pc, m.fixups, m.lines); - X.unsay(m.said); - numFails := m.fails; - exitL := m.exit; (* a try or return in it made jumps to the exit *) -end; - -(* For a second try at the body: the code as it was at m, and the frame - as useRegs found it *) -proc redo*(m: CodeMark); -begin - Chunk.rewindTo(m.pc, m.fixups, m.lines); - X.unsay(m.said); - numFails := 0; - lost := false; - frameTop := frameAt[0]; frameMax := frameAt[1]; permTop := frameAt[2]; - exitL := NoLabel; -end; - -(* The prologue, which is for the procedure's first line. Only the - locals in memory are zeroed, from the parameters' slots down to - zeroTop: the parameters are stored over their slots next, the - registers of variables are zeroed in place, their save slots are - written before they are read, and so is every temporary. *) -proc enterBody*(c, line: INT); -var i, loop, r: INT; n: I64; p: ^Sym.Obj; -begin - Chunk.beginChunk(c); - codeChunk := c; - Chunk.noteLine(line, 1); (* a declaration starts a line *) - X.push(RBP); - X.movRR(RBP, RSP); - X.say("sub rsp, frame"); - (* sub rsp, imm32: always the form with a 32-bit field, so that endProc - can patch the frame's size in *) - Chunk.put1(48H); Chunk.put1(81H); Chunk.put1(0ECH); - frameFix := Chunk.pc; Chunk.put4(0); - n := (Sym.alignUp(zeroTop, 8) - paramTop) div 8; - if n = 1 then - X.movRI(RAX, 0); - X.store(X.mem(RBP, -paramTop - 8), RAX, 8); - elsif n > 1 then - (* the locals, 16 bytes at a time, from xmm8, which holds nothing - yet (xmm0 to xmm7 may hold a parameter): up to 16 stores in a - row, else a loop with r10 running from minus the bytes up to 0, - the store's address scaled by 1. An odd quadword is the - lowest. *) - X.pxorXX(8); - if n <= 32 then - for i := 0 to INT(n div 2) - 1 do - X.movdquMX(X.mem(RBP, -paramTop - 16 * I64(i + 1)), 8); - end; - else - X.movRI(R10, -16 * (n div 2)); - loop := Chunk.pc; - X.movdquMX(X.memIdx(RBP, R10, 1, -paramTop), 8); - X.aluI(X.aluAdd, R10, 16); - X.jccBack(X.ccNE, loop); - end; - if n mod 2 = 1 then - X.movRI(RAX, 0); - X.store(X.mem(RBP, -paramTop - 8 * n), RAX, 8); - end; - end; - (* each register that holds a variable is saved, for the caller, and - zeroed, as a variable starts at zero *) - Chunk.setSaves(c, regMask & ((1 shl XBit) - 1), INT(saveAt)); - n := 0; - for i := 0 to 4 do - if (regMask & (1 shl i)) # 0 then - X.store(X.mem(RBP, saveAt + 8 * n), VarRegs[i], 8); - X.movRI(VarRegs[i], 0); - INC(n); - end; - end; - (* and each xmm register that holds a variable, zeroed, as its slot - is: the caller keeps its own *) - for i := 0 to LEN(XVarRegs) - 1 do - if (regMask & (1 shl (XBit + i))) # 0 then - X.movRI(RAX, 0); - X.movqXR(XVarRegs[i] - XmmVar, RAX); - end; - end; - (* the parameters that came in registers, to their slots or, for a - register variable, to its register: a slice's second word, the one - for the slot 8 bytes into its own, to its length's *) - for i := 0 to numIn - 1 do - if inReg[i] < 0 then - X.movsMX(X.mem(RBP, inSlot[i]), -1 - inReg[i], false); - if inObj[i]^.reg # 0 then X.movX(inObj[i]^.reg - XmmVar, -1 - inReg[i]); end; - elsif (inObj[i] # nil) and (inObj[i]^.reg # 0) then - r := inObj[i]^.reg; - if inSlot[i] # inObj[i]^.val then r := inObj[i]^.reg2; end; - if r # inReg[i] then X.movRR(r, inReg[i]); end; (* else it is kept where it is *) - if inSize[i] < 8 then X.extend(r, inSize[i], inObj[i]^.typ^.signed); end; - else - X.store(X.mem(RBP, inSlot[i]), inReg[i], inSize[i]); - end; - end; - (* a register variable's parameter that came on the stack, above the - frame (val > 0), is loaded from there; one passed by its address - (ind: var, or const) holds the address, 8 bytes, whatever its type: - a var BOOL loaded as a byte was a bad pointer *) - p := procParams; - while p # nil do - if (p^.reg # 0) and (p^.val > 0) then - if p^.ind then - X.load(p^.reg, X.mem(RBP, p^.val), 8, false); - elsif p^.typ^.form = Sym.fReal then - X.movsXM(p^.reg - XmmVar, X.mem(RBP, p^.val), p^.typ^.size = 4); - elsif p^.typ^.form in {Sym.fInt, Sym.fBool, Sym.fEnum, Sym.fSet} then - X.load(p^.reg, X.mem(RBP, p^.val), INT(p^.typ^.size), p^.typ^.signed); - else - X.load(p^.reg, X.mem(RBP, p^.val), 8, false); - if p^.typ^.form = Sym.fSlice then X.load(p^.reg2, X.mem(RBP, p^.val + 8), 8, false); end; - end; - end; - p := p^.next; - end; -end; - -(* Pops one of several results, a value of size bytes, into its place - off bytes into the caller's, behind the hidden pointer. *) -(* The frame slot that holds the hidden result pointer *) -proc resultSlot*: I64; -begin - return retSlot; -end; - -proc resultTo*(off: I64; size: INT); -var r: INT; fl: BOOL; -begin - r := top(); - fl := isReal(depth - 1); - drop(); - X.load(RCX, X.mem(RBP, retSlot), 8, false); - if fl then X.movsMX(X.mem(RCX, off), r, size = 4); - else X.store(X.mem(RCX, off), r, size); end; -end; - -(* Pops an address, and copies size bytes from it to the result, off - bytes into it. *) -proc copyResult*(off, size: I64); -begin - clobberArgs(); - popTo(RSI); - X.load(RDI, X.mem(RBP, retSlot), 8, false); - if off # 0 then X.lea(RDI, X.mem(RDI, off)); end; - copyBytes(size); -end; - -(* return: the result, a value on top, goes in rax or xmm0; two words, - the two values on top, in rax and rdx; one behind the hidden pointer - goes back with that pointer in rax. *) -proc returnJump*; -begin - if resType # nil then - if Sym.behindPointer(resType) then - X.load(RAX, X.mem(RBP, retSlot), 8, false); - elsif Sym.inTwoRegs(resType) then - popTo(RDX); - popTo(RAX); - elsif resType^.form = Sym.fReal then - xValueTo(depth - 1, 0); - drop(); - else - popTo(RAX); - end; - end; - X.jmp(exitL); -end; - -(* The first of what try does where the error isn't nil (the report, 7.8): - the machine's stack made even, as the deferred statements about to be - run expect to find it. try can stand among the arguments of another - call, where quadwords have been pushed. Nothing is lost: the frame is - above rsp, and the code returns through the frame pointer. *) -proc tryAlign*; -begin - X.aluI(X.aluAnd, RSP, -16); -end; - -(* The procedure returns the error in register r, and a zero for each of - its other results; it isn't rax, rcx, rdx or rdi, which this uses. *) -proc returnError(r: INT); -var f: ^Sym.Obj; -begin - if Sym.behindPointer(resType) then - X.load(RDI, X.mem(RBP, retSlot), 8, false); - zeroBytes(resType^.size); - f := resType^.fields; - while f^.next # nil do f := f^.next; end; - X.load(RDX, X.mem(RBP, retSlot), 8, false); - X.store(X.mem(RDX, f^.val), r, 8); - X.load(RAX, X.mem(RBP, retSlot), 8, false); - elsif Sym.inTwoRegs(resType) then - X.movRR(RDX, r); - X.movRI(RAX, 0); - else - X.movRR(RAX, r); - end; - X.jmp(exitL); -end; - -(* The rest of it: the procedure returns the error in the frame slot, and - a zero for each of its other results. Only code is made: no entry of - the stack of values is touched, since the code that follows is the - code for an error that is nil, with the stack as it was. *) -proc tryReturn*(slot: I64); -begin - X.load(RSI, X.mem(RBP, slot), 8, false); - returnError(RSI); -end; - -(* try, with no deferred statement to run: the error on top is tested in - its register r, which is returned, and, if it isn't nil, returned from - the procedure by tryReturnFrom, so it needs no slot in the frame. *) -proc tryTest*(var ok: INT): INT; -var r: INT; -begin - r := loaded(depth - 1); - jumpIf(ok, false); - return r; -end; - -proc tryReturnFrom*(r: INT); -begin - returnError(r); -end; - -(* The end of the procedure in chunk c: the code that returns, and the - frame's size, known only now, patched into its prologue. If it is - open, running off its end, it returns zeros. *) -proc endProc*(c: INT; open: BOOL): ERROR; -var n: I64; i: INT; -begin - codeChunk := -1; - if (depth # 0) or (pushed # 0) then Diag.fatal("internal error: stack depth"); end; - if open then - if Sym.behindPointer(resType) then - X.load(RDI, X.mem(RBP, retSlot), 8, false); - X.movRI(RCX, resType^.size); - X.movRI(RAX, 0); - X.repStos(1); - X.load(RAX, X.mem(RBP, retSlot), 8, false); - else - X.movRI(RAX, 0); - if Sym.inTwoRegs(resType) then X.movRI(RDX, 0); end; - X.movqXR(0, RAX); - end; - else - X.dropJumpTo(exitL); - end; - X.fixLink(exitL); - n := 0; - for i := 0 to 4 do - if (regMask & (1 shl i)) # 0 then - X.load(VarRegs[i], X.mem(RBP, saveAt + 8 * n), 8, false); - INC(n); - end; - end; - X.leave(); - X.ret(); - endFails(); - n := Sym.alignUp(frameMax, 16); - if n < 16 then n := 16; end; - if n > 2147483647 then return Scan.mark("frame too big"); end; - Chunk.put4At(frameFix, INT(n)); - (* the listing's text for the sub, which starts 3 bytes (REX.W, opcode, - ModRM) before its immediate *) - if X.listing then X.restate(frameFix - 3, Diag.say("sub rsp, {}", [Fmt.int(INT(n))])); end; - Chunk.endChunk(c); - return nil; -end; - -(* A deferred statement is compiled where it stands, as a subroutine of - 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 what pushed was, and starts it, with the return address - pushed. The stack is empty where it is called, and where it begins. *) -proc deferBegin*(var L: INT): (INT, INT); -var saved: INT; -begin - X.jmp(L); - saved := pushed; - pushed := 1; - return Chunk.pc, saved; -end; - -proc deferEnd*(L, saved: INT); -begin - keepTemps(); - X.ret(); - X.fixLink(L); - pushed := saved; -end; - -proc runDefer*(at: INT); -begin - X.callBack(at); -end; - -(* The entry point, _start, and its chunk: it saves argc and argv, and - the address of the places for Rt; runs every used module's body, then - 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 the library what it needs of C: Rt C's exit, in cExit, and - Thread pthread_create and pthread_join. - - dynamic: the program uses C. first: the first module, whose chain - gives the order of the bodies. mainObj: the program's main procedure, or - nil. The first numCLinks of cLinks: C's symbols, each loaded from the - quadword the loader fills in and stored in a variable of the - library's, in a program that uses C. exitProc: the chunk of Rt's exit. The - first numLinks of links: the addresses Rt is given, of what the program - has: the places, and the profiler and calls; what it isn't given, - nothing reaches, and the linker leaves out. - - bare: raz -bare, a program for the bare machine, a kernel's, with - no Linux under it. Its entry point reads no argc and argv, which - only Linux leaves on the stack, so that ARGC() is 0; and runs no body - of Rt, whose system calls, to set the signals' handlers, would fault - there. A kernel's own module sets up what Rt's body would. *) -proc entryPoint*(dynamic, bare: BOOL; first: ^Sym.Module; mainObj: ^Sym.Obj; cLinks: []Link; numCLinks, exitProc: INT; links: []Link; numLinks: INT): INT; -var entry, start, i: INT; m: ^Sym.Module; -begin - entry := Chunk.newChunk(Chunk.secText, -1, internStr("_start")); - if dynamic then - start := Chunk.newChunk(Chunk.secText, -1, internStr("main")); - Chunk.beginChunk(entry); - (* at the start rdx holds rtld_fini, from the dynamic loader, and the - stack argc, then argv *) - X.movRI(X.RBP, 0); (* no frame above, where a trace stops *) - X.movRR(R9, RDX); (* rtld_fini, the sixth argument *) - X.pop(RSI); (* argc, the second *) - X.movRR(RDX, RSP); (* argv, the third *) - X.aluI(X.aluAnd, RSP, -16); - X.push(RAX); (* padding, so that the next push, the seventh *) - X.push(RSP); (* argument, stack_end, leaves rsp aligned *) - X.movRI(R8, 0); (* fini and init: none *) - X.movRI(RCX, 0); - X.lea(RDI, X.memRip(start, 0)); (* main, the first argument *) - X.callM(X.memRip(Chunk.externChunk(internStr("__libc_start_main")), 0)); - X.ud2(); (* it never returns *) - Chunk.endChunk(entry); - Chunk.beginChunk(start); - X.push(RBP); (* aligns the stack again *) - X.store(X.memRip(argcChunk, 0), RDI, 8); - X.store(X.memRip(argvChunk, 0), RSI, 8); - for i := 0 to numCLinks - 1 do - X.load(RAX, X.memRip(cLinks[i].chunk, 0), 8, false); - X.store(X.memRip(cLinks[i].into, 0), RAX, 8); - end; - elsif bare then - start := entry; - Chunk.beginChunk(entry); - else - start := entry; - Chunk.beginChunk(entry); - X.load(RAX, X.mem(RSP, 0), 8, false); - X.store(X.memRip(argcChunk, 0), RAX, 8); - X.lea(RAX, X.mem(RSP, 8)); - X.store(X.memRip(argvChunk, 0), RAX, 8); - end; - for i := 0 to numLinks - 1 do - X.lea(RAX, X.memRip(links[i].chunk, 0)); - X.store(X.memRip(links[i].into, 0), RAX, 8); - end; - m := first; - while m # nil do - if m^.used and (m^.body >= 0) and not (bare and (m^.name = internStr("Rt"))) then X.callChunk(m^.body); end; - m := m^.next; - end; - if mainObj # nil then X.callChunk(mainObj^.chunk); end; - if (mainObj # nil) and (mainObj^.typ^.base # nil) then X.movRR(RDI, RAX); else X.movRI(RDI, 0); end; - X.callChunk(exitProc); - X.ud2(); (* exit never returns: trap if it does *) - Chunk.endChunk(start); - (* Rt.fail, for the failures of each kind: the place is where the - 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. rdi and rsi - as the failing code had them go on the stack, as Rt.fail's last two - arguments, and a comes in rax (endFails). *) - for i := 0 to LEN(failStubs) - 1 do - if failStubs[i] >= 0 then - Chunk.beginChunk(failStubs[i]); - X.load(R8, X.mem(RSP, 0), 8, false); - X.aluI(X.aluSub, R8, 1); - X.aluI(X.aluAnd, RSP, -16); - X.push(RSI); - X.push(RDI); - X.movRR(RSI, RAX); - X.movRI(RDI, i); - X.callChunk(rtFail); - X.ud2(); - Chunk.endChunk(failStubs[i]); - end; - end; - return entry; -end; - -(* A code procedure: its instructions, read by the assembler (X64), - are the whole of chunk c *) -proc codeProc*(c: INT; constExpr: X.ConstFn; nameFn: X.NameFn): ERROR; -begin - Chunk.beginChunk(c); - try X.assemble(constExpr, nameFn); - Chunk.endChunk(c); - return nil; -end; - -(* Whether the code procedure in chunk c is a square root of xmm0 in - itself, then ret, as Math.sqrt is: - - sqrtsd xmm0, xmm0 F2 0F 51 C0 - ret C3 - - If so, its prefix and opcode, F251H (F351H for sqrtss), which a call of it does in place - on the value's own register (realInPlace); else 0. A call would spill - the stack's reals and reload the variables' xmm registers around it, - as System V keeps none through one, for an instruction of four bytes. *) -proc oneRealOp*(c: INT): INT; -var s: INT; -begin - s := Chunk.chunks[c].start; - if (Chunk.chunks[c].size # 5) or (Chunk.chunks[c].numFix # 0) then return 0; end; - if ((Chunk.text[s] # 0F2H) and (Chunk.text[s] # 0F3H)) or (Chunk.text[s + 1] # 0FH) - or (Chunk.text[s + 2] # 51H) or (Chunk.text[s + 3] # 0C0H) or (Chunk.text[s + 4] # 0C3H) then - return 0; - end; - return INT(Chunk.text[s]) * 256 + INT(Chunk.text[s + 2]); -end; - -(* The operation op, of oneRealOp, on the real on top, in its register: - Math.sqrt(d2) is sqrtsd xmm8, xmm8, with no call. *) -proc realInPlace*(op: INT); -var x: INT; -begin - x := top(); - X.sse(op & 0FFH, x, x, op shr 8 = 0F3H); -end; - -var i: INT; -begin - for i := 0 to LEN(failStubs) - 1 do failStubs[i] := -1; end; - inPlace := -1; - codeChunk := -1; - resetStack(0, 0); - rtFail := Chunk.newChunk(Chunk.secText, internStr("Rt"), internStr("fail")); - argcChunk := Chunk.newChunk(Chunk.secBss, -1, internStr("argc")); - Chunk.setBss(argcChunk, 8, 8); - argvChunk := Chunk.newChunk(Chunk.secBss, -1, internStr("argv")); - Chunk.setBss(argvChunk, 8, 8); -end Gen. diff --git a/src/Gen.x86_64.raz b/src/Gen.x86_64.raz new file mode 100644 index 0000000..8f1525e --- /dev/null +++ b/src/Gen.x86_64.raz @@ -0,0 +1,2860 @@ +(* Gen: the code generator, for x86-64 (Gen.x86_64.raz; another machine has + a Gen of its own, chosen by the suffix of its file, doc/raz.md, 3). + + Item and Parse drive a stack machine: they push constants, addresses + and the values of variables, operate on the values on top, store + them and jump on them. Every value has a kind: a word, which is an + integer as big as an address, a pointer, a BOOL, a set or a narrower + integer; a long, a 64-bit integer on a machine whose word is smaller + (never here); an F32; an F64. This unit makes the machine's code for + those calls, and nothing above it knows the machine: a port is a new + Gen, with an encoder of its own. + + 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, or in xmm8 to + xmm11 if it is a real. 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. + + 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, and the results of its calls + that hold an array (report 8). The variables are zeroed on + entry. + + Depends on: Scan and Diag for errors, Sym for types, Chunk for code + and data, X64 for instructions. + Leaves out: what the program means, its types and their checks; that + is Item. + + The seed's `Mark` in the middle of a push or a check can't give an + error back, so it is shown and the call goes on without doing what + it could not (see newEntry and check): the compile ends with the + message, and the parser's recovery makes the stack right again with + resetStack. A full stack (newEntry) ends the compile at once: the pops + after it would go below the stack. endProc returns its error, for the + parser to pass up. + + What the parser sets, `inPlace`, has a setter, as the exported + variables can't be set from outside. The seed's types lose their T + (`TAdr` is `Adr`), and its `Call` record, which the procedure `call` + takes, is `CallInfo`. *) +module Gen; +import Fmt, Diag, Scan, Sym, Chunk, X := X64; +import SYSTEM; + +const + Arch* = "x86_64"; (* the target's machine, as a file's suffix says it *) + NoLabel* = -1; + WordSize* = 8; (* the size of an address, and of INT *) + (* What the machine catches by itself, which the code needn't test for + (report section 10): on x86-64 Linux, a division by zero, a stack + overflow (at the guard page under the stack), a call to nil, and + a load or store within NilPage bytes of address 0, which is never + mapped. *) + NilPage* = 4096; + + RAX = X.RAX; RCX = X.RCX; RDX = X.RDX; RSP = X.RSP; RBP = X.RBP; + RSI = X.RSI; RDI = X.RDI; R8 = X.R8; R9 = X.R9; R10 = X.R10; R11 = X.R11; + +type + Kind* = (kWord, kLong, kF32, kF64); + + (* Where a variable is: its address is relative to the frame, to a + chunk, to an address on the stack, or to one held in a frame slot *) + Base* = (bFrame, bGlobal, bStack, bSlot, bReg, bPtr); + Adr* = record + base*: Base; + chunk*: INT; (* bGlobal: the chunk; bSlot: the frame slot; bReg: the register; + bPtr: the register that holds the address *) + off*: I64; (* added to the address; for bReg, which word, 0 or 8 *) + hi*: INT; (* bReg, a slice: the register of its length, the + second word; chunk is that of its pointer *) + end; + + (* The code made so far, to go back to for a second try at a body *) + CodeMark* = record pc*, fixups*, lines*, said*, fails*, exit*: INT; end; + + (* For entryPoint: the address of chunk, put in the variable whose + chunk is into before the program starts; or, for C's symbols, the + address in chunk, the quadword the loader fills in *) + Link* = record chunk*, into*: INT; end; + + CallInfo* = record + sig*: ^Sym.Type; + param*: ^Sym.Obj; (* the parameter the next argument is for *) + obj*: ^Sym.Obj; (* the procedure called, if it has a name *) + n*: INT; (* the arguments *) + isF*: [64]BOOL; (* ... goes in an xmm register *) + pair*: [64]BOOL; (* ... is a slice's first word, the next its second *) + target*: I64; (* the frame slot of a procedure value, if chunk < 0 *) + chunk*: INT; (* else the procedure's chunk *) + ext*: BOOL; (* C's: called through the chunk holding its address *) + ret*: I64; (* set by call: the temporary a slice or a record result is in *) + end; + +const + (* the registers a procedure keeps its busiest variables in: System V's + 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*: [5]INT = [X.RBX, X.R12, X.R13, X.R14, X.R15]; + (* the registers the trap report can show a variable in: VarRegs, then + rdi and rsi, where a procedure that calls nothing keeps the + parameters that arrive in them (keptIn) *) + ShownRegs*: [7]INT = [X.RBX, X.R12, X.R13, X.R14, X.R15, X.RDI, X.RSI]; + (* the registers a procedure keeps its busiest reals in, xmm12 to + xmm15, numbered from XmmVar up so that they aren't taken for r12 to + r15 (regAt); and in a procedure that calls nothing, which has no + real parameter in them, xmm4 to xmm7 too, as nothing else uses + them there. Each has a slot too, written as it is, where the trap + report finds it, and from which it is loaded again after a call, as + System V has no callee-saved xmm register (xHome). *) + XmmVar* = 16; + XVarRegs*: [8]INT = [XmmVar + 12, XmmVar + 13, XmmVar + 14, XmmVar + 15, + XmmVar + 4, XmmVar + 5, XmmVar + 6, XmmVar + 7]; + (* a procedure's registers of variables, as bits: bit i is VarRegs[i], + bit XBit + i XVarRegs[i] *) + XBit* = 5; + +var + rtFail*, argcChunk*, argvChunk*: INT; + (* the stubs that check's code calls, one for each kind of failure, + made by entryPoint for those used *) + failStubs: [8]INT; + lost*: BOOL; (* a parameter kept where it arrived was wanted + for other work: the procedure is compiled again, + the parameter in memory *) + inPlace: INT; (* the register of a variable that the statement + being compiled assigns, x := x + e, where the + value can be worked out in the variable's own + register, from its first push on (lInto) *) + depth*: INT; (* the values on the stack *) + pushed*: INT; (* quadwords pushed on the machine's stack *) + codeChunk*: INT; (* the procedure or body being compiled, or -1 *) + +type + (* where a value on the stack is *) + Loc = (lConst, (* not loaded: val is the value *) + 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 *) + lIdx, (* not loaded: the address m, an element of an array + or of a slice in registers: the array's or the + pointer's register, or rbp, as the base, and the + index in a register variable's or the value's + own register (indexSlice, indexArray) *) + lMem, (* not loaded: the value of size bytes at m, in the + frame, a chunk, or at an address lAdr or lIdx + noted, read where it is used (pushVar) *) + lInto, (* in register val, a register variable's own, which + is what the value goes to (inPlace): so it is + changed in place *) + lReg, (* in its register *) + lFrame); (* spilled: in the frame slot val *) + + Entry = record + loc: Loc; + val: I64; (* lConst: the value; lHeld: the register; lAdr: the + offset; lFrame: the frame slot *) + chunk: INT; (* lAdr: the chunk, or -1 for the frame *) + m: X.Mem; (* lIdx, lMem *) + size: INT; (* lMem *) + signed: BOOL; (* lMem *) + k: Kind; + off: I64; (* lHeld, lReg: a word, its register plus off, the + constant of x + 1 not yet added (op), so that an + operand that uses it can take it as its + displacement: [r13 + r9 * 8 - 8] *) + end; + + (* a check of the procedure, whose failure endFails makes *) + Fail = record + L, what, ra, name: INT; + path, line, col: INT; (* the place, told now: an inlined procedure's + is in its own file (Parse's inlined) *) + m: X.Mem; + n: I64; + end; + +const + MaxStack = 1024; (* values waiting in one expression: 63 nested calls of up to 15 arguments each *) + StubNames: [8][]const U8 = ["check0", "check1", "check2", "check3", "check4", "check5", "check6", "check7"]; + (* the registers of the stack: the value at depth d is in Regs[d mod + NumRegs]. rax, rdx and rcx, which division and shifts need, and rsi + and rdi, which copying needs, aren't among them. *) + NumRegs = 4; + Regs: [NumRegs]INT = [R8, R9, R10, R11]; + XRegs: [NumRegs]INT = [8, 9, 10, 11]; (* xmm8 to xmm11 *) + IntRegs: [6]INT = [RDI, RSI, RDX, RCX, R8, R9]; + +var + stack: [MaxStack]Entry; + owner: [NumRegs]INT; (* the value in each register, or -1 *) + frameTop, frameMax, permTop: I64; + frameFix: INT; (* where the frame size is patched in *) + paramTop: I64; (* the parameters' slots end here *) + zeroTop: I64; (* the locals the prologue zeroes end here *) + retSlot: I64; (* holds the hidden result pointer *) + resType: ^Sym.Type; (* the procedure's result, or nil *) + exitL: INT; + (* parameters arriving in registers: where each is stored on entry *) + inReg: [14]INT; + inSlot: [14]I64; + inSize: [14]INT; + inObj: [14]^Sym.Obj; + numIn: INT; + procParams: ^Sym.Obj; (* the parameters, for enterBody *) + regMask: INT; (* the registers of variables, as bits (XBit) *) + kept: INT; (* bit r: register r holds a parameter, as it arrived *) + saveAt: I64; (* where they are saved, a quadword each *) + homes: [8]I64; (* the slots of the variables in XVarRegs *) + frameAt: [3]I64; (* frameTop, frameMax, permTop after the declarations *) + fails: [4096]Fail; + numFails: INT; + +(* -S: the text of each instruction is kept, and list prints it. Raz asks + Gen, not the encoder, so that no unit but Gen names the machine. *) +proc setListing*(yes: BOOL); +begin + X.setListing(yes); +end; + +proc list*(home: INT); +begin + X.list(home); +end; + +proc setInPlace*(r: INT); +begin + inPlace := r; +end; + +proc kindOf*(t: ^Sym.Type): Kind; +begin + if t^.form = Sym.fReal then + if t^.size = 4 then return kF32; end; + return kF64; + end; + if t^.size > WordSize then return kLong; end; + return kWord; +end; + +(* The stack, as in Wirth's compilers: the value at depth d is held in + 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; xmm0 and xmm1 for reals. + + A real, an F32 or an F64, is held in xmm8 to xmm11 (XRegs), where the + machine computes with reals, the value at depth d in XRegs[d mod + NumRegs]: so each depth has two registers, and holds its value in the + one of its kind, which owner doesn't tell apart. The xmm registers + from xmm8 up carry no arguments, so that call can move a real into + xmm0 to xmm7 without overwriting another still to go. *) + +proc fits32(v: I64): BOOL; +begin + return (v >= -2147483648) and (v <= 2147483647); +end; + +(* The register of kind k for the value at depth i *) +proc regIn(k: Kind; i: INT): INT; +begin + if k in {kF32, kF64} then return XRegs[i mod NumRegs]; end; + return Regs[i mod NumRegs]; +end; + +proc regOf(i: INT): INT; +begin + return regIn(stack[i].k, i); +end; + +proc isReal(i: INT): BOOL; +begin + return stack[i].k in {kF32, kF64}; +end; + +(* A real constant, its bits v, as an operand: 8 bytes in read-only + data, as the machine has no instruction that holds one *) +proc realConst(v: I64): X.Mem; +var c: INT; +begin + c := Chunk.newChunk(Chunk.secRodata, -1, -1); + Chunk.setData(c, ^U8(SYSTEM.ADR(v)), 8, 8); + return X.memRip(c, 0); +end; + +(* The real i into xmm register x, from wherever it is, as valueTo does + for an integer register *) +proc xValueTo(i, x: INT); +begin + match stack[i].loc of + | lConst: X.movsXM(x, realConst(stack[i].val), stack[i].k = kF32); + | lMem: X.movsXM(x, stack[i].m, stack[i].size = 4); + | lHeld: if INT(stack[i].val) # x then X.movX(x, INT(stack[i].val)); end; + | lInto: if INT(stack[i].val) # x then X.movX(x, INT(stack[i].val)); end; + | lReg: if regOf(i) # x then X.movX(x, regOf(i)); end; + | else: X.movsXM(x, X.mem(RBP, stack[i].val), false); (* spilled, as 8 bytes *) + end; +end; + +proc loaded(i: INT): INT; forward; +proc allocPerm*(size, align: I64): I64; forward; +proc allocTemp*(size, align: I64): I64; forward; + +(* The value i, in a register, goes to a frame slot; one noted that + holds its register, as an index, is worked out in it first *) +proc spill(i: INT); +var s: I64; +begin + if (stack[i].loc # lReg) or (stack[i].off # 0) then _ := loaded(i); end; + s := allocTemp(8, 8); + if isReal(i) then X.movsMX(X.mem(RBP, s), regOf(i), false); + else X.store(X.mem(RBP, s), regOf(i), 8); end; + stack[i].loc := lFrame; + stack[i].val := s; + owner[i mod NumRegs] := -1; +end; + +(* Each value below depth d read from memory now, as what comes next + may change it *) +proc readMems(d: INT); +var i: INT; +begin + for i := 0 to d - 1 do + if stack[i].loc = lMem then _ := loaded(i); end; + end; +end; + +(* Every value below depth d in a register, spilled; one noted in memory + is read first, as a call may change it *) +proc spillBelow(d: INT); +var r: INT; +begin + readMems(d); + for r := 0 to NumRegs - 1 do + if (owner[r] >= 0) and (owner[r] < d) then spill(owner[r]); end; + end; +end; + +(* The register of kind k of value i, for it to hold: a lower value at + its depth's registers is spilled. *) +proc claim(i: INT; k: Kind): INT; +var r: INT; +begin + r := i mod NumRegs; + if (owner[r] >= 0) and (owner[r] # i) then spill(owner[r]); end; + owner[r] := i; + return regIn(k, i); +end; + +(* The memory at the noted address i, plus off *) +proc adrMem(i: INT; off: I64): X.Mem; +begin + if stack[i].chunk < 0 then return X.mem(RBP, stack[i].val + off); end; + return X.memRip(stack[i].chunk, INT(stack[i].val + off)); +end; + +(* The value i, in its register *) +proc loaded(i: INT): INT; +var r: INT; +begin + if stack[i].loc = lInto then return INT(stack[i].val); end; + if (stack[i].loc # lReg) and isReal(i) then + xValueTo(i, claim(i, stack[i].k)); + stack[i].loc := lReg; + elsif stack[i].loc # lReg then + r := claim(i, kWord); + match stack[i].loc of + | lConst: X.movRI(r, stack[i].val); + | lHeld: X.movRR(r, INT(stack[i].val)); + | lAdr: X.lea(r, adrMem(i, 0)); + | lIdx: X.lea(r, stack[i].m); + | lMem: X.load(r, stack[i].m, stack[i].size, stack[i].signed); + | else: X.load(r, X.mem(RBP, stack[i].val), 8, false); + end; + stack[i].loc := lReg; + end; + if stack[i].off # 0 then + X.lea(regOf(i), X.mem(regOf(i), stack[i].off)); + stack[i].off := 0; + end; + return regOf(i); +end; + +(* The register value i is in, only to be read: a variable's own, or + its register *) +proc peek(i: INT): INT; +begin + if (stack[i].loc = lHeld) and (stack[i].off = 0) then return INT(stack[i].val); end; + return loaded(i); +end; + +(* The offset of value i, taken from it, for the caller to add or to + make a displacement of *) +proc takeOff(i: INT): I64; +var o: I64; +begin + o := stack[i].off; + stack[i].off := 0; + return o; +end; + +(* The word on top, in a register, has o added: noted, if o can be a + displacement, else added now *) +proc putOff(o: I64); +begin + if fits32(stack[depth - 1].off + o) then + stack[depth - 1].off := stack[depth - 1].off + o; + else + X.movRI(RCX, o); + X.alu(X.aluAdd, loaded(depth - 1), RCX); + end; +end; + +proc top: INT; +begin + if depth = 0 then Diag.fatal("internal error: the stack is empty"); end; + return loaded(depth - 1); +end; + +(* A value on the stack's top. At the stack's last place the error is shown + and the compile ends there: with nothing pushed, the pops after it would + go below the stack. See the head of this unit. *) +proc newEntry(k: Kind; loc: Loc; v: I64); +begin + if depth > LEN(stack) - 1 then + _ := Scan.mark(Diag.say("more than {} values waiting in one expression", [Fmt.int(MaxStack)])); + Diag.finish(); (* ends the compile: an error was counted *) + return; + end; + stack[depth].k := k; + stack[depth].loc := loc; + stack[depth].val := v; + stack[depth].chunk := -1; + stack[depth].off := 0; + INC(depth); +end; + +(* An address, lIdx, or a value at it, lMem, noted as the operand m. Its + index may be in the register of the value just dropped, at this + depth: it is the new value's own, then. *) +proc newMem(loc: Loc; m: X.Mem; k: Kind; size: INT; signed: BOOL); +begin + newEntry(k, loc, 0); + stack[depth - 1].m := m; + stack[depth - 1].size := size; + stack[depth - 1].signed := signed; + if m.index = Regs[(depth - 1) mod NumRegs] then owner[(depth - 1) mod NumRegs] := depth - 1; end; +end; + +(* The register a new value on top is to be computed in *) +proc target: INT; +begin + return claim(depth, kWord); +end; + +(* The xmm register a new real on top is to be computed in *) +proc xTarget: INT; +begin + return claim(depth, kF64); +end; + +(* The value just computed in target goes on top *) +proc computed(k: Kind); +begin + newEntry(k, lReg, 0); +end; + +proc drop*; +begin + DEC(depth); + if owner[depth mod NumRegs] = depth then owner[depth mod NumRegs] := -1; end; +end; + +(* rsi and rdi are about to be used for other work, as in copying: a + parameter kept in either must go to memory (lost). *) +proc clobberArgs; +begin + if kept # 0 then lost := true; end; +end; + +(* The value i into register r, from wherever it is: a constant or an + address is made there, a variable's register or the value's own + register copied, a spilled value loaded. Unlike loaded, it leaves the + value where it was, so r is its only new copy. *) +proc valueTo(i, r: INT); +begin + if isReal(i) and (stack[i].loc in {lHeld, lInto}) then + X.movqRX(r, INT(stack[i].val)); + else + match stack[i].loc of + | lConst: X.movRI(r, stack[i].val); + | lHeld: X.movRR(r, INT(stack[i].val)); + | lInto: X.movRR(r, INT(stack[i].val)); + | lAdr: X.lea(r, adrMem(i, 0)); + | lIdx: X.lea(r, stack[i].m); + | lMem: X.load(r, stack[i].m, stack[i].size, stack[i].signed); + | lReg: + if isReal(i) then X.movqRX(r, regOf(i)); + elsif regOf(i) # r then X.movRR(r, regOf(i)); end; + | else: X.load(r, X.mem(RBP, stack[i].val), 8, false); + end; + end; + if stack[i].off # 0 then X.lea(r, X.mem(r, stack[i].off)); end; +end; + +(* The value on top, popped into register r *) +proc popTo(r: INT); +begin + valueTo(depth - 1, r); + drop(); +end; + +(* Whether the value on top is a constant, and if so, which *) +proc topConst: (BOOL, I64); +begin + return stack[depth - 1].loc = lConst, stack[depth - 1].val; +end; + +proc resetStack*(d, p: INT); +var r: INT; +begin + depth := d; + pushed := p; + for r := 0 to NumRegs - 1 do owner[r] := -1; end; +end; + +proc pushConst*(k: Kind; v: I64); +begin + newEntry(k, lConst, v); +end; + +(* The register of the word at a, a variable in registers: the variable's + own, or for a slice its pointer's (off 0) or its length's (off 8) *) +proc regAt(a: Adr): INT; +var r: INT; +begin + if a.off = 0 then r := a.chunk; else r := a.hi; end; + if r >= XmmVar then r := r - XmmVar; end; (* an xmm register, XVarRegs *) + return r; +end; + +(* The memory a names. An address on the stack is popped, and is in its + register still; one in a slot is loaded into r. *) +proc place(a: Adr; r: INT): X.Mem; +var m: X.Mem; ra: INT; o: I64; +begin + if a.base = bReg then Diag.fatal("internal error: a register has no address"); end; + match a.base of + | bFrame: return X.mem(RBP, a.off); + | bGlobal: return X.memRip(a.chunk, INT(a.off)); + | bStack: + if stack[depth - 1].loc = lAdr then + m := adrMem(depth - 1, a.off); + drop(); + return m; + elsif stack[depth - 1].loc = lIdx then + m := stack[depth - 1].m; + m.disp := m.disp + INT(a.off); + drop(); + return m; + end; + (* an offset noted on the address is the operand's, as + p^.f + 8: [r8 + 8] *) + if fits32(a.off + stack[depth - 1].off) then o := takeOff(depth - 1); else o := 0; end; + ra := peek(depth - 1); + drop(); + return X.mem(ra, a.off + o); + | bPtr: return X.mem(a.chunk, a.off); + | else: (* bSlot: the address is in the frame slot a.chunk *) + X.load(r, X.mem(RBP, a.chunk), 8, false); + return X.mem(r, a.off); + end; +end; + +(* The address a names, on top of the stack *) +proc pushAdr*(a: Adr); +var m: X.Mem; r: INT; +begin + if (a.base = bStack) and (a.off = 0) then return; end; (* it is on top already *) + if a.base in {bFrame, bGlobal} then + newEntry(kWord, lAdr, a.off); + if a.base = bGlobal then stack[depth - 1].chunk := a.chunk; end; + return; + 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 + m := place(a, -1); r := target(); + else + r := target(); m := place(a, r); + end; + (* an address that is already in r, [r], needs no instruction *) + if (m.base # r) or (m.index # X.NoIndex) or (m.disp # 0) then X.lea(r, m); end; + computed(kWord); +end; + +proc pushVar*(a: Adr; size: INT; signed: BOOL; k: Kind); +var m: X.Mem; r: INT; +begin + r := inPlace; + inPlace := -1; + if r >= XmmVar then r := r - XmmVar; end; + if (a.base = bReg) and (regAt(a) = r) then + newEntry(k, lInto, r); + return; + end; + if a.base = bReg then + newEntry(k, lHeld, regAt(a)); + return; + end; + (* a variable in the frame or a chunk, or at an address only noted, is + only noted too: read where it is used, as an operand if it can be *) + if (a.base in {bFrame, bGlobal, bPtr}) or (a.base = bStack) and (stack[depth - 1].loc in {lAdr, lIdx}) then + m := place(a, -1); + newMem(lMem, m, k, size, signed); + return; + end; + (* in the order pushAdr explains *) + if a.base = bStack then + m := place(a, -1); r := target(); + else + r := target(); m := place(a, r); + end; + if k in {kF32, kF64} then X.movsXM(xTarget(), m, size = 4); + else X.load(r, m, size, signed); end; + computed(k); +end; + +proc pushProc*(c: INT; ext: BOOL); +var r: INT; +begin + r := target(); + if ext then X.load(r, X.memRip(c, 0), 8, false); + else X.lea(r, X.memRip(c, 0)); end; + computed(kWord); +end; + +(* Where xmm register r is in XVarRegs *) +proc xIndex(r: INT): INT; +begin + if r >= XVarRegs[0] then return r - XVarRegs[0]; end; + return r - XVarRegs[4] + 4; +end; + +(* The slot of the variable in xmm register x *) +proc homeOf(x: INT): X.Mem; +begin + return X.mem(RBP, homes[xIndex(x + XmmVar)]); +end; + +(* Pops a value into the variable at a; an address on the stack is under + the value. *) +proc popVar*(a: Adr; size: INT); +var r: INT; v: I64; c, fl: BOOL; +begin + if (a.base = bReg) and isReal(depth - 1) then + xValueTo(depth - 1, regAt(a)); + drop(); + X.movsMX(homeOf(regAt(a)), regAt(a), false); (* written through, as xHome says *) + return; + end; + if a.base = bReg then + c, v := topConst(); + if c then X.movRI(regAt(a), v); + elsif peek(depth - 1) # regAt(a) then X.movRR(regAt(a), peek(depth - 1)); end; (* else it is there, lInto *) + drop(); + return; + end; + c, v := topConst(); + if c and fits32(v) then + drop(); + X.storeI(place(a, RCX), INT(v), size); + return; + end; + if c then r := RAX; X.movRI(RAX, v); + else r := peek(depth - 1); end; + fl := (stack[depth - 1].loc # lConst) and isReal(depth - 1); + drop(); + if fl then X.movsMX(place(a, RCX), r, size = 4); + else X.store(place(a, RCX), r, size); end; +end; + +(* Register src to dst, an xmm register's if fl *) +proc movReg(fl: BOOL; dst, src: INT); +begin + if fl then X.movX(dst, src); else X.movRR(dst, src); end; +end; + +(* The two values on top, of one kind, change places. *) +proc swap*; +var e: Entry; x, y, t: INT; rx, ry, fl: BOOL; +begin + x := depth - 2; y := depth - 1; + (* a value noted at an address that uses its register is worked out, + so that its register moves with it *) + if stack[x].loc in {lIdx, lMem} then _ := loaded(x); end; + if stack[y].loc in {lIdx, lMem} then _ := loaded(y); end; + rx := stack[x].loc = lReg; + ry := stack[y].loc = lReg; + fl := isReal(y); + if fl then t := 0; else t := RAX; end; (* xmm0, or rax *) + if rx and ry then + movReg(fl, t, regOf(x)); + movReg(fl, regOf(x), regOf(y)); + movReg(fl, regOf(y), t); + elsif rx then + owner[x mod NumRegs] := -1; + movReg(fl, claim(y, stack[y].k), regOf(x)); + elsif ry then + owner[y mod NumRegs] := -1; + movReg(fl, claim(x, stack[x].k), regOf(y)); + end; + e := stack[x]; stack[x] := stack[y]; stack[y] := e; +end; + +(* Copying *) + +(* The most that copyBytes and zeroBytes do with moves, in place of rep + movsb and rep stosb, which take some twenty cycles to start, longer + than the few moves take. *) +const MaxMoves = 256; + +(* Up to this size a copy goes as words: a record just made field by + field is read back by loads as wide as its stores, and a 16-byte + load across two 8-byte stores waits for them to reach the cache. *) +const MaxWordMoves = 64; + +(* size bytes from [rsi] to [rdi], through xmm0 and rcx; rsi and rdi are + left as they fall. Up to MaxMoves bytes, as a record or a small array + mostly is, they go as moves: of 16 bytes from MaxWordMoves up, then + of 8, 4, 2 and 1. *) +proc copyBytes(size: I64); +var o, n: I64; +begin + if size > MaxMoves then + X.movRI(RCX, size); + X.repMovsb(); + return; + end; + o := 0; + while (size > MaxWordMoves) and (o + 16 <= size) do + X.movdquXM(0, X.mem(RSI, o)); + X.movdquMX(X.mem(RDI, o), 0); + INC(o, 16); + end; + while o < size do + n := 8; + while n > size - o do n := n div 2; end; + X.load(RCX, X.mem(RSI, o), INT(n), false); + X.store(X.mem(RDI, o), RCX, INT(n)); + INC(o, n); + end; +end; + +(* Pops a source's address, and a destination's under it, and copies + size bytes to off bytes past the destination. *) +proc copyBlock*(size, off: I64); +begin + clobberArgs(); + popTo(RSI); + popTo(RDI); + if off # 0 then X.lea(RDI, X.mem(RDI, off)); end; + copyBytes(size); +end; + +(* Pops a source's address, and copies size bytes to a: for a slice in + registers, its two words into them. *) +proc copyTo*(a: Adr; size: I64); +begin + clobberArgs(); + popTo(RSI); + if a.base = bReg then + X.load(a.chunk, X.mem(RSI, 0), 8, false); + X.load(a.hi, X.mem(RSI, 8), 8, false); + return; + end; + X.lea(RDI, place(a, RDI)); + copyBytes(size); +end; + +(* size zero bytes at [rdi], through xmm0 and rax; rdi is left as it + falls. Up to MaxMoves bytes they go as stores of 16, then of 8, 4, 2 + and 1 bytes, as copyBytes does. *) +proc zeroBytes(size: I64); +var o, n: I64; +begin + if size > MaxMoves then + X.movRI(RAX, 0); + X.movRI(RCX, size); + X.repStos(1); + return; + end; + o := 0; + if size >= 16 then X.pxorXX(0); end; + while o + 16 <= size do + X.movdquMX(X.mem(RDI, o), 0); + INC(o, 16); + end; + if o < size then X.movRI(RAX, 0); end; + while o < size do + n := 8; + while n > size - o do n := n div 2; end; + X.store(X.mem(RDI, o), RAX, INT(n)); + INC(o, n); + end; +end; + +proc zeroVar*(a: Adr; size: I64); +begin + clobberArgs(); + X.lea(RDI, place(a, RDI)); + zeroBytes(size); +end; + +(* Operations *) + +(* n if v is 2^n, which is 0 for 1; -1 if v isn't a power of two *) +proc exactLog2(v: I64): INT; +var n: INT; +begin + n := 0; + while (v > 1) and ((v & 1) = 0) do v := v shr 1; INC(n); end; + if v # 1 then n := -1; end; + return n; +end; + +(* r times v, a size: by a shift where v is a power of two, as it + mostly is, since a shift takes one cycle and imul three *) +proc mulI(r: INT; v: I64); +begin + if exactLog2(v) > 0 then X.shiftI(X.shShl, r, exactLog2(v)); + elsif v # 1 then X.imulI(r, INT(v)); end; +end; + +(* r compared with v, through rdx if v needs more than 32 bits; with + zero by test, which sets the flags as cmp would and is shorter *) +proc cmpI(r: INT; v: I64); +begin + if v = 0 then X.testRR(r, r); + elsif fits32(v) then X.aluI(X.aluCmp, r, INT(v)); + else X.movRI(RDX, v); X.alu(X.aluCmp, r, RDX); end; +end; + +(* r div or mod 2^k, 1 <= k <= 62, with shifts: div truncates towards + zero, so a negative dividend first gets 2^k - 1 added (the bias). *) +proc divPow2(sy: Scan.Sym; r, k: INT; unsign: BOOL); +begin + (* unsigned: div shifts right; mod keeps the low k bits, by shifting + them up to the top and back down *) + if unsign then + if sy = Scan.sDiv then X.shiftI(X.shShr, r, k); + else X.shiftI(X.shShl, r, 64 - k); X.shiftI(X.shShr, r, 64 - k); end; + return; + 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. *) + X.movRR(RCX, r); + X.shiftI(X.shSar, RCX, 63); + X.shiftI(X.shShr, RCX, 64 - k); + X.alu(X.aluAdd, RCX, r); + X.shiftI(X.shSar, RCX, k); + if sy = Scan.sDiv then X.movRR(r, RCX); + else X.shiftI(X.shShl, RCX, k); X.alu(X.aluSub, r, RCX); end; +end; + +(* Before rax div y, of a signed type of bits < 64: its smallest value + divided by -1 overflows it, which must stop the program as it does for + an I64 (report section 6.1). idiv on the 64-bit values wouldn't fault, + so then rax is made the smallest I64, and it does. *) +proc divTrap(bits, y: INT); +var L: INT; +begin + L := NoLabel; + cmpI(y, -1); + X.jcc(X.ccNE, L); + cmpI(RAX, I64(-1) shl (bits - 1)); + X.jcc(X.ccNE, L); + X.shiftI(X.shShl, RAX, 64 - bits); + X.fixLink(L); +end; + +(* Whether the value on top is a word in memory that can be the right + operand of an instruction as it is: add r, [m] *) +proc topInMem: BOOL; +begin + return (stack[depth - 1].loc = lMem) and (stack[depth - 1].size = 8); +end; + +(* The right operand of the two values on top, popped, in register y: + its own, or rcx for a constant; the left one stays, in its register, + which is returned with y. *) +proc operands: (INT, INT); +var v: I64; c: BOOL; y: INT; +begin + c, v := topConst(); + if c then X.movRI(RCX, v); y := RCX; else y := peek(depth - 1); end; + drop(); + return top(), y; +end; + +(* The two reals on top, the left op the right, worked out in the left's + xmm register. The right is taken from memory where it is, as a + constant, a variable or a spilled value is: mulsd xmm8, [rbp - 16]. *) +proc realOp(sy: Scan.Sym; k: Kind); +var f: BOOL; c, x, y: INT; m: X.Mem; +begin + f := k = kF32; + match sy of + | sPlus: c := 58H; (* addsd, or addss for an F32 *) + | sMinus: c := 5CH; (* subsd, subss *) + | sTimes: c := 59H; (* mulsd, mulss *) + | else: c := 5EH; (* divsd, divss *) + end; + if stack[depth - 1].loc in {lConst, lMem, lFrame} then + match stack[depth - 1].loc of + | lConst: m := realConst(stack[depth - 1].val); + | lMem: m := stack[depth - 1].m; + | else: m := X.mem(RBP, stack[depth - 1].val); + end; + drop(); + X.sseM(c, top(), m, f); + else + y := peek(depth - 1); + drop(); + x := top(); + X.sse(c, x, y, f); + end; +end; + +(* The group 1 operation of +, -, &, | and xor *) +proc aluOf(sy: Scan.Sym): INT; +begin + match sy of + | sPlus: return X.aluAdd; + | sMinus: return X.aluSub; + | sAmp: return X.aluAnd; + | sBar: return X.aluOr; + | else: return X.aluXor; + end; +end; + +const + (* the condition codes of the comparisons, from sEql: = # < <= > >= *) + CcSigned: [6]INT = [X.ccE, X.ccNE, X.ccL, X.ccLE, X.ccG, X.ccGE]; + CcUnsigned: [6]INT = [X.ccE, X.ccNE, X.ccB, X.ccBE, X.ccA, X.ccAE]; + +(* The two values on top, the left op the right, an integer of size + bytes, signed or not, brought back to its width. *) +proc op*(sy: Scan.Sym; k: Kind; size: INT; signed: BOOL); +var v, o: I64; r, y, sh, bits: INT; c: BOOL; m: X.Mem; +begin + if k in {kF32, kF64} then realOp(sy, k); return; end; + bits := size * 8; + (* a constant on the left of an operation whose order doesn't matter + goes right, where it can be an immediate or a shift *) + 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) + and (stack[depth - 1].loc # lConst) then swap(); end; + c, v := topConst(); + (* A word's offset (see Entry) is carried through + and -, and + through * by a constant, as (x + a) * k is x * k + a * k: the + operation is done on the registers, the offsets worked out here, + and put on the result. x + 1 is only noted. A value changed in + place, lInto, has no offset. *) + o := 0; + if (bits = 64) and (stack[depth - 2].loc # lInto) + and ((((sy = Scan.sPlus) or (sy = Scan.sMinus))) or ((sy = Scan.sTimes) and c and fits32(v))) then + o := takeOff(depth - 2); + if sy = Scan.sTimes then o := o * v; + elsif c and fits32(v) then + if sy = Scan.sPlus then o := o + v; else o := o - v; end; + drop(); + if not (stack[depth - 1].loc in {lReg, lHeld}) then _ := top(); end; + putOff(o); + return; + elsif sy = Scan.sPlus then o := o + takeOff(depth - 1); + else o := o - takeOff(depth - 1); end; + end; + sh := -1; + if c and (((sy = Scan.sTimes) or (sy = Scan.sDiv) or (sy = Scan.sMod))) then sh := exactLog2(v); end; + if c and (sh >= 1) then + drop(); + r := top(); + if sy = Scan.sTimes then X.shiftI(X.shShl, r, sh); else divPow2(sy, r, sh, not signed); end; + 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 + drop(); + r := top(); + match sy of + | sTimes: X.imulI(r, INT(v)); + | sShl: X.shiftI(X.shShl, r, INT(v & I64(bits - 1))); + | sShr: + if signed then X.shiftI(X.shSar, r, INT(v & I64(bits - 1))); + else X.shiftI(X.shShr, r, INT(v & I64(bits - 1))); end; + | else: X.aluI(aluOf(sy), r, INT(v)); + end; + elsif topInMem() and (((sy = Scan.sPlus) or (sy = Scan.sMinus) or (sy = Scan.sAmp) or (sy = Scan.sBar) or (sy = Scan.sXor))) then + m := stack[depth - 1].m; + drop(); + r := top(); + X.aluM(aluOf(sy), r, m); + else + r, y := operands(); + if ((sy = Scan.sPlus) or (sy = Scan.sMinus) or (sy = Scan.sAmp) or (sy = Scan.sBar) or (sy = Scan.sXor)) then + X.alu(aluOf(sy), r, y); + elsif sy = Scan.sTimes then + X.imul(r, y); + elsif ((sy = Scan.sDiv) or (sy = Scan.sMod)) then + X.movRR(RAX, r); + if not signed then + X.movRI(RDX, 0); X.unary(6, y); (* div *) + else + (* 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); end; + X.cqo(); X.unary(7, y); (* idiv, of rdx:rax, which cqo made from rax *) + end; + if sy = Scan.sDiv then X.movRR(r, RAX); else X.movRR(r, RDX); end; + else (* sShl, sShr *) + (* the count modulo the width: the machine takes it modulo 64 *) + if y # RCX then X.movRR(RCX, y); end; + if bits < 64 then X.aluI(X.aluAnd, RCX, bits - 1); end; + if sy = Scan.sShl then X.shift(X.shShl, r); + elsif signed then X.shift(X.shSar, r); + else X.shift(X.shShr, r); end; + end; + end; + if bits < 64 then X.extend(r, size, signed); end; + stack[depth - 1].k := k; + if o # 0 then putOff(o); end; +end; + +(* ROL or ROR, by left, of the two values on top: an unsigned integer of + size bytes, under the count (report section 6.1). x86 takes the count + of rol and ror modulo 32, or 64 for a quadword, and a byte's or a + word's rotation then goes round modulo 8 or 16 itself: as 8 and 16 + divide 32, that is the count modulo the width, as the report has it, + with no mask of the count's own, which a shift needs. A constant + count is cut to the width here, an imm8; 0 rotates nothing. The bits + above the width are zero and stay so: rol al and rol ax leave them, + rol eax clears them. *) +proc rotate*(left: BOOL; size: INT); +var c: BOOL; v: I64; r, y, op: INT; +begin + if left then op := X.shRol; else op := X.shRor; end; + c, v := topConst(); + if c then + drop(); + r := top(); + v := v & I64(size * 8 - 1); + if v # 0 then X.rotate(op, r, size, INT(v)); end; + else + r, y := operands(); + if y # RCX then X.movRR(RCX, y); end; + X.rotate(op, r, size, -1); + end; + stack[depth - 1].k := kWord; +end; + +(* CLZ, if leading, or CTZ of the unsigned integer of size bytes on top + (report section 6.1). bsr finds the place h of its highest one bit, + and the zeros above it are the width less 1 less h; bsf finds the + place of its lowest, which is the zeros below it. Neither finds a + place in 0, the one value with no one bit, and both say so by ZF: + then the count is the whole width, as if h were -1, or the lowest + one at the width. The bits above size bytes are zero, so a scan of + all 64 sees the value's own. The baseline x86-64 lacks lzcnt and + tzcnt, which would count 0 by themselves. For a U32: + + bsr r, r bsf r, r + jnz L jnz L + mov r, -1 mov r, 32 + L: neg r L: + add r, 31 *) +proc countZeros*(leading: BOOL; size: INT); +var r, w, L: INT; +begin + r := top(); + w := size * 8; + L := NoLabel; + X.bitScan(leading, r); + X.jcc(X.ccNE, L); + if leading then X.movRI(r, -1); else X.movRI(r, w); end; + X.fixLink(L); + if leading then + X.unary(3, r); (* neg *) + X.aluI(X.aluAdd, r, w - 1); + end; + stack[depth - 1].k := kWord; +end; + +(* POPCOUNT of the integer or set on top (report section 6.1), counted + as lib/Bytes.raz counts bytes, without a loop: each two bits are + made the sum of their ones, then each four, then each byte, and a + multiplication by 0101...H adds the eight bytes' sums into the top + byte. The baseline x86-64 lacks popcnt. rax and rdx are + free between the stack machine's operations. + + mov rax, r; shr rax, 1; mov rdx, 5555...H; and rax, rdx; sub r, rax + mov rax, r; shr rax, 2; mov rdx, 3333...H; and rax, rdx; and r, rdx; add r, rax + mov rax, r; shr rax, 4; add r, rax; mov rdx, 0F0F...H; and r, rdx + mov rdx, 0101...H; imul r, rdx; shr r, 56 *) +proc popCount*; +var r: INT; +begin + r := top(); + (* each two bits: their value less its upper bit, which is its ones *) + X.movRR(RAX, r); + X.shiftI(X.shShr, RAX, 1); + X.movRI(RDX, 5555555555555555H); + X.alu(X.aluAnd, RAX, RDX); + X.alu(X.aluSub, r, RAX); + (* each four bits: the sums of its two pairs *) + X.movRR(RAX, r); + X.shiftI(X.shShr, RAX, 2); + X.movRI(RDX, 3333333333333333H); + X.alu(X.aluAnd, RAX, RDX); + X.alu(X.aluAnd, r, RDX); + X.alu(X.aluAdd, r, RAX); + (* each byte: the sums of its two halves, at most 8, which fits four bits *) + X.movRR(RAX, r); + X.shiftI(X.shShr, RAX, 4); + X.alu(X.aluAdd, r, RAX); + X.movRI(RDX, 0F0F0F0F0F0F0F0FH); + X.alu(X.aluAnd, r, RDX); + (* the top byte of r times 0101...H is the sum of all eight *) + X.movRI(RDX, 0101010101010101H); + X.imul(r, RDX); + X.shiftI(X.shShr, r, 56); + stack[depth - 1].k := kWord; +end; + +(* ABS of the real, or the signed integer of size bytes, on top (report + section 6.1); an unsigned one needs no code. A real's sign bit is + cleared, in rax, as neg flips it. An integer is negated, and its copy + in rax taken back if the negation is negative (SF), as it is for a + positive one. The smallest value negates to itself, negative, and so + gives itself, as -x does, with no branch and no check. A narrow + value is negated on all 64 bits, where its smallest is not the + smallest, so it is cut back to its width after, as neg does: + -128 in an I8 negates to 128, which is -128 again in 8 bits. + + movq rax, x; btr rax, 63; movq x, rax (F64; 31 for an F32) + mov rax, r; neg r; cmovs r, rax (I64; then movsx r, r for a narrow one) *) +proc abs*(k: Kind; size: INT); +var r: INT; +begin + r := top(); + if k in {kF32, kF64} then + X.movqRX(RAX, r); + if k = kF32 then X.btr(RAX, 31); else X.btr(RAX, 63); end; + X.movqXR(r, RAX); + else + X.movRR(RAX, r); + X.unary(3, r); (* neg *) + X.cmov(X.ccS, r, RAX); + if size < 8 then X.extend(r, size, true); end; + end; +end; + +(* The left op the right of the two values on top, as a BOOL *) +proc compare*(sy: Scan.Sym; k: Kind; signed: BOOL); +var f: BOOL; r, x, y, i: INT; v: I64; c: BOOL; m: X.Mem; +begin + i := INT(sy) - INT(Scan.sEql); + if k in {kF32, kF64} then + f := k = kF32; + y := peek(depth - 1); + drop(); + x := peek(depth - 1); + drop(); + r := target(); (* the BOOL, in the left's integer register *) + (* 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. *) + match sy of + | sEql: X.ucomis(x, y, f); X.setCC(X.ccE, r); X.setCC(X.ccNP, RCX); X.alu(X.aluAnd, r, RCX); + | sNeq: X.ucomis(x, y, f); X.setCC(X.ccNE, r); X.setCC(X.ccP, RCX); X.alu(X.aluOr, r, RCX); + | sLss: X.ucomis(y, x, f); X.setCC(X.ccA, r); + | sLeq: X.ucomis(y, x, f); X.setCC(X.ccAE, r); + | sGtr: X.ucomis(x, y, f); X.setCC(X.ccA, r); + | else: X.ucomis(x, y, f); X.setCC(X.ccAE, r); + end; + computed(kWord); + else + c, v := topConst(); + if c then + drop(); r := top(); cmpI(r, v); + elsif topInMem() then + m := stack[depth - 1].m; drop(); r := top(); X.aluM(X.aluCmp, r, m); + else + r, y := operands(); X.alu(X.aluCmp, r, y); + end; + if signed then X.setCC(CcSigned[i], r); else X.setCC(CcUnsigned[i], r); end; + end; + stack[depth - 1].k := kWord; +end; + +(* A real is negated by flipping its sign bit, in rax *) +proc neg*(k: Kind; size: INT; signed: BOOL); +var r: INT; +begin + r := top(); + if k in {kF32, kF64} then + X.movqRX(RAX, r); + if k = kF32 then X.btc(RAX, 31); else X.btc(RAX, 63); end; + X.movqXR(r, RAX); + else + X.unary(3, r); (* neg *) + if size < 8 then X.extend(r, size, signed); end; + end; +end; + +proc complement*(size: INT; signed: BOOL); +var r: INT; +begin + r := top(); + X.unary(2, r); (* not *) + if size < 8 then X.extend(r, size, signed); end; +end; + +proc notBool*; +begin + X.aluI(X.aluXor, top(), 1); +end; + +(* The integer on top, brought to size bytes *) +proc narrow*(size: INT; signed: BOOL); +var r: INT; +begin + r := top(); + if size < 8 then X.extend(r, size, signed); end; + stack[depth - 1].k := kWord; +end; + +(* The integer on top, as a real of kind k; big if it may be a U64 above + high(I64), which the machine would take as negative *) +proc intToReal*(k: Kind; big: BOOL); +var L1, L2, r, x: INT; f: BOOL; +begin + f := k = kF32; + r := top(); + x := regIn(k, depth - 1); (* its xmm register *) + if big then + (* above high(I64): halve, keeping the low bit, and double *) + L1 := NoLabel; L2 := NoLabel; + X.testRR(r, r); + X.jcc(X.ccS, L1); + X.cvtsi2s(x, r, f); + X.jmp(L2); + X.fixLink(L1); + X.movRR(RCX, r); + X.shiftI(X.shShr, RCX, 1); + X.aluI(X.aluAnd, r, 1); + X.alu(X.aluOr, RCX, r); + X.cvtsi2s(x, RCX, f); + X.sse(58H, x, x, f); (* adds it to itself: doubles *) + X.fixLink(L2); + else + X.cvtsi2s(x, r, f); + end; + stack[depth - 1].k := k; +end; + +(* The real of kind k on top, truncated to an integer *) +proc realToInt*(k: Kind); +var x: INT; +begin + x := top(); + X.cvtts2si(regIn(kWord, depth - 1), x, k = kF32); + stack[depth - 1].k := kWord; +end; + +(* The real of kind k on top, as the other kind *) +proc realToReal*(k: Kind); +var x: INT; +begin + x := top(); + X.sse(5AH, x, x, k = kF32); (* cvtss2sd, or cvtsd2ss *) + if k = kF32 then stack[depth - 1].k := kF64; else stack[depth - 1].k := kF32; end; +end; + +(* 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. *) +proc compareSeq*(a, b: I64; shift: INT; eq: BOOL); +var differ, r: INT; +begin + clobberArgs(); + r := target(); + X.load(RCX, X.mem(RBP, b + 8), 8, false); + X.aluM(X.aluCmp, RCX, X.mem(RBP, a + 8)); + differ := NoLabel; + X.jcc(X.ccNE, differ); + X.load(RSI, X.mem(RBP, b), 8, false); + X.load(RDI, X.mem(RBP, a), 8, false); + if shift > 0 then X.shiftI(X.shShl, RCX, shift); end; + (* repe cmpsb with rcx = 0 leaves the flags alone, so make them say + equal first, which is right if there are no bytes *) + X.alu(X.aluCmp, RCX, RCX); + X.repeCmpsb(); + X.fixLink(differ); + if eq then X.setCC(X.ccE, r); else X.setCC(X.ccNE, r); end; + computed(kWord); +end; + +(* 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. *) +proc errorText*(tmp: I64); +var L: INT; +begin + popTo(RAX); + X.movRI(RCX, 0); + L := NoLabel; + X.testRR(RAX, RAX); + X.jcc(X.ccE, L); + X.load(RCX, X.mem(RAX, 0), 8, false); + X.lea(RAX, X.mem(RAX, 8)); + X.fixLink(L); + X.store(X.mem(RBP, tmp), RAX, 8); + X.store(X.mem(RBP, tmp + 8), RCX, 8); +end; + +(* Pops a step and an integer variable's address, and adds the step to + it, or takes it away. *) +proc incDec*(size: INT; signed, dec: BOOL); +var r, y, o: INT; v: I64; a: Adr; c: BOOL; +begin + c, v := topConst(); + if dec then o := X.aluSub; else o := X.aluAdd; end; + if c and fits32(v) then + drop(); + a.base := bStack; a.off := 0; + X.aluMI(o, place(a, RCX), INT(v), size); + return; + end; + r, y := operands(); + drop(); + X.load(RAX, X.mem(r, 0), size, signed); + X.alu(o, RAX, y); + X.store(X.mem(r, 0), RAX, size); +end; + +(* INC or DEC of the variable in register r, by the value on top; a + narrow one wraps at its width *) +proc incDecReg*(r, size: INT; signed, dec: BOOL); +var y, o: INT; v: I64; c: BOOL; +begin + if dec then o := X.aluSub; else o := X.aluAdd; end; + c, v := topConst(); + if c and fits32(v) then X.aluI(o, r, INT(v)); + else y := top(); X.alu(o, r, y); end; + drop(); + if size < 8 then X.extend(r, size, signed); end; +end; + +(* The pointer on top, which NEW got, to size zero bytes unless nil *) +proc zeroNew*(size: I64); +var L, r: INT; +begin + clobberArgs(); + r := top(); + L := NoLabel; + X.testRR(r, r); + X.jcc(X.ccE, L); + X.movRR(RDI, r); + X.movRI(RCX, size); + X.movRI(RAX, 0); + X.repStos(1); + X.fixLink(L); +end; + +(* CAS(p, old, new), XCHG(p, v) or XADD(p, v), from the stack: the + result where p was *) +proc atomic*(which: INT); +var r, n: INT; +begin + if which = Sym.bCas then readMems(depth - 3); else readMems(depth - 2); end; (* what it writes may be one *) + if which = Sym.bCas then n := top(); drop(); end; + popTo(RAX); (* cmpxchg compares with rax, so CAS's old value goes there *) + r := top(); + match which of + | Sym.bCas: X.lockCmpxchg(X.mem(r, 0), n); X.setCC(X.ccE, r); + | Sym.bXchg: X.xchg(X.mem(r, 0), RAX); X.movRR(r, RAX); + | else: X.lockXadd(X.mem(r, 0), RAX); X.movRR(r, RAX); + end; + stack[depth - 1].k := kWord; +end; + +(* 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. *) +proc sysCall*(n: INT); +const SysRegs: [7]INT = [RAX, RDI, RSI, RDX, R10, R8, R9]; +var i: INT; +begin + clobberArgs(); + spillBelow(depth); + for i := 0 to n - 1 do valueTo(depth - n + i, SysRegs[i]); end; + for i := 1 to n do drop(); end; + X.syscall(); + X.movRR(target(), RAX); + computed(kWord); +end; + +proc fence*; +begin + X.mfence(); +end; + +(* Jumps. A label is the chain of the jumps to it, until it is placed. *) + +proc jump*(var L: INT); +begin + X.jmp(L); +end; + +(* Pops a BOOL, and jumps if it is when *) +proc jumpIf*(var L: INT; when: BOOL); +var r: INT; +begin + r := peek(depth - 1); + drop(); + X.testRR(r, r); + if when then X.jcc(X.ccNE, L); else X.jcc(X.ccE, L); end; +end; + +(* Pops two integers, and jumps if the left op the right *) +proc jumpCmp*(sy: Scan.Sym; signed: BOOL; var L: INT); +var r, y, i: INT; v: I64; c: BOOL; m: X.Mem; +begin + i := INT(sy) - INT(Scan.sEql); + (* a comparison changes neither: a variable's register will do *) + c, v := topConst(); + if c then + drop(); r := peek(depth - 1); cmpI(r, v); + elsif topInMem() then + m := stack[depth - 1].m; drop(); r := peek(depth - 1); X.aluM(X.aluCmp, r, m); + else + y := peek(depth - 1); drop(); r := peek(depth - 1); X.alu(X.aluCmp, r, y); + end; + drop(); + if signed then X.jcc(CcSigned[i], L); else X.jcc(CcUnsigned[i], L); end; +end; + +(* 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. 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. *) +proc jumpOut*(sy: Scan.Sym; signed: BOOL; var L: INT); +begin + spillBelow(depth - 2); + jumpCmp(sy, signed, L); +end; + +(* 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. *) +proc condValue*(notOp: Scan.Sym; signed: BOOL; fj, tj: INT); +var r, e: INT; +begin + jumpOut(notOp, signed, fj); + X.fixLink(tj); + r := target(); + X.movRI(r, 1); + e := NoLabel; + X.jmp(e); + X.fixLink(fj); + X.movRI(r, 0); + X.fixLink(e); + 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. *) +proc jumpBack*(top: INT); +begin + X.jmpBack(top); +end; + +proc fix*(L: INT); +begin + X.fixLink(L); +end; + +(* A jump table, for a match on the integer in frame slot slot, whose + labels run from lo up for n values. The selector less lo, compared + unsigned (so below lo is above n too), is out of the table if it + isn't below n, and goes to the else arm at elseAt, or, if there is + none, to endL, the end of the match. Else it indexes a table of + 4-byte offsets, each from the start of the lea, that follows the + jump, and the code jumps to its start plus the entry: + + mov rax, [slot] + sub rax, lo + cmp rax, n - 1 + ja else + lea rcx, [rip + start] start: this very lea + movsxd rax, [rcx + rax*4 + 17] + add rax, rcx + jmp rax + table: .long arm0 - start, arm1 - start, ... + + The four instructions after the compare are 7, 5, 3 and 2 bytes, so + the table is 17 bytes on, which jumpTable checks. It returns start; + the caller then makes the n entries with tableEntry. *) +proc jumpTable*(slot, lo: I64; n, elseAt: INT; var endL: INT): INT; +const TableAt = 17; +var start: INT; +begin + X.load(RAX, X.mem(RBP, slot), 8, false); + if lo # 0 then X.aluI(X.aluSub, RAX, INT(lo)); end; + X.aluI(X.aluCmp, RAX, n - 1); + if elseAt # NoLabel then X.jccBack(X.ccA, elseAt); else X.jcc(X.ccA, endL); end; + start := Chunk.pc; + X.lea(RCX, X.here()); + X.load(RAX, X.memIdx(RCX, RAX, 4, TableAt), 4, true); + X.alu(X.aluAdd, RAX, RCX); + X.jmpR(RAX); + if Chunk.pc # start + TableAt then Diag.fatal("internal error: the jump table is not where it was said"); end; + return start; +end; + +(* The next entry of the table that jumpTable started at table: the + code at target *) +proc tableEntry*(table, target: INT); +begin + Chunk.put4(target - table); +end; + +proc alignLoop*; +begin + X.align(32); +end; + +proc joinJumps*(L1, L2: INT): INT; +begin + return X.joinLinks(L1, L2); +end; + +proc fixTo*(L, top: INT); +begin + X.fixLinkTo(L, top); +end; + +(* Checks *) + +const + NoBase = -2; (* a Mem that is no memory *) + ARegister = -3; (* a Mem that is no memory but a register, its index *) + +(* The name s, interned *) +proc internStr(s: []const U8): INT; +begin + return Scan.intern(SYSTEM.PTR(s), LEN(s)); +end; + +(* 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, 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), a nil pointer (4), or a view at index a that runs + past a length len (7). 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, or in register m.index if it is ARegister. + rdi and rsi are passed on as they were, since a parameter may be kept + in them, for the trap report to show: so a goes to the stub in rax. + 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 (its line and column, worked out + now, while the source read is p's), never returns, and may use any + register once it has read what it needs. *) +proc check(cc, what: INT; p: Diag.Pos; ra: INT; m: X.Mem; n: I64; name: INT); +begin + if numFails > LEN(fails) - 1 then + _ := Scan.mark(Diag.say("more than {} checks in one procedure", [Fmt.int(LEN(fails))])); + return; + end; + fails[numFails].L := NoLabel; + X.jcc(cc xor 1, fails[numFails].L); (* x86's conditions come in pairs, the other one its last bit flipped *) + fails[numFails].what := what; + fails[numFails].ra := ra; + fails[numFails].m := m; + fails[numFails].n := n; + fails[numFails].name := name; + fails[numFails].path := Chunk.curFilePath(); + fails[numFails].line, fails[numFails].col := Scan.lineCol(p.a); + INC(numFails); +end; + +(* The failures of the procedure's checks: each gives Rt.fail its values + and the place of the offending expression, through a stub for its + kind, which takes the place from where it was called *) +proc endFails; +var i, path: INT; f: Fail; +begin + path := Chunk.curFilePath(); + for i := 0 to numFails - 1 do + f := fails[i]; + X.fixLink(f.L); + Chunk.setCurFile(f.path); + Chunk.noteLine(f.line, f.col); + Chunk.setCurFile(path); + if f.ra # RAX then X.movRR(RAX, f.ra); end; + if f.m.base = NoBase then X.movRI(RCX, f.n); + elsif f.m.base = ARegister then X.movRR(RCX, f.m.index); + else X.load(RCX, f.m, 8, false); end; + if f.name >= 0 then X.lea(R9, X.memRip(f.name, 0)); end; + if failStubs[f.what] < 0 then + failStubs[f.what] := Chunk.newChunk(Chunk.secText, internStr("Rt"), internStr(StubNames[f.what])); + end; + X.callChunk(failStubs[f.what]); + end; + numFails := 0; +end; + +(* For check: a length known here, not in memory *) +proc noMem: X.Mem; +begin + return X.mem(NoBase, 0); +end; + +(* For check: a length in register r, a slice's in registers *) +proc inRegister(r: INT): X.Mem; +var m: X.Mem; +begin + m := X.mem(ARegister, 0); + m.index := r; + return m; +end; + +(* The index on top is below n, unsigned *) +proc checkIndex*(n: I64; p: Diag.Pos); +var r: INT; +begin + r := peek(depth - 1); + cmpI(r, n); + check(X.ccB, 0, p, r, noMem(), n, -1); +end; + +(* The index on top is the element a view starts at, in an array of n + elements: the view needs k elements from there, so the index must be + below n - k + 1, which is below. A negative index is a huge one, + unsigned, so one comparison does (report section 6.9). *) +proc checkView*(n, below: I64; p: Diag.Pos); +var r: INT; +begin + r := peek(depth - 1); + cmpI(r, below); + check(X.ccB, 7, p, r, noMem(), n, -1); +end; + +(* What a failed index check is: an index past the length (0), or a + view that runs past it (7), when the view needs room elements more + than the one indexed. *) +proc kindOfIndex(room: I64): INT; +begin + if room > 0 then return 7; end; + return 0; +end; + +(* A view of a slice's element, at the index in r, needs room elements + after it: rdx holds the slice's length, which r is below already, + so length - r, at least 1, can't wrap, and must be more than room. + The length is at m for the message. *) +proc checkRoom(r: INT; room: I64; p: Diag.Pos; m: X.Mem); +begin + X.alu(X.aluSub, RDX, r); + X.aluI(X.aluCmp, RDX, INT(room)); + check(X.ccA, 7, p, r, m, 0, -1); +end; + +(* The integer on top is a position of an enumeration of n names *) +proc checkEnum*(n: I64; name: INT; p: Diag.Pos); +var r: INT; +begin + r := top(); + cmpI(r, n); + check(X.ccB, 2, p, r, noMem(), n, name); +end; + +(* The address on top, from a pointer, which is to be used reach bytes + past: the program stops if it is nil, unless the machine would stop + it, as for a reach within NilPage. *) +proc checkNil*(reach: I64; p: Diag.Pos); +var r: INT; +begin + if reach <= NilPage then return; end; + r := top(); + X.testRR(r, r); + check(X.ccNE, 4, p, r, noMem(), 0, -1); +end; + +(* The displacement disp of an element of size bytes, with the offset of + the index on top taken into it if it fits: s[k - 1] is [r13 + r9 * 8 + - 8] *) +proc indexOff(size, disp: I64): I64; +begin + if fits32(disp + stack[depth - 1].off * size) then return disp + takeOff(depth - 1) * size; end; + return disp; +end; + +(* Pops an index, and the address of the slice at a if it is on the + stack, and pushes the address of its element of size bytes: the + index, checked against the length, times size, plus the pointer. + It is worked out in the index's own register, which then holds the + address; but if the slice's address is on the stack, under the + index, the element's register is the one that holds that, still + needed, so the work is done in rax. A slice in registers is + compared with and added to them; for an element of 1, 2, 4 or 8 + bytes, its address is only noted, as the operand [pointer + index * + size], to be read or written where it is used (lIdx). *) +proc indexSlice*(a: Adr; size, room: I64; checked: BOOL; p: Diag.Pos); +var m, ml: X.Mem; r: INT; inRax: BOOL; o: I64; +begin + if (a.base = bReg) and (((size = 1) or (size = 2) or (size = 4) or (size = 8))) then + o := 0; + if not checked then o := indexOff(size, 0); end; + r := peek(depth - 1); + if checked then + X.alu(X.aluCmp, r, a.hi); + check(X.ccB, kindOfIndex(room), p, r, inRegister(a.hi), 0, -1); + if room > 0 then X.movRR(RDX, a.hi); checkRoom(r, room, p, inRegister(a.hi)); end; + end; + drop(); + newMem(lIdx, X.memIdx(a.chunk, r, INT(size), o), kWord, 8, false); + return; + end; + inRax := a.base = bStack; + if inRax then r := RAX; popTo(RAX); + else r := top(); drop(); end; + if a.base = bReg then + if checked then + X.alu(X.aluCmp, r, a.hi); + check(X.ccB, kindOfIndex(room), p, r, inRegister(a.hi), 0, -1); + if room > 0 then X.movRR(RDX, a.hi); checkRoom(r, room, p, inRegister(a.hi)); end; + end; + mulI(r, size); + X.alu(X.aluAdd, r, a.chunk); + else + m := place(a, RCX); + ml := m; ml.disp := ml.disp + 8; + if checked then + X.aluM(X.aluCmp, r, ml); + check(X.ccB, kindOfIndex(room), p, r, ml, 0, -1); + if room > 0 then X.load(RDX, ml, 8, false); checkRoom(r, room, p, ml); end; + end; + mulI(r, size); + X.aluM(X.aluAdd, r, m); + end; + if inRax then X.movRR(target(), RAX); + else _ := claim(depth, kWord); end; (* the index's register again, now for the address *) + computed(kWord); +end; + +(* Whether r is one of the stack's registers, not a variable's *) +proc isStackReg(r: INT): BOOL; +var i: INT; +begin + for i := 0 to NumRegs - 1 do + if Regs[i] = r then return true; end; + end; + return false; +end; + +(* Pops an index and the pointer under it, and pushes the address of + the element of size bytes: p + i * size. For an element of 1, 2, 4 + or 8 bytes it is only noted, as the operand [p + i * size] (lIdx), to + be read or written where it is used, when at most one of the two is + in a stack register, the register the new value owns. Otherwise lea + adds them up, in one instruction in place of a multiplication and an + addition. *) +proc indexPtr*(size: I64); +var b, x, own: INT; o: I64; +begin + o := 0; + if fits32(stack[depth - 2].off + stack[depth - 1].off * size) then + o := takeOff(depth - 2) + takeOff(depth - 1) * size; + end; + b := peek(depth - 2); + x := peek(depth - 1); + own := Regs[(depth - 2) mod NumRegs]; + drop(); + drop(); + if (not isStackReg(b) or (b = own)) and (not isStackReg(x) or (x = own)) then + newMem(lIdx, X.memIdx(b, x, INT(size), o), kWord, 8, false); + if b = own then owner[(depth - 1) mod NumRegs] := depth - 1; end; + else + X.lea(target(), X.memIdx(b, x, INT(size), o)); + computed(kWord); + end; +end; + +(* Pops an index, checked, and makes the address of the element it + picks of the array at a. An element of 1, 2, + 4 or 8 bytes is only noted, as the operand [base + index * size] + (lIdx): an array in the frame has rbp as its base, one reached + through a pointer in a register (a var or const parameter) that + register, and one in a chunk its address as the displacement + (X.memAbs), with no lea. Any other is added up. *) +proc indexArray*(a: Adr; size: I64); +var r: INT; o: I64; +begin + if (((size = 1) or (size = 2) or (size = 4) or (size = 8))) and (a.base in {bFrame, bGlobal, bPtr}) then + o := indexOff(size, a.off); + r := peek(depth - 1); + drop(); + if a.base = bFrame then + newMem(lIdx, X.memIdx(RBP, r, INT(size), o), kWord, 8, false); + elsif a.base = bPtr then + newMem(lIdx, X.memIdx(a.chunk, r, INT(size), o), kWord, 8, false); + else + newMem(lIdx, X.memAbs(a.chunk, r, INT(size), INT(o)), kWord, 8, false); + end; + else + mulI(top(), size); + pushAdr(a); + op(Scan.sPlus, kWord, 8, false); + end; +end; + +(* Pops lo and hi, and the address of the array or slice at a if it is + on the stack, and makes the slice lo..hi of it, with elements of size + bytes, in the frame at tmp; the array has n elements. *) +proc slice*(a: Adr; isArray: BOOL; n, size, tmp: I64; checked: BOOL; p: Diag.Pos); +var m, ml: X.Mem; +begin + popTo(RDX); + popTo(RCX); + if a.base = bSlot then clobberArgs(); end; (* place loads its slot into rdi *) + if a.base = bReg then + ml := inRegister(a.hi); (* a slice in registers *) + else + m := place(a, RDI); + ml := m; ml.disp := ml.disp + 8; + end; + if checked then + (* two checks, both unsigned, so that a negative bound fails too: + hi against the length, then lo against hi *) + if isArray then cmpI(RDX, n); ml := noMem(); + elsif a.base = bReg then X.alu(X.aluCmp, RDX, a.hi); + else X.aluM(X.aluCmp, RDX, ml); end; + check(X.ccBE, 1, p, RCX, ml, n, -1); + X.alu(X.aluCmp, RCX, RDX); + check(X.ccBE, 1, p, RCX, ml, n, -1); + end; + X.movRR(RAX, RDX); + X.alu(X.aluSub, RAX, RCX); + X.store(X.mem(RBP, tmp + 8), RAX, 8); + mulI(RCX, size); + if isArray then X.lea(RAX, m); + elsif a.base = bReg then X.movRR(RAX, a.chunk); + else X.load(RAX, m, 8, false); end; + X.alu(X.aluAdd, RAX, RCX); + X.store(X.mem(RBP, tmp), RAX, 8); +end; + +(* The rcx bytes below rsi to those below rdi, n at a time while rcx + holds n or more, through rax, moving rsi, rdi and rcx down: COPY's + backward copy, as a loop, since rep movsb going down (std) moves a + byte at a time. *) +proc copyDown(n: INT); +var top, out: INT; +begin + top := Chunk.pc; + X.aluI(X.aluCmp, RCX, n); + out := NoLabel; + X.jcc(X.ccB, out); + X.aluI(X.aluSub, RSI, n); + X.aluI(X.aluSub, RDI, n); + X.aluI(X.aluSub, RCX, n); + X.load(RAX, X.mem(RSI, 0), n, false); + X.store(X.mem(RDI, 0), RAX, n); + X.jmpBack(top); + X.fixLink(out); +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 at least as long + (the source may be shorter), as one block. It goes forwards, by rep + movsb, but backwards when the destination starts inside the source, + so that an overlap comes out right: by words from the ends, then the + last few bytes one by one. *) +proc copySlice*(dOff, sOff, size: I64; checked: BOOL; p: Diag.Pos); +var ml: X.Mem; L, E: INT; +begin + clobberArgs(); + X.load(RDX, X.mem(RBP, sOff + 8), 8, false); + if checked then + ml := X.mem(RBP, dOff + 8); + X.movRI(RAX, 0); + X.aluM(X.aluCmp, RDX, ml); + check(X.ccBE, 1, p, RAX, ml, 0, -1); + end; + X.movRR(RCX, RDX); + mulI(RCX, size); + X.load(RSI, X.mem(RBP, sOff), 8, false); + X.load(RDI, X.mem(RBP, dOff), 8, false); + L := NoLabel; + X.alu(X.aluCmp, RDI, RSI); + X.jcc(X.ccBE, L); (* the destination is not above: forwards, at L *) + X.lea(RAX, X.memIdx(RSI, RCX, 1, 0)); + X.alu(X.aluCmp, RDI, RAX); + X.jcc(X.ccAE, L); (* nor does it start inside the source *) + X.alu(X.aluAdd, RSI, RCX); (* backwards, from the ends *) + X.alu(X.aluAdd, RDI, RCX); + copyDown(8); + copyDown(1); + E := NoLabel; + X.jmp(E); + X.fixLink(L); + X.repMovsb(); + X.fixLink(E); +end; + +(* The most elements FILL stores one by one: as for MaxMoves, a store + each costs less than rep stos takes to start, which at 10 elements + is twice the time. *) +const FewFills = 16; + +(* rax, an element of size bytes, 1, 2, 4 or 8, into each of the + elements of the slice in the frame at dOff, of which there are n if + n isn't -1. Few, as of a short array, are a store each; else, at run + time, a loop of stores for fewer than FewFills, or rep stos of the + element's width: + + mov rdi, [rbp + dOff] + mov rcx, [rbp + dOff + 8] + cmp rcx, 16 + jae many + test rcx, rcx + jz out + top: mov [rdi], eax ; for a U32 + add rdi, 4 + sub rcx, 1 + jne top + jmp out + many: rep stosd + out: *) +proc fillScalar(dOff, size, n: I64); +var i: I64; many, out, top: INT; +begin + X.load(RDI, X.mem(RBP, dOff), 8, false); + if (n >= 0) and (n <= FewFills) then + for i := 0 to n - 1 do X.store(X.mem(RDI, i * size), RAX, INT(size)); end; + return; + end; + X.load(RCX, X.mem(RBP, dOff + 8), 8, false); + many := NoLabel; + out := NoLabel; + X.aluI(X.aluCmp, RCX, FewFills); + X.jcc(X.ccAE, many); + X.testRR(RCX, RCX); + X.jcc(X.ccE, out); + top := Chunk.pc; + X.store(X.mem(RDI, 0), RAX, INT(size)); + X.aluI(X.aluAdd, RDI, INT(size)); + X.aluI(X.aluSub, RCX, 1); + X.jccBack(X.ccNE, top); + X.jmp(out); + X.fixLink(many); + X.repStos(INT(size)); + X.fixLink(out); +end; + +(* The size bytes at rsi into each element of the slice in the frame at + dOff: into the first by copyBytes, and from there forward by rep + movsb, from d[0] on to d[1] on. A forward copy reads each byte after it has written it, size + bytes before, so the first element repeats through the rest: + + mov rdi, [rbp + dOff] + mov rdx, [rbp + dOff + 8] + test rdx, rdx + jz out ; nothing to fill + ... ; copyBytes(size): d[0] := x + mov rsi, [rbp + dOff] + lea rdi, [rsi + size] + lea rcx, [rdx - 1] + imul rcx, size ; the bytes of d[1..n] + rep movsb + out: *) +proc fillCopy(dOff, size: I64); +var out: INT; +begin + X.load(RDI, X.mem(RBP, dOff), 8, false); + X.load(RDX, X.mem(RBP, dOff + 8), 8, false); + X.testRR(RDX, RDX); + out := NoLabel; + X.jcc(X.ccE, out); + copyBytes(size); + X.load(RSI, X.mem(RBP, dOff), 8, false); + X.lea(RDI, X.mem(RSI, size)); + X.lea(RCX, X.mem(RDX, -1)); + mulI(RCX, size); + X.repMovsb(); + X.fixLink(out); +end; + +(* FILL: every element of the slice in the frame at dOff, of size bytes + each, set to the value on top of the stack if the element is a + scalar, or else to the size bytes at the address on top. n is how + many elements the slice has if that is known, as for an array, else + -1. A scalar goes into rax and is stored as it is, a real's bits as + an integer's (fillScalar); but a constant zero into an array of n + elements is n * size zero bytes, as NEW's zeroing is: by moves, or + rep stosb (zeroBytes). Any other element is copied (fillCopy). *) +proc fillSlice*(dOff, size, n: I64; scalar: BOOL); +var isConst: BOOL; v: I64; +begin + clobberArgs(); + isConst, v := topConst(); + if scalar and isConst and (v = 0) and (n >= 0) then + drop(); + X.load(RDI, X.mem(RBP, dOff), 8, false); + zeroBytes(n * size); + elsif scalar then + popTo(RAX); + fillScalar(dOff, size, n); + else + popTo(RSI); + fillCopy(dOff, size); + end; +end; + +(* Pops a pointer, lo and hi, and makes the slice p[lo..hi] at tmp. Its + bounds can't be known, but it can't run backwards. *) +proc slicePtr*(size, tmp: I64; checked: BOOL; p: Diag.Pos); +begin + clobberArgs(); + popTo(RDX); + popTo(RCX); + popTo(RDI); + if checked then + X.alu(X.aluCmp, RCX, RDX); + check(X.ccLE, 3, p, RCX, noMem(), 0, -1); + end; + X.movRR(RAX, RDX); + X.alu(X.aluSub, RAX, RCX); + X.store(X.mem(RBP, tmp + 8), RAX, 8); + mulI(RCX, size); + X.alu(X.aluAdd, RCX, RDI); + X.store(X.mem(RBP, tmp), RCX, 8); +end; + +(* Calls *) + +(* 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. *) + +proc call*(var c: CallInfo); +var + res: ^Sym.Type; i, ni, nf, k, pad, r, first: INT; + onStack: [64]BOOL; late: [2]INT; (* late: the values for r8 and r9 *) +begin + (* the arguments are the c.n values on top, where computing them left + them; the registers in use under them are saved around the call *) + clobberArgs(); + first := depth - c.n; + spillBelow(first); + res := c.sig^.base; + c.ret := 0; + ni := 0; nf := 0; + if (res # nil) and Sym.holdsArray(res) then + (* a slice of it may be kept for the rest of the procedure + (report 8), so its slot lasts as long *) + c.ret := allocPerm(res^.size, res^.align); + ni := 1; + elsif (res # nil) and (Sym.behindPointer(res) or (res^.form = Sym.fSlice)) then + c.ret := allocTemp(res^.size, res^.align); + if Sym.behindPointer(res) then ni := 1; end; + end; + (* the System V classes: each argument in the next free register of + its kind, or else on the stack *) + k := 0; + for i := 0 to c.n - 1 do + if c.isF[i] then + onStack[i] := nf >= 8; + if nf < 8 then INC(nf); end; + else + (* a slice's words both go in registers, or both on the stack *) + if (i > 0) and c.pair[i - 1] then onStack[i] := onStack[i - 1]; + elsif c.pair[i] then onStack[i] := ni > 4; + else onStack[i] := ni >= 6; end; + if not onStack[i] then INC(ni); end; + end; + if onStack[i] then INC(k); end; + end; + (* 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 := 0; + if ((pushed + k) & 1) # 0 then pad := 1; end; + if pad # 0 then X.aluI(X.aluSub, RSP, 8); end; + for i := c.n - 1 to 0 by -1 do + if onStack[i] then + valueTo(first + i, RAX); + X.push(RAX); + end; + end; + ni := 0; nf := 0; + late[0] := -1; late[1] := -1; + if (c.ret # 0) and Sym.behindPointer(res) then X.lea(RDI, X.mem(RBP, c.ret)); ni := 1; end; + (* rdi, rsi, rdx, rcx and the xmm registers first; r8 and r9 last, as + 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 + xValueTo(first + i, nf); + INC(nf); + else + if ni < 4 then valueTo(first + i, IntRegs[ni]); else late[ni - 4] := first + i; end; + INC(ni); + end; + end; + end; + if late[0] >= 0 then valueTo(late[0], RAX); end; + if late[1] >= 0 then valueTo(late[1], R9); end; + if late[0] >= 0 then X.movRR(R8, RAX); end; + for i := 1 to c.n do drop(); end; + (* a procedure taking ... is told in al how many xmm registers it got *) + if c.sig^.variadic then X.movRI(RAX, nf); end; + if c.ext then X.callM(X.memRip(c.chunk, 0)); + elsif c.chunk >= 0 then X.callChunk(c.chunk); + else + (* r11 is scratch: caller-saved, carrying no argument, and free, + as the value stack was spilled above *) + X.load(R11, X.mem(RBP, c.target), 8, false); + X.callR(R11); + end; + if k + pad > 0 then X.aluI(X.aluAdd, RSP, 8 * (k + pad)); end; + (* the variables in xmm registers, which the call may have changed, + from their slots *) + for i := 0 to LEN(XVarRegs) - 1 do + if (regMask & (1 shl (XBit + i))) # 0 then + X.movsXM(XVarRegs[i] - XmmVar, X.mem(RBP, homes[i]), false); + end; + end; + (* the result: a slice in rax and rdx goes to the caller's temporary, + two results on the stack, the first under the second, and a single + value on top *) + if res # nil then + if res^.form = Sym.fSlice then + X.store(X.mem(RBP, c.ret), RAX, 8); + X.store(X.mem(RBP, c.ret + 8), RDX, 8); + elsif Sym.inTwoRegs(res) then + X.movRR(target(), RAX); computed(kWord); + X.movRR(target(), RDX); computed(kWord); + elsif (c.ret = 0) and (res^.form = Sym.fReal) then + X.movX(xTarget(), 0); + computed(kindOf(res)); + elsif c.ret = 0 then + r := target(); + X.movRR(r, RAX); + if res^.form = Sym.fBool then X.extend(r, 1, false); + elsif (res^.form = Sym.fInt) and (res^.size < 8) then X.extend(r, INT(res^.size), res^.signed); end; + computed(kindOf(res)); + end; + end; +end; + +(* 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. *) +proc allocTemp*(size, align: I64): I64; +begin + if align < 1 then align := 1; end; + frameTop := Sym.alignUp(frameTop + size, align); + if frameTop > frameMax then frameMax := frameTop; end; + return -frameTop; +end; + +proc allocPerm*(size, align: I64): I64; +var s: I64; +begin + s := allocTemp(size, align); + permTop := frameTop; + return s; +end; + +proc tempMark*: I64; +begin + return frameTop; +end; + +(* The slots allocated since the mark m are free again, but those + allocPerm made stay *) +proc releaseTemps*(m: I64); +begin + if m < permTop then m := permTop; end; + frameTop := m; +end; + +(* Every slot used so far stays reserved for the rest of the procedure: + a deferred statement's temporaries live until it runs. *) +proc keepTemps*; +begin + frameTop := frameMax; + permTop := frameMax; +end; + +(* The parameters' places: each in a frame slot of its own, stored there + from its register on entry, or above the frame where the caller + pushed it. A var parameter, and a record or array passed by value, + holds an address (ind). *) +proc beginProc*(sig: ^Sym.Type; params: ^Sym.Obj); +var p: ^Sym.Obj; ni, nf, k: INT; stackOff: I64; f: BOOL; +begin + frameTop := 0; frameMax := 0; permTop := 0; + resetStack(0, 0); + exitL := NoLabel; + numIn := 0; + lost := false; + kept := 0; + resType := sig^.base; + procParams := params; + regMask := 0; + ni := 0; nf := 0; stackOff := 16; (* stackOff: above the saved rbp and the return address *) + if (resType # nil) and Sym.behindPointer(resType) then + retSlot := allocPerm(8, 8); + inReg[0] := RDI; inSlot[0] := retSlot; inSize[0] := 8; inObj[0] := nil; + numIn := 1; ni := 1; + end; + p := params; + while p # nil do + p^.ind := p^.isVar or (Sym.isAggregate(p^.typ) and (p^.typ^.form # Sym.fSlice)); + f := (p^.typ^.form = Sym.fReal) and not p^.isVar; + if (p^.typ^.form = Sym.fSlice) and not p^.isVar then + (* its two words, in two registers or both on the stack *) + if ni <= 4 then + p^.val := allocPerm(16, 8); + for k := 0 to 1 do + inReg[numIn] := IntRegs[ni]; inSlot[numIn] := p^.val + I64(8 * k); + inSize[numIn] := 8; inObj[numIn] := p; + INC(numIn); INC(ni); + end; + else + p^.val := stackOff; + INC(stackOff, 16); + end; + elsif (f and (nf < 8)) or (not f and (ni < 6)) then + 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 + inReg[numIn] := -1 - nf; INC(nf); + else + inReg[numIn] := IntRegs[ni]; INC(ni); + end; + inSlot[numIn] := p^.val; + inObj[numIn] := p; + if p^.ind then inSize[numIn] := 8; + elsif p^.typ^.form in {Sym.fInt, Sym.fBool, Sym.fEnum, Sym.fSet, Sym.fReal} then inSize[numIn] := INT(p^.typ^.size); + else inSize[numIn] := 8; end; + INC(numIn); + else + p^.val := stackOff; + INC(stackOff, 8); + end; + p := p^.next; + end; + paramTop := frameTop; +end; + +(* The frame as beginProc left it, with the parameters' slots only: the + locals are given theirs again once their registers are chosen. *) +proc resetLocals*; +begin + frameTop := paramTop; frameMax := paramTop; permTop := paramTop; +end; + +(* The register the word (0, or 1 for a slice's second) of parameter o + arrives in, or -1 if it comes on the stack or in an xmm register *) +proc arrivesIn(o: ^Sym.Obj; word: INT): INT; +var i, r: INT; +begin + r := -1; + for i := 0 to numIn - 1 do + if (inObj[i] = o) and (inSlot[i] = o^.val + I64(8 * word)) and (inReg[i] >= 0) then r := inReg[i]; end; + end; + return r; +end; + +(* Parameter o, of a procedure that calls nothing, stays in the register + it arrives in if that is rdi or rsi, which only a call or a copy needs: + no register is saved for it, and nothing is moved. A slice stays only + if it has both. If the procedure turns out to copy after all, lost is + set, and it is compiled again with o in memory. *) +proc keepArrived*(o: ^Sym.Obj); +var r: INT; +begin + r := arrivesIn(o, 0); + if o^.typ^.form = Sym.fSlice then + if (r = RDI) and (arrivesIn(o, 1) = RSI) then o^.reg := RDI; o^.reg2 := RSI; end; + elsif (r = RDI) or (r = RSI) then o^.reg := r; end; +end; + +(* Whether parameter o is kept where it arrived *) +proc keptIn*(o: ^Sym.Obj): BOOL; +begin + return (o^.reg = RDI) or (o^.reg = RSI); +end; + +(* The locals in memory have their slots: the prologue zeroes those and + nothing below. The procedure keeps variables in the registers of + mask, which are saved next, a quadword each, in slots that need no + zeroing; the frame as it then stands is where a second try at the + body starts. *) +proc useRegs*(mask: INT); +var i, k: INT; p: ^Sym.Obj; +begin + zeroTop := permTop; + regMask := mask; + (* the parameters left in rdi and rsi, as they arrived *) + kept := 0; + p := procParams; + while p # nil do + if ((p^.reg = RDI) or (p^.reg = RSI)) then kept := kept | (1 shl p^.reg); end; + if ((p^.reg2 = RDI) or (p^.reg2 = RSI)) then kept := kept | (1 shl p^.reg2); end; + p := p^.next; + end; + k := 0; + for i := 0 to 4 do + if (mask & (1 shl i)) # 0 then INC(k); end; + end; + if k > 0 then saveAt := allocPerm(8 * k, 8); end; + frameAt[0] := frameTop; frameAt[1] := frameMax; frameAt[2] := permTop; +end; + +(* The variable in xmm register r of XVarRegs has a slot of 8 bytes at + slot, kept as it changes *) +proc xHome*(r: INT; slot: I64); +begin + homes[xIndex(r)] := slot; +end; + +proc markCode*(var m: CodeMark); +begin + m.pc := Chunk.pc; m.fixups := Chunk.numFixups; m.lines := Chunk.numLines; m.said := X.saidCount(); + m.fails := numFails; m.exit := exitL; +end; + +(* The code made since m taken back, as if it had never been made; the + frame is left as it is *) +proc rewind*(m: CodeMark); +begin + Chunk.rewindTo(m.pc, m.fixups, m.lines); + X.unsay(m.said); + numFails := m.fails; + exitL := m.exit; (* a try or return in it made jumps to the exit *) +end; + +(* For a second try at the body: the code as it was at m, and the frame + as useRegs found it *) +proc redo*(m: CodeMark); +begin + Chunk.rewindTo(m.pc, m.fixups, m.lines); + X.unsay(m.said); + numFails := 0; + lost := false; + frameTop := frameAt[0]; frameMax := frameAt[1]; permTop := frameAt[2]; + exitL := NoLabel; +end; + +(* The prologue, which is for the procedure's first line. Only the + locals in memory are zeroed, from the parameters' slots down to + zeroTop: the parameters are stored over their slots next, the + registers of variables are zeroed in place, their save slots are + written before they are read, and so is every temporary. *) +proc enterBody*(c, line: INT); +var i, loop, r: INT; n: I64; p: ^Sym.Obj; +begin + Chunk.beginChunk(c); + codeChunk := c; + Chunk.noteLine(line, 1); (* a declaration starts a line *) + X.push(RBP); + X.movRR(RBP, RSP); + X.say("sub rsp, frame"); + (* sub rsp, imm32: always the form with a 32-bit field, so that endProc + can patch the frame's size in *) + Chunk.put1(48H); Chunk.put1(81H); Chunk.put1(0ECH); + frameFix := Chunk.pc; Chunk.put4(0); + n := (Sym.alignUp(zeroTop, 8) - paramTop) div 8; + if n = 1 then + X.movRI(RAX, 0); + X.store(X.mem(RBP, -paramTop - 8), RAX, 8); + elsif n > 1 then + (* the locals, 16 bytes at a time, from xmm8, which holds nothing + yet (xmm0 to xmm7 may hold a parameter): up to 16 stores in a + row, else a loop with r10 running from minus the bytes up to 0, + the store's address scaled by 1. An odd quadword is the + lowest. *) + X.pxorXX(8); + if n <= 32 then + for i := 0 to INT(n div 2) - 1 do + X.movdquMX(X.mem(RBP, -paramTop - 16 * I64(i + 1)), 8); + end; + else + X.movRI(R10, -16 * (n div 2)); + loop := Chunk.pc; + X.movdquMX(X.memIdx(RBP, R10, 1, -paramTop), 8); + X.aluI(X.aluAdd, R10, 16); + X.jccBack(X.ccNE, loop); + end; + if n mod 2 = 1 then + X.movRI(RAX, 0); + X.store(X.mem(RBP, -paramTop - 8 * n), RAX, 8); + end; + end; + (* each register that holds a variable is saved, for the caller, and + zeroed, as a variable starts at zero *) + Chunk.setSaves(c, regMask & ((1 shl XBit) - 1), INT(saveAt)); + n := 0; + for i := 0 to 4 do + if (regMask & (1 shl i)) # 0 then + X.store(X.mem(RBP, saveAt + 8 * n), VarRegs[i], 8); + X.movRI(VarRegs[i], 0); + INC(n); + end; + end; + (* and each xmm register that holds a variable, zeroed, as its slot + is: the caller keeps its own *) + for i := 0 to LEN(XVarRegs) - 1 do + if (regMask & (1 shl (XBit + i))) # 0 then + X.movRI(RAX, 0); + X.movqXR(XVarRegs[i] - XmmVar, RAX); + end; + end; + (* the parameters that came in registers, to their slots or, for a + register variable, to its register: a slice's second word, the one + for the slot 8 bytes into its own, to its length's *) + for i := 0 to numIn - 1 do + if inReg[i] < 0 then + X.movsMX(X.mem(RBP, inSlot[i]), -1 - inReg[i], false); + if inObj[i]^.reg # 0 then X.movX(inObj[i]^.reg - XmmVar, -1 - inReg[i]); end; + elsif (inObj[i] # nil) and (inObj[i]^.reg # 0) then + r := inObj[i]^.reg; + if inSlot[i] # inObj[i]^.val then r := inObj[i]^.reg2; end; + if r # inReg[i] then X.movRR(r, inReg[i]); end; (* else it is kept where it is *) + if inSize[i] < 8 then X.extend(r, inSize[i], inObj[i]^.typ^.signed); end; + else + X.store(X.mem(RBP, inSlot[i]), inReg[i], inSize[i]); + end; + end; + (* a register variable's parameter that came on the stack, above the + frame (val > 0), is loaded from there; one passed by its address + (ind: var, or const) holds the address, 8 bytes, whatever its type: + a var BOOL loaded as a byte was a bad pointer *) + p := procParams; + while p # nil do + if (p^.reg # 0) and (p^.val > 0) then + if p^.ind then + X.load(p^.reg, X.mem(RBP, p^.val), 8, false); + elsif p^.typ^.form = Sym.fReal then + X.movsXM(p^.reg - XmmVar, X.mem(RBP, p^.val), p^.typ^.size = 4); + elsif p^.typ^.form in {Sym.fInt, Sym.fBool, Sym.fEnum, Sym.fSet} then + X.load(p^.reg, X.mem(RBP, p^.val), INT(p^.typ^.size), p^.typ^.signed); + else + X.load(p^.reg, X.mem(RBP, p^.val), 8, false); + if p^.typ^.form = Sym.fSlice then X.load(p^.reg2, X.mem(RBP, p^.val + 8), 8, false); end; + end; + end; + p := p^.next; + end; +end; + +(* Pops one of several results, a value of size bytes, into its place + off bytes into the caller's, behind the hidden pointer. *) +(* The frame slot that holds the hidden result pointer *) +proc resultSlot*: I64; +begin + return retSlot; +end; + +proc resultTo*(off: I64; size: INT); +var r: INT; fl: BOOL; +begin + r := top(); + fl := isReal(depth - 1); + drop(); + X.load(RCX, X.mem(RBP, retSlot), 8, false); + if fl then X.movsMX(X.mem(RCX, off), r, size = 4); + else X.store(X.mem(RCX, off), r, size); end; +end; + +(* Pops an address, and copies size bytes from it to the result, off + bytes into it. *) +proc copyResult*(off, size: I64); +begin + clobberArgs(); + popTo(RSI); + X.load(RDI, X.mem(RBP, retSlot), 8, false); + if off # 0 then X.lea(RDI, X.mem(RDI, off)); end; + copyBytes(size); +end; + +(* return: the result, a value on top, goes in rax or xmm0; two words, + the two values on top, in rax and rdx; one behind the hidden pointer + goes back with that pointer in rax. *) +proc returnJump*; +begin + if resType # nil then + if Sym.behindPointer(resType) then + X.load(RAX, X.mem(RBP, retSlot), 8, false); + elsif Sym.inTwoRegs(resType) then + popTo(RDX); + popTo(RAX); + elsif resType^.form = Sym.fReal then + xValueTo(depth - 1, 0); + drop(); + else + popTo(RAX); + end; + end; + X.jmp(exitL); +end; + +(* The first of what try does where the error isn't nil (the report, 7.8): + the machine's stack made even, as the deferred statements about to be + run expect to find it. try can stand among the arguments of another + call, where quadwords have been pushed. Nothing is lost: the frame is + above rsp, and the code returns through the frame pointer. *) +proc tryAlign*; +begin + X.aluI(X.aluAnd, RSP, -16); +end; + +(* The procedure returns the error in register r, and a zero for each of + its other results; it isn't rax, rcx, rdx or rdi, which this uses. *) +proc returnError(r: INT); +var f: ^Sym.Obj; +begin + if Sym.behindPointer(resType) then + X.load(RDI, X.mem(RBP, retSlot), 8, false); + zeroBytes(resType^.size); + f := resType^.fields; + while f^.next # nil do f := f^.next; end; + X.load(RDX, X.mem(RBP, retSlot), 8, false); + X.store(X.mem(RDX, f^.val), r, 8); + X.load(RAX, X.mem(RBP, retSlot), 8, false); + elsif Sym.inTwoRegs(resType) then + X.movRR(RDX, r); + X.movRI(RAX, 0); + else + X.movRR(RAX, r); + end; + X.jmp(exitL); +end; + +(* The rest of it: the procedure returns the error in the frame slot, and + a zero for each of its other results. Only code is made: no entry of + the stack of values is touched, since the code that follows is the + code for an error that is nil, with the stack as it was. *) +proc tryReturn*(slot: I64); +begin + X.load(RSI, X.mem(RBP, slot), 8, false); + returnError(RSI); +end; + +(* try, with no deferred statement to run: the error on top is tested in + its register r, which is returned, and, if it isn't nil, returned from + the procedure by tryReturnFrom, so it needs no slot in the frame. *) +proc tryTest*(var ok: INT): INT; +var r: INT; +begin + r := loaded(depth - 1); + jumpIf(ok, false); + return r; +end; + +proc tryReturnFrom*(r: INT); +begin + returnError(r); +end; + +(* The end of the procedure in chunk c: the code that returns, and the + frame's size, known only now, patched into its prologue. If it is + open, running off its end, it returns zeros. *) +proc endProc*(c: INT; open: BOOL): ERROR; +var n: I64; i: INT; +begin + codeChunk := -1; + if (depth # 0) or (pushed # 0) then Diag.fatal("internal error: stack depth"); end; + if open then + if Sym.behindPointer(resType) then + X.load(RDI, X.mem(RBP, retSlot), 8, false); + X.movRI(RCX, resType^.size); + X.movRI(RAX, 0); + X.repStos(1); + X.load(RAX, X.mem(RBP, retSlot), 8, false); + else + X.movRI(RAX, 0); + if Sym.inTwoRegs(resType) then X.movRI(RDX, 0); end; + X.movqXR(0, RAX); + end; + else + X.dropJumpTo(exitL); + end; + X.fixLink(exitL); + n := 0; + for i := 0 to 4 do + if (regMask & (1 shl i)) # 0 then + X.load(VarRegs[i], X.mem(RBP, saveAt + 8 * n), 8, false); + INC(n); + end; + end; + X.leave(); + X.ret(); + endFails(); + n := Sym.alignUp(frameMax, 16); + if n < 16 then n := 16; end; + if n > 2147483647 then return Scan.mark("frame too big"); end; + Chunk.put4At(frameFix, INT(n)); + (* the listing's text for the sub, which starts 3 bytes (REX.W, opcode, + ModRM) before its immediate *) + if X.listing then X.restate(frameFix - 3, Diag.say("sub rsp, {}", [Fmt.int(INT(n))])); end; + Chunk.endChunk(c); + return nil; +end; + +(* A deferred statement is compiled where it stands, as a subroutine of + 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 what pushed was, and starts it, with the return address + pushed. The stack is empty where it is called, and where it begins. *) +proc deferBegin*(var L: INT): (INT, INT); +var saved: INT; +begin + X.jmp(L); + saved := pushed; + pushed := 1; + return Chunk.pc, saved; +end; + +proc deferEnd*(L, saved: INT); +begin + keepTemps(); + X.ret(); + X.fixLink(L); + pushed := saved; +end; + +proc runDefer*(at: INT); +begin + X.callBack(at); +end; + +(* The entry point, _start, and its chunk: it saves argc and argv, and + the address of the places for Rt; runs every used module's body, then + 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 the library what it needs of C: Rt C's exit, in cExit, and + Thread pthread_create and pthread_join. + + dynamic: the program uses C. first: the first module, whose chain + gives the order of the bodies. mainObj: the program's main procedure, or + nil. The first numCLinks of cLinks: C's symbols, each loaded from the + quadword the loader fills in and stored in a variable of the + library's, in a program that uses C. exitProc: the chunk of Rt's exit. The + first numLinks of links: the addresses Rt is given, of what the program + has: the places, and the profiler and calls; what it isn't given, + nothing reaches, and the linker leaves out. + + bare: raz -bare, a program for the bare machine, a kernel's, with + no Linux under it. Its entry point reads no argc and argv, which + only Linux leaves on the stack, so that ARGC() is 0; and runs no body + of Rt, whose system calls, to set the signals' handlers, would fault + there. A kernel's own module sets up what Rt's body would. *) +proc entryPoint*(dynamic, bare: BOOL; first: ^Sym.Module; mainObj: ^Sym.Obj; cLinks: []Link; numCLinks, exitProc: INT; links: []Link; numLinks: INT): INT; +var entry, start, i: INT; m: ^Sym.Module; +begin + entry := Chunk.newChunk(Chunk.secText, -1, internStr("_start")); + if dynamic then + start := Chunk.newChunk(Chunk.secText, -1, internStr("main")); + Chunk.beginChunk(entry); + (* at the start rdx holds rtld_fini, from the dynamic loader, and the + stack argc, then argv *) + X.movRI(X.RBP, 0); (* no frame above, where a trace stops *) + X.movRR(R9, RDX); (* rtld_fini, the sixth argument *) + X.pop(RSI); (* argc, the second *) + X.movRR(RDX, RSP); (* argv, the third *) + X.aluI(X.aluAnd, RSP, -16); + X.push(RAX); (* padding, so that the next push, the seventh *) + X.push(RSP); (* argument, stack_end, leaves rsp aligned *) + X.movRI(R8, 0); (* fini and init: none *) + X.movRI(RCX, 0); + X.lea(RDI, X.memRip(start, 0)); (* main, the first argument *) + X.callM(X.memRip(Chunk.externChunk(internStr("__libc_start_main")), 0)); + X.ud2(); (* it never returns *) + Chunk.endChunk(entry); + Chunk.beginChunk(start); + X.push(RBP); (* aligns the stack again *) + X.store(X.memRip(argcChunk, 0), RDI, 8); + X.store(X.memRip(argvChunk, 0), RSI, 8); + for i := 0 to numCLinks - 1 do + X.load(RAX, X.memRip(cLinks[i].chunk, 0), 8, false); + X.store(X.memRip(cLinks[i].into, 0), RAX, 8); + end; + elsif bare then + start := entry; + Chunk.beginChunk(entry); + else + start := entry; + Chunk.beginChunk(entry); + X.load(RAX, X.mem(RSP, 0), 8, false); + X.store(X.memRip(argcChunk, 0), RAX, 8); + X.lea(RAX, X.mem(RSP, 8)); + X.store(X.memRip(argvChunk, 0), RAX, 8); + end; + for i := 0 to numLinks - 1 do + X.lea(RAX, X.memRip(links[i].chunk, 0)); + X.store(X.memRip(links[i].into, 0), RAX, 8); + end; + m := first; + while m # nil do + if m^.used and (m^.body >= 0) and not (bare and (m^.name = internStr("Rt"))) then X.callChunk(m^.body); end; + m := m^.next; + end; + if mainObj # nil then X.callChunk(mainObj^.chunk); end; + if (mainObj # nil) and (mainObj^.typ^.base # nil) then X.movRR(RDI, RAX); else X.movRI(RDI, 0); end; + X.callChunk(exitProc); + X.ud2(); (* exit never returns: trap if it does *) + Chunk.endChunk(start); + (* Rt.fail, for the failures of each kind: the place is where the + 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. rdi and rsi + as the failing code had them go on the stack, as Rt.fail's last two + arguments, and a comes in rax (endFails). *) + for i := 0 to LEN(failStubs) - 1 do + if failStubs[i] >= 0 then + Chunk.beginChunk(failStubs[i]); + X.load(R8, X.mem(RSP, 0), 8, false); + X.aluI(X.aluSub, R8, 1); + X.aluI(X.aluAnd, RSP, -16); + X.push(RSI); + X.push(RDI); + X.movRR(RSI, RAX); + X.movRI(RDI, i); + X.callChunk(rtFail); + X.ud2(); + Chunk.endChunk(failStubs[i]); + end; + end; + return entry; +end; + +(* A code procedure: its instructions, read by the assembler (X64), + are the whole of chunk c *) +proc codeProc*(c: INT; constExpr: X.ConstFn; nameFn: X.NameFn): ERROR; +begin + Chunk.beginChunk(c); + try X.assemble(constExpr, nameFn); + Chunk.endChunk(c); + return nil; +end; + +(* Whether the code procedure in chunk c is a square root of xmm0 in + itself, then ret, as Math.sqrt is: + + sqrtsd xmm0, xmm0 F2 0F 51 C0 + ret C3 + + If so, its prefix and opcode, F251H (F351H for sqrtss), which a call of it does in place + on the value's own register (realInPlace); else 0. A call would spill + the stack's reals and reload the variables' xmm registers around it, + as System V keeps none through one, for an instruction of four bytes. *) +proc oneRealOp*(c: INT): INT; +var s: INT; +begin + s := Chunk.chunks[c].start; + if (Chunk.chunks[c].size # 5) or (Chunk.chunks[c].numFix # 0) then return 0; end; + if ((Chunk.text[s] # 0F2H) and (Chunk.text[s] # 0F3H)) or (Chunk.text[s + 1] # 0FH) + or (Chunk.text[s + 2] # 51H) or (Chunk.text[s + 3] # 0C0H) or (Chunk.text[s + 4] # 0C3H) then + return 0; + end; + return INT(Chunk.text[s]) * 256 + INT(Chunk.text[s + 2]); +end; + +(* The operation op, of oneRealOp, on the real on top, in its register: + Math.sqrt(d2) is sqrtsd xmm8, xmm8, with no call. *) +proc realInPlace*(op: INT); +var x: INT; +begin + x := top(); + X.sse(op & 0FFH, x, x, op shr 8 = 0F3H); +end; + +var i: INT; +begin + for i := 0 to LEN(failStubs) - 1 do failStubs[i] := -1; end; + inPlace := -1; + codeChunk := -1; + resetStack(0, 0); + rtFail := Chunk.newChunk(Chunk.secText, internStr("Rt"), internStr("fail")); + argcChunk := Chunk.newChunk(Chunk.secBss, -1, internStr("argc")); + Chunk.setBss(argcChunk, 8, 8); + argvChunk := Chunk.newChunk(Chunk.secBss, -1, internStr("argv")); + Chunk.setBss(argvChunk, 8, 8); +end Gen. diff --git a/src/Host.linux.raz b/src/Host.linux.raz new file mode 100644 index 0000000..3726c1c --- /dev/null +++ b/src/Host.linux.raz @@ -0,0 +1,103 @@ +(* Host: what the compiler asks of the system it runs on, beyond the + library. The host is the system running raz; the target, the one its + program will run on. This file is Linux's. + + Another host stages its own file in its place: copy src/ to a + directory, put that host's Host.raz there instead of this one, and + build the copy with the host's library (doc/compiler.md says how). + Raz and Exe import only this module for what follows, so a host + gives these five procedures and keeps every export: + + libraryDir where the standard library is, as a directory path + cLibrary which C library a program that uses C is linked + against by default, or none if the host can't make one + writeExecutable the file at path made to hold an executable + prepareRun the path raz run writes its program to, or an error + if this host can't run it; asked first, before any + source is read, so its error is the refusal + execute replaces the compiler with the program written there + + A host that can't run programs refuses in prepareRun and gives + execute any body; one that has no C gives cLibrary the value none. + Strings it returns must live until the compiler exits. + + Depends on: Sys and Files for Linux's services, Scan for memory that + lasts until exit, Diag and Fmt for paths. Leaves out: compiling and + the executable format, which are Parse and Exe's. *) +module Host; +import Sys, Files, Fmt, Diag, Scan; +import SYSTEM; + +type + CLib* = (none, glibc, musl); (* the C library to link against *) + +const + LoaderGlibc = "/lib64/ld-linux-x86-64.so.2"; + LoaderMusl = "/lib/ld-musl-x86_64.so.1"; + MemfdCreate = 319; (* the system calls raz run makes *) + MfdCloexec = 1; (* an ELF still executes: the kernel opens it first *) + Execve = 59; + Mode755 = 1EDH; (* rwxr-xr-x *) + CreateRun: ERROR = "can't create a memfd"; + +(* The directory of the library, ending in what the name of raz leaves, + "lib": the one beside raz as the system says (a link to raz is + followed), or, with no /proc, beside argument 0 as it was typed *) +proc libraryDir*: []const U8; +var path: []const U8; error, i: INT; +begin + path, error := Sys.readLink("/proc/self/exe"); + if error # 0 then path := Files.arg(0); end; + i := LEN(path); + while (i > 0) and (path[i - 1] # '/') do DEC(i); end; + if i = 0 then return "lib"; end; + return Diag.say("{}lib", [Fmt.str(path[0..i])]); +end; + +(* The C library a program that uses C is linked against when -libc + doesn't say: glibc, or musl only if the machine has musl's loader and + not glibc's, as Alpine has *) +proc cLibrary*: CLib; +begin + if (Sys.access(LoaderGlibc, {}) # 0) and (Sys.access(LoaderMusl, {}) = 0) then return musl; end; + return glibc; +end; + +(* The file at path made to hold data, an executable: written, then + given mode 755. False if either failed. *) +proc writeExecutable*(path, data: []const U8): BOOL; +begin + return Files.write(path, data) and (Sys.chmod(path, Mode755) >= 0); +end; + +(* s as a C string, in memory that is never freed *) +proc cstr(s: []const U8): ^U8; +var p: ^U8; +begin + p := Scan.grab(LEN(s) + 1); + if LEN(s) > 0 then COPY(p[0..LEN(s)], s); end; + p[LEN(s)] := 0; + return p; +end; + +(* The path raz run writes its program to: a memfd, a file that lives + only in memory. Its descriptor stays open until execute, whose + close-on-exec flag lets the kernel release it, or until the compiler + ends after an error. *) +proc prepareRun*: ([]const U8, ERROR); +var fd: INT; +begin + fd := SYSTEM.SYSCALL(MemfdCreate, cstr("raz"), MfdCloexec); + if fd < 0 then return "", CreateRun; end; + return Diag.say("/proc/self/fd/{}", [Fmt.int(fd)]), nil; +end; + +(* The program at path runs in the compiler's place, with the compiler's + arguments from number first on as its own, first as its argument 0, + and the environment. It returns only if that failed: minus the errno. *) +proc execute*(path: []const U8; first: INT): INT; +begin + return SYSTEM.SYSCALL(Execve, cstr(path), SYSTEM.ARGV() + first, SYSTEM.ARGV() + (Files.argCount() + 1)); +end; + +end Host. diff --git a/src/Host.raz b/src/Host.raz deleted file mode 100644 index 6d5cc66..0000000 --- a/src/Host.raz +++ /dev/null @@ -1,103 +0,0 @@ -(* Host: what the compiler asks of the system it runs on, beyond the - library. The host is the system running raz; the target, the one its - program will run on. This file is Linux's. - - Another host stages its own file in its place: copy src/ to a - directory, put that host's Host.raz there instead of this one, and - build the copy with the host's library (doc/compiler.md says how). - Raz and Elf import only this module for what follows, so a host - gives these five procedures and keeps every export: - - libraryDir where the standard library is, as a directory path - cLibrary which C library a program that uses C is linked - against by default, or none if the host can't make one - writeExecutable the file at path made to hold an executable - prepareRun the path raz run writes its program to, or an error - if this host can't run it; asked first, before any - source is read, so its error is the refusal - execute replaces the compiler with the program written there - - A host that can't run programs refuses in prepareRun and gives - execute any body; one that has no C gives cLibrary the value none. - Strings it returns must live until the compiler exits. - - Depends on: Sys and Files for Linux's services, Scan for memory that - lasts until exit, Diag and Fmt for paths. Leaves out: compiling and - the ELF format, which are Parse and Elf's. *) -module Host; -import Sys, Files, Fmt, Diag, Scan; -import SYSTEM; - -type - CLib* = (none, glibc, musl); (* the C library to link against *) - -const - LoaderGlibc = "/lib64/ld-linux-x86-64.so.2"; - LoaderMusl = "/lib/ld-musl-x86_64.so.1"; - MemfdCreate = 319; (* the system calls raz run makes *) - MfdCloexec = 1; (* an ELF still executes: the kernel opens it first *) - Execve = 59; - Mode755 = 1EDH; (* rwxr-xr-x *) - CreateRun: ERROR = "can't create a memfd"; - -(* The directory of the library, ending in what the name of raz leaves, - "lib": the one beside raz as the system says (a link to raz is - followed), or, with no /proc, beside argument 0 as it was typed *) -proc libraryDir*: []const U8; -var path: []const U8; error, i: INT; -begin - path, error := Sys.readLink("/proc/self/exe"); - if error # 0 then path := Files.arg(0); end; - i := LEN(path); - while (i > 0) and (path[i - 1] # '/') do DEC(i); end; - if i = 0 then return "lib"; end; - return Diag.say("{}lib", [Fmt.str(path[0..i])]); -end; - -(* The C library a program that uses C is linked against when -libc - doesn't say: glibc, or musl only if the machine has musl's loader and - not glibc's, as Alpine has *) -proc cLibrary*: CLib; -begin - if (Sys.access(LoaderGlibc, {}) # 0) and (Sys.access(LoaderMusl, {}) = 0) then return musl; end; - return glibc; -end; - -(* The file at path made to hold data, an executable: written, then - given mode 755. False if either failed. *) -proc writeExecutable*(path, data: []const U8): BOOL; -begin - return Files.write(path, data) and (Sys.chmod(path, Mode755) >= 0); -end; - -(* s as a C string, in memory that is never freed *) -proc cstr(s: []const U8): ^U8; -var p: ^U8; -begin - p := Scan.grab(LEN(s) + 1); - if LEN(s) > 0 then COPY(p[0..LEN(s)], s); end; - p[LEN(s)] := 0; - return p; -end; - -(* The path raz run writes its program to: a memfd, a file that lives - only in memory. Its descriptor stays open until execute, whose - close-on-exec flag lets the kernel release it, or until the compiler - ends after an error. *) -proc prepareRun*: ([]const U8, ERROR); -var fd: INT; -begin - fd := SYSTEM.SYSCALL(MemfdCreate, cstr("raz"), MfdCloexec); - if fd < 0 then return "", CreateRun; end; - return Diag.say("/proc/self/fd/{}", [Fmt.int(fd)]), nil; -end; - -(* The program at path runs in the compiler's place, with the compiler's - arguments from number first on as its own, first as its argument 0, - and the environment. It returns only if that failed: minus the errno. *) -proc execute*(path: []const U8; first: INT): INT; -begin - return SYSTEM.SYSCALL(Execve, cstr(path), SYSTEM.ARGV() + first, SYSTEM.ARGV() + (Files.argCount() + 1)); -end; - -end Host. diff --git a/src/Link.raz b/src/Link.raz index 38170d7..e343c87 100644 --- a/src/Link.raz +++ b/src/Link.raz @@ -9,12 +9,12 @@ text right after the headers, rodata on the next page, then a writable page that starts with the table the dynamic loader reads (none in a static program) and goes on as bss, in memory only. The - loader's other tables come at the end of rodata; Elf writes them + loader's other tables come at the end of rodata; Exe writes them in the room left there. Depends on: Chunk for chunks and fixups, Scan for names and memory, Diag for errors and paths. - Leaves out: the file format; that is Elf. *) + Leaves out: the file format; that is Exe. *) module Link; import Fmt, Diag, Scan, Chunk; import SYSTEM; diff --git a/src/Parse.raz b/src/Parse.raz index 14023d4..a38ffe5 100644 --- a/src/Parse.raz +++ b/src/Parse.raz @@ -82,7 +82,6 @@ MaxPending = 64; (* modules being compiled at once *) MaxFors = 256; (* for loops of a procedure whose limit may go in a register *) MaxNest = 256; (* statements, expressions and types nested; each level is a few recursive calls of the parser *) - Suffixes: [4][]const U8 = [".linux-x86_64", ".linux", ".x86_64", ""]; var libDir*, mainDir: []const U8; @@ -90,6 +89,7 @@ numInc*: INT; userDirs: [][]const U8; (* RAZ_PATH, or HOME/.raz/lib; set by the driver *) thisVersion: []const U8; (* the compiler's version; set by the driver *) + targetOs, targetArch: []const U8; (* the target's names, Exe.Os and Gen.Arch; set by the driver *) originNote: []const U8; (* for the module about to be opened, see libraryNote *) firstModule*, lastModule*: PModule; (* in the order they were finished *) @@ -174,6 +174,14 @@ userDirs := dirs; end; +(* The target's operating system and machine, as the suffixes of a + module's files say them: Exe.Os and Gen.Arch, which the driver gives *) +proc setTarget*(os, arch: []const U8); +begin + targetOs := os; + targetArch := arch; +end; + (* The driver's version of the compiler, which a library's note names *) proc setVersion*(v: []const U8); begin @@ -4715,11 +4723,19 @@ return libDir; end; -(* The file of module n in dir that suffix j says: Name.linux-x86_64.raz - for a file of this target alone, and so on to Name.raz *) +(* The file of module n in dir that suffix j says: Name.OS-ARCH.raz for + a file of this target alone (Name.linux-x86_64.raz, say), then + Name.OS.raz, Name.ARCH.raz, and Name.raz *) proc fileName(n, j: INT): []const U8; begin - return Diag.say("{}{}.raz", [Fmt.str(nameOf(n)), Fmt.str(Suffixes[j])]); + if j = 0 then + return Diag.say("{}.{}-{}.raz", [Fmt.str(nameOf(n)), Fmt.str(targetOs), Fmt.str(targetArch)]); + elsif j = 1 then + return Diag.say("{}.{}.raz", [Fmt.str(nameOf(n)), Fmt.str(targetOs)]); + elsif j = 2 then + return Diag.say("{}.{}.raz", [Fmt.str(nameOf(n)), Fmt.str(targetArch)]); + end; + return Diag.say("{}.raz", [Fmt.str(nameOf(n))]); end; proc moduleFile(n: INT): ([]const U8, []const U8, BOOL); diff --git a/src/README.md b/src/README.md index 5500839..21510a2 100644 --- a/src/README.md +++ b/src/README.md @@ -77,8 +77,8 @@ 32 bits and goes on, since an operand has nowhere to return an error to; the compile ends with the message shown. The listing's text is made by `Diag.say`, which keeps it, and only when `-S` asks for it. -- **`Link` and `Elf`.** What `raz.pas` set there has a setter each: - `Link.setPlaces`, `Elf.needLib`, `noLibs`, `setMainPath`, +- **`Link` and `Exe`.** What `raz.pas` set there has a setter each: + `Link.setPlaces`, `Exe.needLib`, `noLibs`, `setMainPath`, `setStripped` and `X64.setListing`. The file is written by `Files.write` and made executable by `Sys.chmod`, in place of one `open` with mode 755 (which the umask would trim). @@ -134,7 +134,7 @@ library beside it, it reads from `/proc/self/exe` as FPC's `ParamStr(0)` does: `Files.arg(0)` is what the shell was typed, and `./raz` made the library `./lib`, so the same program held other paths in its file. - `raz run` writes the memfd with `Elf.writeElf` and executes it with + `raz run` writes the memfd with `Exe.write` and executes it with the system call, `execve`, which `Sys` has no procedure for. The version is the module `Version`, which `check.sh` makes in `build/src/` from `build/version.inc`, as the seed's `{$I}` is. diff --git a/src/Raz.raz b/src/Raz.raz index 773c385..c9af392 100644 --- a/src/Raz.raz +++ b/src/Raz.raz @@ -34,7 +34,7 @@ Leaves out: the work itself; the other units compile, link and write, and this only reads the command line and runs them in order. *) module Raz; -import Sys, Out, Str, Version, Files, Host, Fmt, Diag, Scan, Sym, Chunk, X64, Gen, Parse, Link, Elf; +import Sys, Out, Str, Version, Files, Host, Fmt, Diag, Scan, Sym, Chunk, Gen, Parse, Link, Exe; import SYSTEM; const @@ -72,20 +72,20 @@ end; (* Whether the program uses C: if so, the libraries it needs go to - Elf, the C library first. *) + Exe, the C library first. *) proc usesC: BOOL; var m, st, c: ^Sym.Module; l: ^Sym.Lib; begin st := nil; c := nil; - Elf.noLibs(); - _ := Elf.needLib(internStr(Elf.libc)); + Exe.noLibs(); + _ := Exe.needLib(internStr(Exe.libc)); m := Parse.firstModule; while m # nil do if m^.used and m^.linkStatic then st := m; end; if m^.used and m^.usesC then c := m; end; l := m^.libs; while m^.used and (l # nil) do - if not Elf.needLib(l^.name) then Diag.fatal("more than 32 libraries"); end; + if not Exe.needLib(l^.name) then Diag.fatal("more than 32 libraries"); end; l := l^.next; end; m := m^.next; @@ -93,7 +93,7 @@ if (st # nil) and (c # nil) then Diag.fatal(Diag.say("{} says link static, but {} uses C", [Fmt.str(Scan.nameOf(st^.name)), Fmt.str(Scan.nameOf(c^.name))])); end; - if c = nil then Elf.noLibs(); end; + if c = nil then Exe.noLibs(); end; return c # nil; end; @@ -350,9 +350,9 @@ Diag.setWerror(true); elsif s = "-S" then listing := true; - X64.setListing(true); + Gen.setListing(true); elsif s = "-s" then - Elf.setStripped(true); + Exe.setStripped(true); elsif s = "-base" then INC(i); base, ok := address(Files.arg(i)); @@ -371,7 +371,7 @@ INC(i); s := Files.arg(i); if (s # "glibc") and (s # "musl") then Diag.fatal(say1("unknown C library {}: glibc or musl", s)); end; - Elf.setMusl(s = "musl"); + Exe.setMusl(s = "musl"); libcSaid := true; elsif (s = "-h") or (s = "--help") then usage(); @@ -400,8 +400,9 @@ outPath, err := Host.prepareRun(); if err # nil then Diag.fatal(MSG(err)); end; end; - if not libcSaid then Elf.setMusl(Host.cLibrary() = Host.musl); end; + if not libcSaid then Exe.setMusl(Host.cLibrary() = Host.musl); end; Parse.setVersion(Version.Text); + Parse.setTarget(Exe.Os, Gen.Arch); if LEN(libDir) = 0 then libDir := Host.libraryDir(); end; Parse.setLibDir(libDir); userLibraries(); @@ -446,7 +447,7 @@ -noprofile no profiler, and -bare no profiler, since Rt's body, which starts it, doesn't run. *) numLinks := 0; - if not Elf.stripped then giveRtPlaces(rt, not noProfile and not bare); end; + if not Exe.stripped then giveRtPlaces(rt, not noProfile and not bare); end; (* what a program that uses C is given of C: Rt its exit, and Thread, if the program has it, the calls that make and join C's threads, so that the C library knows of them *) @@ -475,17 +476,17 @@ end; if Diag.errors > 0 then Diag.finish(); end; if listing then - X64.list(m^.sname); + Gen.list(m^.sname); return 0; end; - Elf.setMainPath(path); + Exe.setMainPath(path); if run then - Elf.writeElf(outPath, entry); + Exe.write(outPath, entry); _ := Host.execute(outPath, first); (* the program's argv is ours from Main.raz on *) Diag.fatal(say1("can't run {}", path)); end; - Elf.writeElf(outPath, entry); + Exe.write(outPath, entry); return 0; end; diff --git a/src/cross.sh b/src/cross.sh new file mode 100755 index 0000000..65328ff --- /dev/null +++ b/src/cross.sh @@ -0,0 +1,59 @@ +#!/bin/sh +# A compiler that runs here and compiles for TARGET (OS-ARCH, as +# darwin-arm64 or linux-x86_64): raz built by staging, for the target +# is whatever files the compiler was built from (doc/raz.md, 3). +# +# src/cross.sh TARGET [OUT] run from the repository root +# +# Stage build/cross/TARGET/src/ holds src/'s generic files and, under +# the plain names, the target's own: Gen.ARCH.raz as Gen.raz and +# Exe.OS.raz as Exe.raz; and the host's, Host.OS.raz as Host.raz, the +# host being the system the compiler will run on, which is this one. +# With only plain names there, module lookup has one choice each. BOOT's +# release builds the stage as the Makefile builds raz, from a directory +# where src/Raz.raz is again at src/, so the paths a program holds are +# the same. The compiler is OUT, build/cross/TARGET/raz if not said; +# its library is lib/, beside it. +set -e +target=$1 +out=${2:-build/cross/$target/raz} +case $target in +*-*) ;; +*) echo "usage: src/cross.sh OS-ARCH [OUT]" >&2; exit 2;; +esac +os=${target%%-*} +arch=${target#*-} +host=$(uname -s | tr A-Z a-z) # the OS that runs the compiler + +# Each unit with files by target, and the file this build takes of it +missing= +for f in Gen.$arch.raz Exe.$os.raz Host.$host.raz; do + [ -f src/$f ] || missing="$missing src/$f" +done +if [ -n "$missing" ]; then + echo "cross.sh: no files for $target (host $host):$missing" >&2 + exit 1 +fi +[ -f build/src/Version.raz ] || make build/src/Version.raz +[ -x build/boot/raz ] || make build/boot/raz + +d=build/cross/$target +rm -rf $d +mkdir -p $d/src $d/v +for f in src/*.raz; do + case $f in + *.*.raz) ;; # a target's file, below + *) cp $f $d/src/;; + esac +done +cp src/Gen.$arch.raz $d/src/Gen.raz +cp src/Exe.$os.raz $d/src/Exe.raz +cp src/Host.$host.raz $d/src/Host.raz +cp build/src/Version.raz $d/v/ +ln -s ../../../lib $d/lib +boot=$PWD/build/boot/raz +(cd $d && $boot -Werror -I src -I v -o raz src/Raz.raz) +case $out in +build/cross/$target/raz) ;; +*) cp $d/raz "$out";; +esac diff --git a/test/compiler-host.sh b/test/compiler-host.sh index 136c17b..44c05f9 100755 --- a/test/compiler-host.sh +++ b/test/compiler-host.sh @@ -1,6 +1,6 @@ #!/bin/sh # Builds the compiler with another host, test/host/Host.raz in place of -# src/Host.raz (the staging doc/compiler.md describes), and checks what +# src/Host.linux.raz (the staging doc/compiler.md describes), and checks what # that host changes: the library it names, a refused raz run, no C, and # a refused write. # Usage: test/compiler-host.sh path/to/raz @@ -30,6 +30,8 @@ # The staged sources and the compiler built from them. mkdir "$top/src" "$top/work" cp src/*.raz "$top/src" +# staged as src/cross.sh does: the plain name takes the place of Linux's +rm "$top/src/Host.linux.raz" cp test/host/Host.raz "$top/src/Host.raz" "$raz" -Werror -I "$top/src" -I build/src -o "$top/compiler" "$top/src/Raz.raz" 2>"$top/build.err" || { cat "$top/build.err"