From 848f0c57c9a7d9ae7eceeaa3054ec32eeb3d5e38 Mon Sep 17 00:00:00 2001 From: Luis <42945842+ldiaz94@users.noreply.github.com> Date: Mon, 12 Oct 2026 09:42:09 +0100 Subject: [PATCH] Step 7: the parser reaches the machine only through gen Three layers, none of the upper two knowing x86-64: - parse.pas: syntax; jumps and labels through gen. - item.pas (was gen.pas): Wirth's items, type checks, folding, where variables are (TAdr: frame, chunk, address on the stack, address in a slot); drives gen. - gen.pas (new): a stack machine for x86-64. PushConst/PushAdr/PushVar/ PushProc/PopVar, Op/Compare/Neg/Narrow/conversions with the kind of each value (word, long, F32, F64), JumpIf/JumpCmp/JumpKeep, checks, IndexSlice/Slice, Call, frames, defers, Atomic/SysCall/Fence, and the entry point (EntryPoint, from raz.pas). Top of stack in rax, the rest pushed; constants noted, not loaded, until needed. chunk.pas splits out of x64.pas: buffers, chunks, fixups, line notes. A port is a new gen.pas and encoder. All tests give the same output; bench 957k lines/s (was 1.25M). handtest and enctest call MarkLive, which WriteElf stopped doing in step 6: make tests had been failing since. --- diff --git a/Makefile b/Makefile index 9e238bb..21fd5e7 100644 --- a/Makefile +++ b/Makefile @@ -16,7 +16,7 @@ FORCE: units: src/*.pas | build - for u in diag scan sym x64 link elf; do $(FPC) $(FPCFLAGS) src/$$u.pas || exit 1; done + for u in diag scan sym chunk x64 link elf; do $(FPC) $(FPCFLAGS) src/$$u.pas || exit 1; done # tests of the parts below the parser, built from test/ tests: units diff --git a/PLAN.md b/PLAN.md index 14626fb..5df682d 100644 --- a/PLAN.md +++ b/PLAN.md @@ -55,7 +55,7 @@ - [x] 6. `examples/Sh.raz`: pipelines, redirection, `cd`, `&`, `wait`, and Ctrl-C to the job in the foreground, in a few hundred lines. Its test runs scripts given with `-c`. -- [ ] 7. rat, rlX11, rmacs and ravite on this raz, in their own +- [x] 7. rat, rlX11, rmacs and ravite on this raz, in their own repositories: the four copies of UTF-8 encoding go to `Str.encode`. - [x] 8. The freeze, in CLAUDE.md and the report's first section: the @@ -129,7 +129,7 @@ labels, no value in two, `else` required (7.4); compares and branches, no jump table. `examples/Sh.raz`'s chains of `elsif` become `match`. -- [ ] 7. The parser reaches the machine only through `gen`: calls of +- [x] 7. The parser reaches the machine only through `gen`: calls of a stack machine, with the kind of each value (a word, a 64-bit integer, an `F32`, an `F64`) and the place in the source, and no x86-64 in the parser; a port is a new `gen`. Every test gives diff --git a/doc/compiler.md b/doc/compiler.md index f183860..244d235 100644 --- a/doc/compiler.md +++ b/doc/compiler.md @@ -1,6 +1,6 @@ # Reading the raz compiler -The compiler is nine files of Free Pascal, under 6,500 lines of code. +The compiler is eleven files of Free Pascal, under 7,000 lines of code. This guide walks through them in the order they are best read: from the characters of a source file to the bytes of an executable. It assumes you know the language from `doc/raz.md`, and enough x86-64 to read a @@ -11,12 +11,14 @@ | `src/diag.pas` | 274 | 198 | Messages: positions, source excerpts, colour, counts | | `src/scan.pas` | 851 | 722 | Symbols, literals, comments, positions | | `src/sym.pas` | 596 | 497 | Types, objects, scopes, layout | -| `src/x64.pas` | 695 | 559 | Code buffer, chunks, fixups, places, instruction encoder | -| `src/gen.pas` | 1,750 | 1,493 | Items: loading, storing, copying, frames, calls | -| `src/parse.pas` | 2,468 | 2,222 | Declarations, statements, expressions, built-ins, recovery, warnings | +| `src/chunk.pas` | 244 | 192 | The compiled program: chunks, fixups, line notes | +| `src/x64.pas` | 476 | 377 | The instruction encoder, and jumps within a procedure | +| `src/gen.pas` | 1,206 | 963 | The stack machine, for x86-64: values, operations, checks, calls, frames | +| `src/item.pas` | 1,303 | 1,090 | Items: types, constants, variables, operators, conversions, calls | +| `src/parse.pas` | 2,538 | 2,276 | Declarations, statements, expressions, built-ins, recovery, warnings | | `src/link.pas` | 180 | 139 | Tree shaking, layout, patching, the places | | `src/elf.pas` | 424 | 351 | Static and dynamic ELF, symbol table, line numbers | -| `src/raz.pas` | 234 | 185 | The command line, the entry points | +| `src/raz.pas` | 188 | 141 | The command line | 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. @@ -28,16 +30,26 @@ is kept to be looked at again, except the declarations, which live in the symbol table for as long as the compiler runs. -The code generator is a stack machine through `rax`. An expression's -value is computed into `rax`; when a second operand has to be computed, -the first is pushed, and popped into `rax` when both are ready, the -second going to `rcx`; if the second needed no code of its own (a -constant, or a plain variable), the push is taken back instead. No -register is ever allocated, so there is no register allocator, and -every access the program writes is one instruction, in the order -written. That is also why `VOLATILE` costs the compiler nothing: it -never does anything clever to begin with. +Three layers do it. `parse.pas` knows the language's syntax. `item.pas` +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.pas`, 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.pas` is the only one that knows x86-64; a port to +another machine is a new `gen.pas`, with an encoder of its own in place +of `x64.pas`. +On x86-64 the stack machine's stack is the machine's: the value on +top is in `rax`, and the values under it are pushed when another is +computed; a constant is only noted, until something needs it in a +register, so that it can be an instruction's operand. No register is +ever allocated, so there is no register allocator, and every access +the program writes is one instruction, in the order written. That is +also why `VOLATILE` costs the compiler nothing: it never does anything +clever to begin with. + The output is a set of *chunks*: one for each procedure, each module variable, each string. Code refers to other chunks through *fixups*, which aren't resolved until the end. When everything is compiled, the @@ -64,9 +76,9 @@ 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.pas`, `Use` marks the modules the program uses; the - entry point, `_start`, is written 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`. + entry point, `_start`, is written by `gen.pas`'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.pas`) marks what `_start` reaches; then `WriteElf` (`elf.pas`) has `link.pas` place it and patch it, and writes headers, code, data, symbols and line numbers. @@ -89,8 +101,8 @@ mov QWORD PTR [rbp-0x8],rdi ; the parameters, into their slots mov QWORD PTR [rbp-0x10],rsi mov rax,QWORD PTR [rbp-0x8] ; a -push rax ; kept while b * 2 is computed -mov rax,QWORD PTR [rbp-0x10] ; b, its push taken back for the 2 +push rax ; kept while b is loaded +mov rax,QWORD PTR [rbp-0x10] ; b; the 2 is only noted shl rax,0x1 ; times 2 is a shift mov rcx,rax pop rax ; a again @@ -102,9 +114,10 @@ ret ``` -Every line of it can be traced to a routine in `gen.pas`; the pushes -and pops are `Op1` and `Op2`, the frame `EnterBody` and `EndProc`. It -is not fast code. It is code whose every instruction you can account +Every line of it can be traced to a routine in `gen.pas`; the push is +`Spill`'s, as `PushVar` loads `b`, the pop `PopTo`'s, as `Op` takes +its operands, and the frame is `EnterBody`'s and `EndProc`'s. It is +not fast code. It is code whose every instruction you can account for, which is the point. ## diag.pas: messages @@ -197,50 +210,110 @@ for different targets agree. The universe, the basic types and built-in procedures, is set up in the unit's `initialization`. -## x64.pas: machine code +## chunk.pas: the compiled program Code is written into one growing buffer, `code`, with `pc` its length; -strings go to `rodata`. A chunk (`TChunk`) records its section, where -its bytes start, how many, and the fixups it makes. `BeginChunk` and -`EndChunk` bracket a procedure; `SetData` and `SetBss` make data -chunks. +strings and other constants go to `rodata`. A chunk (`TChunk`) records +its section, where its bytes start, how many, and the fixups it makes. +`BeginChunk` and `EndChunk` bracket a procedure; `SetData` and `SetBss` +make data chunks. A *fixup* (`TFixup`) is a 32-bit field in the code that will hold the distance to another chunk: a call's target, or a rip-relative address. -`AddFixup` records one; `link.pas` fills them in. +`AddFixup` records one; `link.pas` fills them in. `NoteLine` records +which line and column of the source the code from `pc` on belongs to, +for gdb and for the places. `ExternChunk` makes, once per C symbol, +the quadword the dynamic loader will fill with that symbol's address. +None of this depends on the machine. -Jumps within a procedure don't wait for the linker. A label not yet -placed is a chain of the jumps to it, each jump's 32-bit field holding -the position of the one before (`Jmp`, `Jcc`); `FixLink` walks the -chain and patches each once the label's position is known. This is the -trick from Wirth's compilers, and it means a label is one integer. +## x64.pas: machine code The encoder is `OpM` and `OpR`: a prefix, the REX byte, the opcode, the ModRM and SIB bytes and the displacement, for a register and a memory operand (`TMem`) or two registers. Everything else (`MovRR`, `Load`, `Store`, `Alu`, `Sse`, ...) is a line or two that calls them with the right opcode. Only the instructions the code generator uses are here. -`test/enctest.pas` emits one of each for `objdump` to check. +`test/enctest.pas` emits one of each for `objdump` to check. `Here` is +the address of the code being written, as an operand. -Two more things live here because they are tied to code positions: -`NoteLine` records which line and column of the source the code from -`pc` on belongs to, for gdb and for the places; `Here` is the address -of the code being written, as an operand. `ExternChunk` makes, once per C symbol, the quadword the -dynamic loader will fill with that symbol's address. +Jumps within a procedure don't wait for the linker. A label not yet +placed is a chain of the jumps to it, each jump's 32-bit field holding +the position of the one before (`Jmp`, `Jcc`); `FixLink` walks the +chain and patches each once the label's position is known. This is the +trick from Wirth's compilers, and it means a label is one integer. + +## gen.pas: the stack machine + +This is the only unit that knows the machine. The calls it answers: + +- values: `PushConst`, `PushAdr` (the address of a variable), + `PushVar` (its value), `PushProc`, and `PopVar`, which stores the + value on top; `Drop` and `Swap`; +- operations on the values on top: `Op`, `Compare`, `Neg`, + `Complement`, `NotBool`, `Narrow` (to a narrow integer's width), + the conversions between integers and reals, `CompareSeq` (of two + slices), and copying: `CopyBlock`, `CopyTo`, `ZeroVar`; +- jumps: `Jump`, `JumpIf` (on a `BOOL`), `JumpCmp` (on two integers), + `JumpKeep` and `FixKeep` for `and` and `or`, `Fix` where the label + is; +- checks: `CheckIndex`, `CheckEnum`, and `IndexSlice`, `Slice` and + `SlicePtr`, which check as they make their address or slice; +- calls (`Call`), frames (`BeginProc`, `EnterBody`, `ReturnJump`, + `EndProc`, the temporaries of `AllocTemp`), deferred statements + (`DeferBegin`, `DeferEnd`, `RunDefer`), the built-ins that are + instructions (`Atomic`, `SysCall`, `Fence`), and the program's entry + point (`EntryPoint`). -## gen.pas: the code generator +A variable's place is a `TAdr`: relative to the frame (`bFrame`), to a +chunk (`bGlobal`), to an address on the stack (`bStack`), or to one +held in a frame slot (`bSlot`, as a `var` parameter's is); plus `off`. +`Place` turns it into an x64 memory operand, popping or loading the +address first, so that a variable is read or written with one +instruction. -This is the heart, and the file to read slowly. +The stack: `stack` notes each value, a constant or one computed; +`inRax` is the one in `rax`, if any. `Computed` puts a value just +computed in `rax` on top; `Spill` pushes the one in `rax` first, when +`rax` is wanted for another; `PopTo` brings the value on top into a +register, from the constant, from `rax` or by a pop. `pushed` counts +what is on the machine's stack, which a call must align. `Op` takes a +constant on the right as it is, and a power of two on the right of +`*`, `div` or `mod` becomes shifts (`DivPow2`), since `idiv` is slow. +Narrow integers are brought back to their width after each operation, +which is how `U8` arithmetic wraps; since they are computed in 64 bits, +a shift's count is cut to their width first, and `DivTrap` makes the +smallest value of one divided by -1 fault as an `I64`'s does. +Checks: `Check` jumps over a call to `Rt.fail` when the check holds. +The call passes what failed, the values involved and its own address, +by which `Rt` finds the place; that code has the place of the +offending expression (`LineCol` in `scan.pas`), and the code after it +the statement's again. + +Calls: the arguments are in frame slots by the time `Call` runs, one +each, computed left to right; only then are they loaded into the +registers System V wants, and the stack aligned for the call. A record +passed by value goes as the address of a copy; one returned comes back +through a hidden pointer in `rdi`, as C's structs do, and so do several +results (`ResultTo`, `CopyResult`). + +Frames: `BeginProc` gives the parameters their slots; `EnterBody` +writes the prologue, which zeroes the locals (with a few stores, or a +loop for more; there are none to zero in `scale`) but not the +temporaries, since each is written before it is read; `EndProc` writes +the epilogue and patches the frame's size in. Within a statement, +scratch space comes from `AllocTemp` and is given back by +`ReleaseTemps`; `AllocPerm` reserves space for the whole procedure. + +## item.pas: items + An operand is an *item* (`TItem`), as in Wirth's compilers. Its `mode` says what it is now: - `mConst`: a value known to the compiler, in `val`; -- `mVar`: a variable at an address the code can name: relative to - `rbp` (`bFrame`), to a chunk (`bGlobal`), to a register (`bReg`), to - an address pushed on the stack (`bStack`), or kept in a frame slot - (`bSlot`); plus `off`; -- `mReg`: a value in `rax`; `mStack`: a value pushed on the stack; +- `mVar`: a variable, at `base`, `chunk` and `off`, which `AdrOf` + makes a `TAdr` for gen; +- `mStack`: a value on gen's stack; - `mProc`, `mType`, `mStr`, and a few more the parser needs. An item also carries `pos`, the stretch of source it came from, which @@ -250,99 +323,74 @@ message: a constant without a type of its own as it is written (`found 1.5`), anything else by its type. -Three routines move items towards the machine. `Value` brings a value -into `rax`, loading it with the one instruction its size needs. -`Address` brings a variable's address into a register. `Save` pushes -whatever an item has in a register, so that another expression can be -computed; the item remembers that it's on the stack. Read these three, -then `MemOf`, which turns an `mVar` into an x64 memory operand, popping -its address first if it was pushed. +Two routines move items towards the machine: `Value` pushes an item's +value, and `Address` a variable's address. Both leave the item saying +it is on the stack. An item nothing more is done with is given back to +`Discard`. Expressions: `Op1` is called when the parser has seen an operator and -its left operand, `Op2` when it has the right one. `Op1` saves the left -operand (or, for `and` and `or`, emits the test that skips the right -one). `Op2` checks the types, folds constants (`FoldInt`, `FoldReal`), -and otherwise puts the left operand in `rax`, the right in `rcx`, and -emits the operation. When the left was the last thing pushed and the -right needs no code (a constant, or a variable on the frame or in a -chunk), `Unpush` takes the push back, and the right goes straight to -`rcx`; not if a jump or a line starts after the push. A power of two -on the right of `*`, `div` or `mod` becomes shifts (`DivPow2`), since -`idiv` is slow. Narrow integers are brought back to their width -after each operation (`Norm`), which is how `U8` arithmetic wraps. -Since they are computed in 64 bits, a shift's count is cut to their -width first, and `DivTrap` makes the smallest value of one divided by --1 fault as an `I64`'s does. -`=` and `#` on arrays, slices and strings make a slice of each side -(`SeqSlice`), compare the lengths, and then the bytes with `repe -cmpsb`, right where the comparison stands: no call. `+` on two string -constants is `JoinStr`, which makes one string of them, in a chunk of -its own. +its left operand, `Op2` when it has the right one. `Op1` pushes the +left operand, unless it is a constant (or, for `and` and `or`, has gen +jump past the right one). `Op2` checks the types, folds constants +(`FoldInt`, `FoldReal`), and otherwise pushes the right operand and has +gen do the operation; a constant on the left goes on after the right, +and the two `Swap`. A set's operations are operations on its bits +(`SetOp`). `=` and `#` on arrays, slices and strings make a slice of +each side (`SeqSlice`) and have gen compare them right where the +comparison stands: no call. `+` on two string constants is `JoinStr`, +which makes one string of them, in a chunk of its own. Variables: `Deref`, `Field`, `Index` and `Slice` turn an item for a variable into an item for part of it, mostly by adding to `off`. An item for another module's exported variable, or part of it, is `ro`: it isn't a variable (`isVar`), and `NotReadOnly` says why where one is -wanted; what it points at is. An array constant is a variable too, -in read-only data: `ArrayConst` (`parse.pas`) reads its literal into the +wanted; what it points at is. An array constant is a variable too, in +read-only data: `ArrayConst` (`parse.pas`) reads its literal into the bytes of a chunk, as a string constant's are, and `MakeItem` makes it an `mVar` there that isn't `isVar`, so it is read, indexed, sliced and -passed, never changed. -`Index` and `Slice` emit the bounds checks, unless the module says -`check off;` (`checks`, which `CompileFile` sets for each module), and -`Convert` the check of an enumeration's position; `Check` jumps over a call to `Rt.fail` when -the check holds. The call passes what failed, the values involved and -its own address, by which `Rt` finds the place; that code has the -place of the offending expression (`LineCol` in `scan.pas`), and the -code after it the statement's again. +passed, never changed. `Index` and `Slice` have gen make the bounds +checks, unless the module says `check off;` (`checks`, which +`CompileFile` sets for each module), and `Convert` the check of an +enumeration's position. Assignment and conversion: `Coerce` makes a value fit the type it's going to, or reports that it can't; it's where a string literal becomes a slice, an array a slice, an untyped constant a typed one, and an `INT` an `I64` (`Widens`). `CoerceExact` is for where the types must be the same, as in a `for` loop, `INC` and several results. `Assign` -stores, copying records and arrays with `rep movsb`. `Convert` is the -written conversion, `T(x)`. +stores, or copies records and arrays. `Convert` is the written +conversion, `T(x)`. -Calls: `BeginCall`, then `PassArg` for each argument, then `EndCall`. -Each argument is computed into a frame slot of its own, left to right; -only in `EndCall` are they loaded into the registers System V wants, -and the stack aligned for the call. A record passed by value goes as -the address of a copy; one returned comes back through a hidden pointer -in `rdi`, as C's structs do, and so do several results. `return -f(x);` passing on f's several results copies them, with `ReturnAll`, -from the call's temporary to the place its own hidden pointer names. - -Frames: `BeginProc` gives the parameters their slots; `EnterBody` -writes the prologue, which zeroes the locals (with a few stores, or a -loop for more; there are none to zero in `scale`) but not the -temporaries, since each is written before it is read; -`EndProc` writes the epilogue and patches the frame's size in. Within -a statement, scratch space comes from `AllocTemp` and is given back by -`ReleaseTemps`; `AllocPerm` reserves space for the whole procedure. +Calls: `BeginCall`, then `PassArg` for each argument, then `EndCall`, +which has gen's `Call` make the call. Each argument is computed into a +frame slot of its own. `return f(x);` passing on f's several results +copies them, with `ReturnAll`, from the call's temporary to the place +its own hidden pointer names. ## parse.pas: the parser A recursive descent parser, one routine for each rule of the grammar in -the report, calling `gen.pas` as it goes. +the report, calling `item.pas`, and for jumps `gen.pas`, as it goes. Start with expressions, bottom up: `Factor`, `Term`, `SimpleExpr`, `Relation`, `Conjunct` (the `and`s), `Expression` (the `or`s). Then `Designator`, which reads a name and what follows it: `.field`, `^`, `[i]`, `[lo..hi]`, a call, a conversion. Each step -calls the matching routine in `gen.pas` on the item it has. The +calls the matching routine in `item.pas` on the item it has. The `want` parameter carries the type an expression must have, where it is known, so that `[1, 2, 3]`, `{x: 1}` and `{red}` know what to build. Then statements: `Statement` makes each one a recovery point (below) and `OneStatement` dispatches; `IfStatement`, `WhileStatement`, `ForStatement` and `MatchStatement` emit their jumps -with `x64.pas`'s labels. A `match` on an integer reads each arm's +with gen's labels. A `match` on an integer reads each arm's labels in `IntArm`, which refuses a value in two of them, and tests them one after another with `MatchRange`: compares and branches, no jump table. `Defer` is worth reading: a deferred statement is compiled where it stands, as a little subroutine of the procedure -that the code jumps over, and `RunDefers` emits a call to it at every -way out of its statement list: the end, `return` and `break`. +that the code jumps over (gen's `DeferBegin` and `DeferEnd`), and +`RunDefers` emits a call to it at every way out of its statement list: +the end, `return` and `break`. A `return`'s result waits in the frame +meanwhile, so that gen's stack is empty when they run. Then declarations: `Declarations` reads `const`, `type`, `var`, `proc` and `extern`, each one through `Declaration`, a recovery point, which @@ -451,11 +499,12 @@ `raz.pas` parses the arguments, calls `CompileMain`, and works out what the program uses: `Use` marks the modules imported from the main module and `Rt`; `UsesC` decides whether the program is dynamic, refusing one -that both uses C and has a module saying `link static`. Then it writes -the entry point, and has `MarkLive` mark what it reaches. On a target +that both uses C and has a module saying `link static`. Then it has +gen's `EntryPoint` write the entry point, and `MarkLive` mark what it +reaches. On a target without reals (`HasReals`, beside `Target` in `parse.pas`; x86-64 has them), a live chunk that computes with one is an error at the first -place it does: `UsesReals` in `gen.pas` notes it, from `Value` and a +place it does: `UsesReals` in `item.pas` notes it, from `Value` and a real literal, on the chunk of the procedure being compiled. A real moved whole, as a record's bytes are, isn't noted. A static program starts at `_start` itself. A dynamic one starts at a `_start` that calls `__libc_start_main` the way C's own @@ -470,9 +519,12 @@ ## Where to start changing it - **A built-in procedure:** an entry in `sym.pas`'s universe, a case in - `Builtin` in `parse.pas`, and the code, in `gen.pas` or right there. + `Builtin` in `parse.pas`, and the code, in `gen.pas` if it is an + instruction, or of calls to gen right there. - **An instruction:** a routine in `x64.pas` built on `OpM` or `OpR`, and a line in `test/enctest.pas` to check its encoding. +- **A machine:** a new `gen.pas`, answering the same calls, and an + encoder for it in place of `x64.pas`. - **A statement:** a reserved word in `scan.pas` (in `TSym` and `Words`, in the same order), a case in `Statement`, and a routine beside the others. diff --git a/src/chunk.pas b/src/chunk.pas new file mode 100644 index 0000000..c0d0f46 --- /dev/null +++ b/src/chunk.pas @@ -0,0 +1,244 @@ +{ chunk.pas: the compiled program, before it is linked. + + The code of a program is a set of chunks: one per procedure, module + variable and string. A chunk's bytes go in one of three sections: + text (code), rodata (strings and other constants), bss (variables, + which are all zero). A reference from code to another chunk (a call, + or an address) is a fixup, patched once the linker has placed every + chunk. Line notes say which place in the source the code from each + point on is for. + + Nothing here depends on the machine: text is bytes, written by the + encoder for the target (x64.pas). + + Depends on: scan, for errors. + Leaves out: the instructions; that is x64.pas. } + +unit chunk; + +{$mode objfpc}{$H-} + +interface + +uses scan, diag; + +type + TSection = (secText, secRodata, secBss); + + TChunk = record + sec: TSection; + start, size, align: longint; { in its section's buffer } + firstFix, numFix: longint; { its fixups, text chunks only } + module, name: longint; { for the symbol table; -1 if none } + adr: int64; { its address, set by the linker } + live: boolean; { reached from the entry point } + ext: boolean; { bss: the address of a C symbol, its name } + reals: boolean; { code: computes with reals, first at realsAt } + realsAt: TPos; + end; + + { A place in the source whose code starts at a place in text: for + gdb, and for Rt to say where a failed check or a signal was } + TLine = record + at, chunk: longint; { the place in text, and its chunk } + path, line, col: longint; { the file's path, interned, the line and column } + end; + + TFixup = record + at: longint; { the 32-bit field, as an offset in text } + chunk: longint; { the chunk it refers to } + addend: longint; { added to the chunk's address } + end; + + PChunks = ^TChunkArray; + TChunkArray = array[0..MaxInt div SizeOf(TChunk) - 1] of TChunk; + PLines = ^TLineArray; + TLineArray = array[0..MaxInt div SizeOf(TLine) - 1] of TLine; + PFixups = ^TFixupArray; + TFixupArray = array[0..MaxInt div SizeOf(TFixup) - 1] of TFixup; + +var + code: PBytes; { text } + pc: longint; { its length } + rodata: PBytes; + rolen: longint; + chunks: PChunks; + numChunks: longint; + fixups: PFixups; + numFixups: longint; + lines: PLines; + numLines: longint; + curFile: longint; { the file being compiled, for NoteLine } + curChunk: longint; { the chunk of code being written } + +function NewChunk(sec: TSection; module, name: longint): longint; +procedure BeginChunk(c: longint); +procedure EndChunk(c: longint); +procedure SetData(c: longint; p: PBytes; n, align: longint); +procedure SetBss(c: longint; size, align: longint); +function ExternChunk(name: longint): longint; +procedure NoteLine(line, col: longint); +procedure AddFixup(at, chunk, addend: longint); + +procedure Put1(b: longint); +procedure Put4(v: longint); +procedure Put8(v: int64); +procedure Put4At(at, v: longint); +function Get4At(at: longint): longint; + +implementation + +var + codeCap, roCap, chunkCap, fixCap, lineCap: longint; + +procedure Room(n: longint); +begin + if pc + n > codeCap then begin + codeCap := codeCap * 2 + n; + code := ReAllocMem(code, codeCap); + end; +end; + +procedure Put1(b: longint); +begin + if pc + 16 > codeCap then Room(16); + code^[pc] := byte(b); + inc(pc); +end; + +procedure Put4(v: longint); +begin + if pc + 16 > codeCap then Room(16); + PLongint(@code^[pc])^ := v; + inc(pc, 4); +end; + +procedure Put4At(at, v: longint); +begin + PLongint(@code^[at])^ := v; +end; + +function Get4At(at: longint): longint; +begin + Get4At := PLongint(@code^[at])^; +end; + +procedure Put8(v: int64); +begin + Put4(longint(v and $FFFFFFFF)); + Put4(longint(v shr 32)); +end; + +function NewChunk(sec: TSection; module, name: longint): longint; +begin + if numChunks = chunkCap then begin + chunkCap := chunkCap * 2; + chunks := ReAllocMem(chunks, chunkCap * SizeOf(TChunk)); + end; + FillChar(chunks^[numChunks], SizeOf(TChunk), 0); + chunks^[numChunks].sec := sec; + chunks^[numChunks].module := module; + chunks^[numChunks].name := name; + chunks^[numChunks].align := 1; + chunks^[numChunks].size := -1; { not yet defined } + NewChunk := numChunks; + inc(numChunks); +end; + +procedure BeginChunk(c: longint); +begin + { code is aligned to 16 bytes, padded with CC, x86's int3: a trap if + it were ever run } + while pc and 15 <> 0 do Put1($CC); + curChunk := c; + chunks^[c].start := pc; + chunks^[c].align := 16; + chunks^[c].firstFix := numFixups; +end; + +procedure EndChunk(c: longint); +begin + chunks^[c].size := pc - chunks^[c].start; + chunks^[c].numFix := numFixups - chunks^[c].firstFix; +end; + +procedure SetData(c: longint; p: PBytes; n, align: longint); +begin + if rolen + n > roCap then begin + roCap := roCap * 2 + n; + rodata := ReAllocMem(rodata, roCap); + end; + Move(p^, rodata^[rolen], n); + chunks^[c].start := rolen; + chunks^[c].size := n; + chunks^[c].align := align; + inc(rolen, n); +end; + +procedure SetBss(c: longint; size, align: longint); +begin + chunks^[c].size := size; + chunks^[c].align := align; +end; + +{ The code from here on is for line and column of the current file. A + place with no code of its own gives way to the next. } +procedure NoteLine(line, col: longint); +begin + if (numLines > 0) and (lines^[numLines - 1].at = pc) then dec(numLines); + if (numLines > 0) and (lines^[numLines - 1].chunk = curChunk) and (lines^[numLines - 1].line = line) + and (lines^[numLines - 1].col = col) and (lines^[numLines - 1].path = curFile) then exit; + if numLines = lineCap then begin + lineCap := lineCap * 2; + lines := ReAllocMem(lines, lineCap * SizeOf(TLine)); + end; + lines^[numLines].at := pc; + lines^[numLines].chunk := curChunk; + lines^[numLines].path := curFile; + lines^[numLines].line := line; + lines^[numLines].col := col; + inc(numLines); +end; + +{ The quadword that holds the address of C's symbol name, filled in + when the program starts; one for each name. } +function ExternChunk(name: longint): longint; +var c: longint; +begin + for c := 0 to numChunks - 1 do + if chunks^[c].ext and (chunks^[c].name = name) then exit(c); + c := NewChunk(secBss, -1, name); + SetBss(c, 8, 8); + chunks^[c].ext := true; + ExternChunk := c; +end; + +procedure AddFixup(at, chunk, addend: longint); +begin + if numFixups = fixCap then begin + fixCap := fixCap * 2; + fixups := ReAllocMem(fixups, fixCap * SizeOf(TFixup)); + end; + fixups^[numFixups].at := at; + fixups^[numFixups].chunk := chunk; + fixups^[numFixups].addend := addend; + inc(numFixups); +end; + +initialization + codeCap := 1 shl 20; + code := GetMem(codeCap); + pc := 0; + roCap := 1 shl 16; + rodata := GetMem(roCap); + rolen := 0; + chunkCap := 1 shl 10; + chunks := GetMem(chunkCap * SizeOf(TChunk)); + numChunks := 0; + fixCap := 1 shl 12; + fixups := GetMem(fixCap * SizeOf(TFixup)); + numFixups := 0; + lineCap := 1 shl 12; + lines := GetMem(lineCap * SizeOf(TLine)); + numLines := 0; +end. diff --git a/src/elf.pas b/src/elf.pas index dea8fbc..a82d01b 100644 --- a/src/elf.pas +++ b/src/elf.pas @@ -13,7 +13,7 @@ (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, x64 for the chunks, + Depends on: link for the images and addresses, chunk for the chunks, scan for names and errors, BaseUnix to write the file. Leaves out: position independent executables, symbol versions, the rest of DWARF. } @@ -24,7 +24,7 @@ interface -uses scan, diag, x64, link; +uses scan, diag, chunk, link; var needed: array[0..31] of longint; { the libraries to load, names interned } diff --git a/src/gen.pas b/src/gen.pas index 6ae2c16..14cfbf9 100644 --- a/src/gen.pas +++ b/src/gen.pas @@ -1,25 +1,34 @@ -{ gen.pas: the code generator. +{ gen.pas: the code generator, for x86-64. - The parser describes each operand as an item (TItem), as in Wirth's - compilers: a constant, a variable at an address the code can name, a - value in rax, a value pushed on the stack, a procedure. The routines - here turn items into code. They are a stack machine through rax: a - value is computed into rax, and pushed while another is computed, so - no register is ever allocated. Every access the program writes is one - instruction, in the order written. + item.pas and parse.pas 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.pas, with an encoder of its own. + Here the stack is the machine's: the value on top, once computed, is + in rax, and the values under it are pushed when another is computed. + A constant is only noted until something needs it in a register, so + that it can be an instruction's operand. + Calls use the System V convention. Arguments are computed left to right into frame slots, then loaded into registers just before the call, so that computing one argument can't disturb another. A record, array, slice or variant passed by value goes as the address of a copy the caller makes; one returned goes through a hidden pointer, as C's - structs do. + structs do, and so do several results. A procedure's frame holds its parameters, its variables, and the - temporaries of the statement running. All of it is zeroed on entry. + temporaries of the statement running. The variables are zeroed on + entry. - Depends on: scan for errors, sym for types, x64 for instructions. - Leaves out: the language's syntax; that is parse.pas. } + 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.pas. } unit gen; @@ -27,98 +36,93 @@ interface -uses scan, diag, sym, x64; +uses scan, diag, sym, chunk, x64; + +const + NoLabel = -1; + WordSize = 8; { the size of an address, and of INT } type - TMode = (mConst, mVar, mReg, mStack, mProc, mType, mStr, mBuiltin, mCase, mNone); - TBase = (bFrame, bGlobal, bReg, bStack, bSlot); { bSlot: address in a frame slot, chunk } + TKind = (kWord, kLong, kF32, kF64); - TItem = record - mode: TMode; - typ: PType; - val: int64; { mConst: the value, an F64's bits; mStr: its length } - base: TBase; { mVar: what the address is relative to } - reg: longint; { mVar with bReg: the register } - off: int64; { mVar: added to the base } - chunk: longint; { mVar with bGlobal, mStr: the chunk } - vol: boolean; { mVar: reached through ^VOLATILE } - isVar: boolean; { mVar: a variable of the program, not a temporary } - odd: boolean; { mVar: in a packed record, so maybe misaligned } - ro: boolean; { mVar: another module's exported variable, or part - of one, which only that module changes } - obj: PObj; { mProc, mBuiltin, mCase } - pos: TPos; { where it is in the source, for messages } + { 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 } + TBase = (bFrame, bGlobal, bStack, bSlot); + TAdr = record + base: TBase; + chunk: longint; { bGlobal: the chunk; bSlot: the frame slot } + off: int64; { added to the address } end; TCall = record sig: PType; param: PObj; { the parameter the next argument is for } - slots: array[0..63] of int64; - n: longint; - target: int64; { the frame slot of a procedure value, if any } + obj: PObj; { the procedure called, if it has a name } + n: longint; { the arguments } + slots: array[0..63] of int64; { each one's frame slot } + isF: array[0..63] of boolean; { ... goes in an xmm register } + target: int64; { the frame slot of a procedure value, if chunk < 0 } chunk: longint; { else the procedure's chunk } - obj: PObj; { the procedure called, if it has a name } code: boolean; { a code procedure: two results come in rax and rdx } ext: boolean; { C's: called through the chunk holding its address } - isF: array[0..63] of boolean; { each argument: goes in an xmm register } + ret: int64; { set by Call: the temporary an aggregate result is in } end; var rtFail, argcChunk, argvChunk: longint; - depth: longint; { values pushed and not yet popped } - checks: boolean; { the module's index and slice checks are made: it - doesn't say check off } + depth: longint; { the values on the stack } + pushed: longint; { quadwords pushed on the machine's stack } + codeChunk: longint = -1; { the procedure or body being compiled, or -1 } -procedure MakeConst(var x: TItem; t: PType; v: int64); -function What(const x: TItem): shortstring; -procedure MakeReal(var x: TItem; r: double); -procedure MakeStr(var x: TItem); -procedure MakeItem(var x: TItem; o: PObj); -function RealOf(const x: TItem): double; +function KindOf(t: PType): TKind; -procedure UsesReals(const p: TPos); -procedure Value(var x: TItem); -procedure Address(var x: TItem; r: longint); -procedure Save(var x: TItem); -procedure Coerce(var x: TItem; t: PType); -procedure CoerceExact(var x: TItem; t: PType; const help: shortstring); -procedure NotReadOnly(const x: TItem); -procedure Assign(var dst, src: TItem); -procedure CopyToTemp(var x: TItem); -function ToSlot(var x: TItem): int64; +procedure PushConst(k: TKind; v: int64); +procedure PushAdr(const a: TAdr); +procedure PushVar(const a: TAdr; size: longint; signed: boolean; k: TKind); +procedure PushProc(c: longint; ext: boolean); +procedure PopVar(const a: TAdr; size: longint); +procedure Drop; +procedure Swap; +procedure ResetStack(d, p: longint); -procedure Deref(var x: TItem); -procedure Field(var x: TItem; f: PObj); -procedure IndexPrep(var x: TItem); -procedure Index(var x, y: TItem); -procedure SliceLo(var lo: TItem); -procedure Slice(var x, lo, hi: TItem); +procedure CopyBlock(size, off: int64); +procedure CopyTo(const a: TAdr; size: int64); +procedure ZeroVar(const a: TAdr; size: int64); -procedure Neg(var x: TItem); -procedure NotOp(var x: TItem); -procedure Complement(var x: TItem); -procedure Op1(op: TSym; var x: TItem; var L: longint); -procedure Op2(op: TSym; var x, y: TItem; L: longint); -function IsWord(t: PType): boolean; -procedure Convert(var x: TItem; t: PType); +procedure Op(op: TSym; k: TKind; size: longint; signed: boolean); +procedure Compare(op: TSym; k: TKind; signed: boolean); +procedure Neg(k: TKind; size: longint; signed: boolean); +procedure Complement(size: longint; signed: boolean); +procedure NotBool; +procedure Narrow(size: longint; signed: boolean); +procedure IntToReal(k: TKind; big: boolean); +procedure RealToInt(k: TKind); +procedure RealToReal(k: TKind); +procedure CompareSeq(a, b: int64; shift: longint; eq: boolean); +procedure ErrorText(tmp: int64); +procedure IncDec(size: longint; signed, dec: boolean); +procedure ZeroNew(size: int64); +procedure Atomic(which: longint); +procedure SysCall(n: longint); +procedure Fence; -procedure BeginCall(var c: TCall; var x: TItem); -procedure PassArg(var c: TCall; var a: TItem); -procedure EndCall(var c: TCall; var x: TItem); +procedure Jump(var L: longint); +procedure JumpIf(var L: longint; when: boolean); +procedure JumpKeep(var L: longint; when: boolean); +procedure FixKeep(L: longint); +procedure JumpCmp(op: TSym; signed: boolean; var L: longint); +procedure JumpBack(top: longint); +procedure Fix(L: longint); +procedure FixTo(L, top: longint); -procedure ZeroTemp(var x: TItem; t: PType); -procedure Construct(var x: TItem; c: PObj); -procedure SetField(const x: TItem; f: PObj; var a: TItem); -function MatchBegin(var x: TItem): int64; -procedure MatchTag(p: int64; tag: int64; var L: longint; isEnum: boolean); -procedure MatchRange(p, lo, hi: int64; var body: longint); -procedure CondJump(var x: TItem; var L: longint); +procedure CheckIndex(n: int64; const p: TPos); +procedure CheckEnum(n: int64; name: longint; const p: TPos); +procedure IndexSlice(const a: TAdr; size: int64; checked: boolean; const p: TPos); +procedure Slice(const a: TAdr; isArray: boolean; n, size, tmp: int64; checked: boolean; const p: TPos); +procedure SlicePtr(size, tmp: int64; checked: boolean; const p: TPos); + +procedure Call(var c: TCall); -procedure SliceOf(var x: TItem; t: PType; len: int64); -procedure TempItem(var x: TItem; t: PType; off: int64); -function ScalarSize(t: PType): longint; -procedure Norm(t: PType); -procedure ForNext(o: PObj; bslot, step: int64; var exitL: longint; top: longint); function AllocTemp(size, align: int64): int64; function AllocPerm(size, align: int64): int64; function TempMark: int64; @@ -127,31 +131,34 @@ procedure BeginProc(sig: PType; params: PObj); procedure EnterBody(c, line: longint); -procedure ReturnValue(var x: TItem); -procedure ReturnField(f: PObj; var x: TItem); -procedure ReturnAll(var x: TItem); +procedure ResultTo(off: int64; size: longint); +procedure CopyResult(off, size: int64); procedure ReturnJump; -procedure ReturnNone; -procedure Pin(var x: TItem); -procedure IncDec(var v, k: TItem; dec: boolean); -procedure Msg(var x: TItem); -function ErrorChunk(var x: TItem; module, name: longint): longint; procedure EndProc(c: longint); -procedure CmpI(r: longint; v: int64); -procedure PushRax; -procedure PopR(r: longint); +function DeferBegin(var L, saved: longint): longint; +procedure DeferEnd(L, saved: longint); +procedure RunDefer(at: longint); + +function EntryPoint(dynamic: boolean; first: PModule; main: PObj; cExit, places, placesVar, exitProc: longint): longint; implementation +type + TEntry = record + isConst: boolean; { not loaded: val is the value } + val: int64; + k: TKind; + end; + var + stack: array[0..255] of TEntry; + inRax: longint; { the entry whose value is in rax, or -1 } frameTop, frameMax, permTop: int64; frameFix: longint; { where the frame size is patched in } paramTop: int64; { the parameters' slots end here } retSlot: int64; { holds the hidden result pointer } - pushEnd: longint; { the code just after the last push of rax } - result: PType; { the procedure's result, or nil } + resType: PType; { the procedure's result, or nil } exitL: longint; - codeChunk: longint = -1; { the procedure or body being compiled, or -1 } { parameters arriving in registers: where each is stored on entry } inReg: array[0..13] of longint; inSlot: array[0..13] of int64; @@ -161,322 +168,166 @@ const IntRegs: array[0..5] of longint = (RDI, RSI, RDX, RCX, R8, R9); -{ Items } - -procedure MakeConst(var x: TItem; t: PType; v: int64); -var p: TPos; +function KindOf(t: PType): TKind; begin - p := x.pos; - FillChar(x, SizeOf(x), 0); - x.pos := p; - x.mode := mConst; - x.typ := t; - x.val := v; -end; - -{ A real constant: untyped, unless typed later. Its value is an F64, - which for an F32 is one an F32 can hold. } -procedure MakeReal(var x: TItem; r: double); -begin - MakeConst(x, tRConst, 0); - Move(r, x.val, 8); + if t^.form = fReal then begin + if t^.size = 4 then KindOf := kF32 else KindOf := kF64 + end else if t^.size > WordSize then KindOf := kLong + else KindOf := kWord; end; -function IsF32(t: PType): boolean; -begin - IsF32 := (t^.form = fReal) and (t^.size = 4); -end; +{ The stack } -{ Gives a real constant the real type t, rounded to it. } -procedure RealTo(var x: TItem; t: PType); -var r: double; +{ rax is wanted for a new value: the one in it is pushed } +procedure Spill; begin - r := RealOf(x); - if IsF32(t) then MakeReal(x, single(r)) else MakeReal(x, r); - x.typ := t; -end; - -function RealOf(const x: TItem): double; -var r: double; -begin - Move(x.val, r, 8); - RealOf := r; -end; - -{ The current string literal, as an item of its own chunk. } -procedure MakeStr(var x: TItem); -begin - FillChar(x, SizeOf(x), 0); - x.mode := mStr; - x.typ := tStr; - x.val := slen; - x.chunk := NewChunk(secRodata, -1, -1); - SetData(x.chunk, @sbuf, slen + 1, 1); -end; - -{ An item for "found ...": a constant without a type of its own as it - is written, so that "found 1.5" says what is wrong; else its type. } -function What(const x: TItem): shortstring; -begin - if (x.mode = mConst) and ((x.typ = tConst) or (x.typ = tRConst)) then What := Source(x.pos) - else What := TypeName(x.typ); -end; - -{ Two operands of different types. Numbers convert, so say how. } -procedure Mismatch(const x, y: TItem; xt, yt: PType); -var msg: shortstring; -begin - msg := TypeName(xt) + ' and ' + TypeName(yt) + ' are different types'; - if (IsInt(xt) or (xt^.form = fReal)) and (IsInt(yt) or (yt^.form = fReal)) - and (xt <> tConst) and (xt <> tRConst) then - MarkHelp(Join(x.pos, y.pos), msg, 'convert one to the other''s type, as in ' + TypeName(xt) + '(' + Source(y.pos) + ')') - else MarkAt(Join(x.pos, y.pos), msg); -end; - -{ An item that is not a value, by what it is. } -procedure NotValue(const x: TItem); -begin - case x.mode of - mType: MarkAt(x.pos, TypeName(x.typ) + ' is a type, not a value'); - mBuiltin: MarkAt(x.pos, NameOf(x.obj^.name) + ' is a built-in procedure, not a value'); - mCase: MarkAt(x.pos, NameOf(x.obj^.name) + ' is a case, not a value'); - mNone: - if x.obj <> nil then MarkAt(x.pos, NameOf(x.obj^.name) + ' returns nothing') - else MarkAt(x.pos, 'the procedure returns nothing'); - else MarkAt(x.pos, 'a string can''t be an operand'); + if inRax >= 0 then begin + Push(RAX); + inc(pushed); + inRax := -1; end; end; -procedure MakeItem(var x: TItem; o: PObj); +procedure NewEntry(k: TKind; isConst: boolean; v: int64); begin - FillChar(x, SizeOf(x), 0); - x.typ := o^.typ; - x.obj := o; - case o^.cls of - oConst: - if o^.typ = tStr then begin - x.mode := mStr; x.val := o^.val; x.chunk := o^.chunk - end else if o^.typ^.form = fArray then begin - { an array constant: a variable in read-only data, not one of - the program's, so nothing can change it } - x.mode := mVar; x.base := bGlobal; x.chunk := o^.chunk - end else begin - x.mode := mConst; x.val := o^.val - end; - oVar: begin - x.mode := mVar; - x.ro := (o^.lev = 0) and (o^.module <> curModule); - x.isVar := not x.ro; - if o^.ext then begin - Load(RAX, MemRip(o^.chunk, 0), 8, false); - x.base := bReg; x.reg := RAX; - end else if o^.lev = 0 then begin - x.base := bGlobal; x.chunk := o^.chunk - end else if o^.ind then begin - Load(RAX, Mem(RBP, o^.val), 8, false); - x.base := bReg; x.reg := RAX; x.off := o^.off; - end else begin - x.base := bFrame; x.off := o^.val - end; - end; - oProc: x.mode := mProc; - oType: x.mode := mType; - oBuiltin: x.mode := mBuiltin; - oCase: x.mode := mCase; - else Mark(NameOf(o^.name) + ' is not a value'); - end; + if depth > High(stack) then Mark('the expression is too deep'); + stack[depth].k := k; + stack[depth].isConst := isConst; + stack[depth].val := v; + inc(depth); end; -procedure PushRax; +{ The value just computed in rax goes on top } +procedure Computed(k: TKind); begin - Push(RAX); - inc(depth); - pushEnd := pc; + NewEntry(k, false, 0); + inRax := depth - 1; end; -procedure PopR(r: longint); +{ The value on top, popped into register r } +procedure PopTo(r: longint); +var e: TEntry; begin - Pop(r); + if depth = 0 then Fatal('internal error: the stack is empty'); dec(depth); -end; - -procedure CmpI(r: longint; v: int64); -begin - if (v >= low(longint)) and (v <= high(longint)) then AluI(aluCmp, r, v) - else begin MovRI(R11, v); Alu(aluCmp, r, R11) end; -end; - -{ A constant into r: an error constant is the address of its chunk. } -procedure ConstTo(r: longint; const x: TItem); -var f: single; -begin - if (x.typ^.form = fError) and (x.val > 0) then Lea(r, MemRip(x.val - 1, 0)) - else if IsF32(x.typ) then begin - f := RealOf(x); - MovRI(r, PLongword(@f)^); - end else MovRI(r, x.val); -end; - -function MemOf(var x: TItem; r: longint): TMem; -begin - case x.base of - bFrame: MemOf := Mem(RBP, x.off); - bGlobal: MemOf := MemRip(x.chunk, x.off); - bStack: begin - PopR(r); - x.base := bReg; x.reg := r; - MemOf := Mem(r, x.off); - end; - bSlot: begin - Load(r, Mem(RBP, x.chunk), 8, false); - x.base := bReg; x.reg := r; - MemOf := Mem(r, x.off); - end; - else MemOf := Mem(x.reg, x.off); + e := stack[depth]; + if e.isConst then begin + if r = RAX then Spill; + MovRI(r, e.val); + end else if inRax = depth then begin + if r <> RAX then MovRR(r, RAX); + inRax := -1; + end else begin + Pop(r); + dec(pushed); end; end; -function ScalarSize(t: PType): longint; +{ The value on top, into rax, and on top still } +procedure TopToRax; +var k: TKind; begin - if t^.form in [fInt, fBool, fEnum, fSet, fReal] then ScalarSize := t^.size - else ScalarSize := 8; + k := stack[depth - 1].k; + PopTo(RAX); + Computed(k); end; -{ Brings a value just computed in rax to its type's width. } -procedure Norm(t: PType); +procedure ResetStack(d, p: longint); begin - if (t^.form = fInt) and (t^.size < 8) then Extend(RAX, t^.size, t^.signed); + depth := d; + pushed := p; + inRax := -1; end; -function Cut(v: int64; t: PType): int64; +procedure PushConst(k: TKind; v: int64); begin - Cut := v; - if t^.form <> fInt then exit; - case t^.size of - 1: if t^.signed then Cut := shortint(v) else Cut := byte(v); - 2: if t^.signed then Cut := smallint(v) else Cut := word(v); - 4: if t^.signed then Cut := longint(v) else Cut := longword(v); - end; -end; - -procedure LoadVar(var x: TItem; r: longint); -begin - if not IsScalar(x.typ) then MarkAt(x.pos, 'expected a single value, found ' + What(x)); - Load(r, MemOf(x, r), ScalarSize(x.typ), (x.typ^.form = fInt) and x.typ^.signed); + NewEntry(k, true, v); end; -{ Takes back the push of rax just emitted, if it is the last code, and - neither a jump nor a line starts after it: the value is still in rax. } -function Unpush: boolean; +{ The memory a names: an address on the stack is popped into r, one in + a slot loaded into r } +function Place(const a: TAdr; r: longint): TMem; begin - Unpush := (pc = pushEnd) and (labelAt <> pc) - and ((numLines = 0) or (lines^[numLines - 1].at < pc)); - if Unpush then begin dec(pc); dec(depth); pushEnd := -1 end; -end; - -{ Code computing with a real is noted on its chunk, at the first place, - for a target without reals (report 5.1) to refuse if the chunk turns - out to be used. A real moved whole, as a record's bytes are copied, - needs nothing the target lacks, and isn't noted. } -procedure UsesReals(const p: TPos); -begin - if (codeChunk >= 0) and not chunks^[codeChunk].reals then begin - chunks^[codeChunk].reals := true; - chunks^[codeChunk].realsAt := p; + case a.base of + bFrame: Place := Mem(RBP, a.off); + bGlobal: Place := MemRip(a.chunk, a.off); + bStack: begin PopTo(r); Place := Mem(r, a.off) end; + else + if r = RAX then Spill; + Load(r, Mem(RBP, a.chunk), 8, false); + Place := Mem(r, a.off); end; end; -procedure Value(var x: TItem); -begin - if x.typ^.form = fReal then UsesReals(x.pos); - case x.mode of - mConst: ConstTo(RAX, x); - mVar: LoadVar(x, RAX); - mReg: ; - mStack: PopR(RAX); - mProc: begin - if x.obj^.isCode and (x.obj^.typ^.base <> nil) and x.obj^.typ^.base^.tuple then - MarkAt(x.pos, 'a code procedure with two results can only be called'); - if x.obj^.ext then Load(RAX, MemRip(x.obj^.chunk, 0), 8, false) - else Lea(RAX, MemRip(x.obj^.chunk, 0)); - end; - else NotValue(x); - end; - x.mode := mReg; -end; - -procedure Address(var x: TItem; r: longint); +procedure PushAdr(const a: TAdr); var m: TMem; begin - if x.mode = mStr then Lea(r, MemRip(x.chunk, 0)) - else if x.mode = mVar then begin - m := MemOf(x, r); - if (x.base <> bReg) or (x.reg <> r) or (x.off <> 0) then Lea(r, m); - x.base := bReg; x.reg := r; x.off := 0; - end else MarkAt(x.pos, 'expected a variable'); + if (a.base = bStack) and (a.off = 0) then exit; + m := Place(a, RAX); + Spill; + Lea(RAX, m); + Computed(kWord); end; -procedure Save(var x: TItem); +procedure PushVar(const a: TAdr; size: longint; signed: boolean; k: TKind); +var m: TMem; begin - if x.mode = mReg then begin - PushRax; x.mode := mStack - end else if (x.mode = mVar) and (x.base = bReg) then begin - if x.reg <> RAX then MovRR(RAX, x.reg); - PushRax; x.base := bStack; - end; + m := Place(a, RAX); + Spill; + Load(RAX, m, size, signed); + Computed(k); end; -{ Frames } - -function AllocTemp(size, align: int64): int64; +procedure PushProc(c: longint; ext: boolean); begin - if align < 1 then align := 1; - frameTop := AlignUp(frameTop + size, align); - if frameTop > frameMax then frameMax := frameTop; - AllocTemp := -frameTop; + Spill; + if ext then Load(RAX, MemRip(c, 0), 8, false) + else Lea(RAX, MemRip(c, 0)); + Computed(kWord); end; -function AllocPerm(size, align: int64): int64; +{ Pops a value into the variable at a; an address on the stack is under + the value. } +procedure PopVar(const a: TAdr; size: longint); +var m: TMem; begin - AllocPerm := AllocTemp(size, align); - permTop := frameTop; -end; - -function TempMark: int64; -begin - TempMark := frameTop; -end; - -procedure ReleaseTemps(m: int64); -begin - if m < permTop then m := permTop; - 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. } -procedure KeepTemps; -begin - frameTop := frameMax; - permTop := frameMax; + if a.base in [bFrame, bGlobal] then begin + PopTo(RAX); + Store(Place(a, RAX), RAX, size); + end else begin + PopTo(RCX); + m := Place(a, RAX); + Store(m, RCX, size); + end; end; -procedure TempItem(var x: TItem; t: PType; off: int64); -var p: TPos; +procedure Drop; begin - p := x.pos; - FillChar(x, SizeOf(x), 0); - x.pos := p; - x.mode := mVar; x.typ := t; x.base := bFrame; x.off := off; + dec(depth); + if stack[depth].isConst then exit; + if inRax = depth then inRax := -1 + else begin + AluI(aluAdd, RSP, 8); + dec(pushed); + end; end; -function ToSlot(var x: TItem): int64; -var s: int64; +{ The two values on top change places. } +procedure Swap; +var e: TEntry; a, b: boolean; begin - Value(x); - s := AllocTemp(8, 8); - Store(Mem(RBP, s), RAX, 8); - ToSlot := s; + a := stack[depth - 2].isConst; + b := stack[depth - 1].isConst; + if not a and not b then begin + { the one on top is in rax, or pushed over the other } + if inRax <> depth - 1 then begin Pop(RAX); dec(pushed) end; + Xchg(Mem(RSP, 0), RAX); + inRax := depth - 1; + end else if inRax = depth - 1 then inRax := depth - 2 + else if inRax = depth - 2 then inRax := depth - 1; + e := stack[depth - 1]; + stack[depth - 1] := stack[depth - 2]; + stack[depth - 2] := e; end; { Copying } @@ -485,7 +336,7 @@ as they fall. Up to 64 bytes, as a record or a small array mostly is, they go as moves of 8, 4, 2 and 1 bytes: rep movsb takes some twenty cycles to start, longer than the few moves take. } -procedure Copy(size: int64); +procedure CopyBytes(size: int64); var o, n: int64; begin if size > 64 then begin @@ -503,929 +354,559 @@ end; end; -procedure CopyToTemp(var x: TItem); -var t: int64; +{ Pops a source's address, and a destination's under it, and copies + size bytes to off bytes past the destination. } +procedure CopyBlock(size, off: int64); begin - if x.vol then MarkAt(x.pos, 'can''t copy through a volatile pointer'); - t := AllocTemp(x.typ^.size, x.typ^.align); - Address(x, RSI); - Lea(RDI, Mem(RBP, t)); - Copy(x.typ^.size); - TempItem(x, x.typ, t); + PopTo(RSI); + PopTo(RDI); + if off <> 0 then Lea(RDI, Mem(RDI, off)); + CopyBytes(size); end; -{ A slice made from an address in rax and a length. } -procedure SliceOf(var x: TItem; t: PType; len: int64); -var s: int64; +{ Pops a source's address, and copies size bytes to a. } +procedure CopyTo(const a: TAdr; size: int64); begin - s := AllocTemp(16, 8); - Store(Mem(RBP, s), RAX, 8); - MovRI(RAX, len); - Store(Mem(RBP, s + 8), RAX, 8); - TempItem(x, t, s); + PopTo(RSI); + Lea(RDI, Place(a, RDI)); + CopyBytes(size); end; -{ An INT goes silently into an I64, and a UINT into a U64, losing - nothing on any target (report section 5.10). } -function Widens(s, t: PType): boolean; +procedure ZeroVar(const a: TAdr; size: int64); begin - Widens := ((s = tInt) and Same(t, tI64)) or ((s = tUInt) and Same(t, tU64)); + Lea(RDI, Place(a, RDI)); + Spill; + MovRI(RCX, size); + MovRI(RAX, 0); + RepStosb; end; -{ Another module's exported variable can be read, not changed, nor - handed to anything that could change it (report section 3). } -procedure NotReadOnly(const x: TItem); -begin - if x.ro then MarkAt(x.pos, Source(x.pos) + ' is ' + NameOf(x.obj^.module^.name) + '''s, and can''t be changed outside it'); -end; +{ Operations } -procedure Coerce(var x: TItem; t: PType); -var s: PType; tmp: int64; +function Log2(v: int64): longint; +var n: longint; begin - s := x.typ; - if x.mode = mStr then begin - if (t^.form = fSlice) and (t^.base = tU8) then begin - Address(x, RAX); SliceOf(x, t, x.val) - end else if (t^.form = fPtr) and (t^.base = tU8) then begin - Address(x, RAX); x.mode := mReg; x.typ := t - end else if (t^.form = fArray) and (t^.base = tU8) and (t^.len >= x.val) then begin - tmp := AllocTemp(t^.size, 1); - Lea(RDI, Mem(RBP, tmp)); - Lea(RSI, MemRip(x.chunk, 0)); - Copy(x.val); - Lea(RDI, Mem(RBP, tmp + x.val)); - MovRI(RCX, t^.len - x.val); - MovRI(RAX, 0); - RepStosb; - TempItem(x, t, tmp); - end else MarkAt(x.pos, 'can''t use a string as ' + TypeName(t)); - exit; - end; - if x.mode in [mType, mBuiltin, mNone, mCase] then NotValue(x); - if Same(s, t) then exit; - if Widens(s, t) then x.typ := t { the same bits, on a 64-bit target } - else if (s = tRConst) and (t^.form = fReal) then RealTo(x, t) - else if (s^.form = fConst) and (t^.form = fInt) then begin - if (x.mode = mConst) and not Fits(x.val, t) then MarkAt(x.pos, IntStr(x.val) + ' doesn''t fit ' + TypeName(t)); - x.typ := t; - end else if (s^.form = fNil) and (t^.form in [fPtr, fProc, fError]) then - x.typ := t - else if (s^.form = fPtr) and (t^.form = fPtr) and t^.vol and not s^.vol - and Same(s^.base, t^.base) then - x.typ := t - else if (s^.form = fArray) and (t^.form = fSlice) and Same(s^.base, t^.base) then begin - NotReadOnly(x); - if x.vol then MarkAt(x.pos, 'can''t make a slice through a volatile pointer'); - if x.odd then MarkAt(x.pos, 'can''t make a slice of a field of a packed record'); - Address(x, RAX); - SliceOf(x, t, s^.len); - end else - MarkAt(x.pos, 'can''t use ' + TypeName(s) + ' as ' + TypeName(t)); + n := 0; + while (v > 1) and (v and 1 = 0) do begin v := v shr 1; inc(n) end; + if v <> 1 then n := -1; + Log2 := n; end; -{ Coerce where the types must be the same, as in a for loop, INC and - several results, which don't widen an INT to an I64 (report sections - 5.10, 6.1 and 7.2); help, if not empty, says why. } -procedure CoerceExact(var x: TItem; t: PType; const help: shortstring); -var h: shortstring; +{ rax 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). } +procedure DivPow2(op: TSym; k: longint; unsign: boolean); begin - if Widens(x.typ, t) then begin - h := help; - if h = '' then h := 'they don''t mix here: write ' + TypeName(t) + '(' + Source(x.pos) + ')'; - MarkHelp(x.pos, 'expected ' + TypeName(t) + ', found ' + What(x), h); + if unsign then begin + if op = sDiv then ShiftI(shShr, RAX, k) + else begin ShiftI(shShl, RAX, 64 - k); ShiftI(shShr, RAX, 64 - k) end; + exit; end; - Coerce(x, t); + MovRR(RCX, RAX); + ShiftI(shSar, RCX, 63); + ShiftI(shShr, RCX, 64 - k); + Alu(aluAdd, RCX, RAX); + ShiftI(shSar, RCX, k); + if op = sDiv then MovRR(RAX, RCX) + else begin ShiftI(shShl, RCX, k); Alu(aluSub, RAX, RCX) end; end; -procedure Assign(var dst, src: TItem); -var m: TMem; +procedure CmpI(r: longint; v: int64); begin - Coerce(src, dst.typ); - if IsScalar(dst.typ) then begin - Value(src); - m := MemOf(dst, RCX); - Store(m, RAX, ScalarSize(dst.typ)); - end else begin - if dst.vol or src.vol then MarkAt(src.pos, 'can''t copy through a volatile pointer'); - Address(src, RSI); - Address(dst, RDI); - Copy(dst.typ^.size); - end; + if (v >= low(longint)) and (v <= high(longint)) then AluI(aluCmp, r, v) + else begin MovRI(R11, v); Alu(aluCmp, r, R11) end; end; - -{ Checks } -const - NoBase = -2; { a TMem that is no memory } - -{ The program goes on if the condition cc holds, and otherwise stops - in Rt.fail(what, a, b, len, at, name), which says what failed at p, - found by at, the address of the call: an index a (what = 0), a slice - a..b (1), each for a length len, or a position a of the enumeration - called name (2). a is in register ra, b in RDX; len is in memory at - m, or n if m.base is NoBase. The failing code has p for its place, - and the code after it the place before it again. } -procedure Check(cc, what: longint; const p: TPos; ra: longint; const m: TMem; n: int64; name: longint); -var L, line, col: longint; before: TLine; +{ Before rax div rcx, 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. } +procedure DivTrap(bits: longint); +var L: longint; begin L := NoLabel; - Jcc(cc, L); - before := lines^[numLines - 1]; - LineCol(p.a, line, col); - NoteLine(line, col); - MovRR(RSI, ra); - if m.base = NoBase then MovRI(RCX, n) else Load(RCX, m, 8, false); - Lea(R8, Here); - MovRI(RDI, what); - if name >= 0 then Lea(R9, MemRip(name, 0)); - AluI(aluAnd, RSP, -16); - CallChunk(rtFail); - Ud2; + CmpI(RCX, -1); + Jcc(ccNE, L); + CmpI(RAX, int64(-1) shl (bits - 1)); + Jcc(ccNE, L); + ShiftI(shShl, RAX, 64 - bits); FixLink(L); - NoteLine(before.line, before.col); end; -{ For Check: a length known here, not in memory } -function NoMem: TMem; +{ The two values on top, the left one into rax and the right into rcx } +procedure Operands; begin - NoMem := Mem(NoBase, 0); + PopTo(RCX); + PopTo(RAX); end; -{ t's name, ending in a zero byte, for Rt.fail } -function NameChunk(t: PType): longint; -var s: shortstring; c: longint; +procedure RealOp(op: TSym; k: TKind); +var f: boolean; begin - s := TypeName(t) + #0; - c := NewChunk(secRodata, -1, -1); - SetData(c, @s[1], length(s), 1); - NameChunk := c; + f := k = kF32; + Operands; + MovqXR(0, RAX); + MovqXR(1, RCX); + case op of + sPlus: Sse($58, 0, 1, f); + sMinus: Sse($5C, 0, 1, f); + sTimes: Sse($59, 0, 1, f); + sSlash: Sse($5E, 0, 1, f); + end; + MovqRX(RAX, 0); + Computed(k); end; -{ Selectors } - -procedure Deref(var x: TItem); -var t: PType; +{ The two values on top, the left op the right, an integer of size + bytes, signed or not, brought back to its width. } +procedure Op(op: TSym; k: TKind; size: longint; signed: boolean); +var y: TEntry; sh, bits: longint; begin - t := x.typ; - if t^.form <> fPtr then MarkAt(x.pos, 'expected a pointer, found ' + TypeName(t)); - if t^.base = nil then MarkAt(x.pos, TypeName(t) + ' points to a type never declared'); - Value(x); - x.mode := mVar; x.base := bReg; x.reg := RAX; x.off := 0; - x.typ := t^.base; x.vol := t^.vol; x.isVar := true; x.odd := false; x.ro := false; -end; - -{ A field of a packed record, of more than one byte's alignment, may - sit anywhere; it is read and written, but has no address and no - volatile access, which a machine that can't reach a misaligned word - couldn't make one access (report section 5.5). } -procedure Field(var x: TItem; f: PObj); -begin - if x.typ^.packd and (f^.typ^.align > 1) then begin - if x.vol then MarkAt(x.pos, 'a field of a packed record can''t be volatile'); - x.odd := true; + if k in [kF32, kF64] then begin RealOp(op, k); exit end; + bits := size * 8; + y := stack[depth - 1]; + sh := -1; + if y.isConst and (op in [sTimes, sDiv, sMod]) then sh := Log2(y.val); + if y.isConst then begin + dec(depth); + PopTo(RAX); + if sh < 1 then MovRI(RCX, y.val); + end else Operands; + case op of + sPlus: Alu(aluAdd, RAX, RCX); + sMinus: Alu(aluSub, RAX, RCX); + sTimes: if sh >= 1 then ShiftI(shShl, RAX, sh) else Imul(RAX, RCX); + sDiv, sMod: if sh >= 1 then DivPow2(op, sh, not signed) else begin + if not signed then begin MovRI(RDX, 0); Unary(6, RCX) end + else begin + if (bits < 64) and (not y.isConst or (y.val = -1)) then DivTrap(bits); + Cqo; Unary(7, RCX) + end; + if op = sMod then MovRR(RAX, RDX); + end; + sAmp: Alu(aluAnd, RAX, RCX); + sBar: Alu(aluOr, RAX, RCX); + sXor: Alu(aluXor, RAX, RCX); + sShl, sShr: begin + { the count modulo the width: the machine takes it modulo 64 } + if bits < 64 then AluI(aluAnd, RCX, bits - 1); + if op = sShl then Shift(shShl, RAX) + else if signed then Shift(shSar, RAX) else Shift(shShr, RAX); + end; end; - x.off := x.off + f^.val; - x.typ := f^.typ; -end; - -procedure IndexPrep(var x: TItem); -begin - if x.mode = mStr then Coerce(x, tBytes); - if (x.typ^.form = fPtr) and (x.typ^.base^.form = fArray) then - MarkAt(x.pos, 'a pointer to an array is indexed as p^[i]'); - if x.typ^.form = fPtr then begin - Value(x); PushRax; x.mode := mStack - end else if (x.mode = mVar) and (x.typ^.form in [fArray, fSlice]) then - Save(x) - else MarkAt(x.pos, 'expected an array, a slice or a pointer, found ' + What(x)); + if bits < 64 then Extend(RAX, size, signed); + Computed(k); end; -procedure Index(var x, y: TItem); -var t: PType; s: int64; m, ml: TMem; +{ The left op the right of the two values on top, as a BOOL } +procedure Compare(op: TSym; k: TKind; signed: boolean); +const + CcSigned: array[sEql..sGeq] of longint = (ccE, ccNE, ccL, ccLE, ccG, ccGE); + CcUnsigned: array[sEql..sGeq] of longint = (ccE, ccNE, ccB, ccBE, ccA, ccAE); +var y: TEntry; f: boolean; begin - t := x.typ; - s := t^.base^.size; - if not IsInt(y.typ) then MarkAt(y.pos, 'an index is an integer, found ' + What(y)); - if t^.form = fPtr then begin - Value(y); - if s <> 1 then ImulI(RAX, s); - PopR(RCX); - Alu(aluAdd, RAX, RCX); - x.mode := mVar; x.base := bReg; x.reg := RAX; x.off := 0; - x.vol := t^.vol; x.isVar := true; x.odd := false; x.ro := false; - end else if (t^.form = fArray) and (y.mode = mConst) then begin - if (y.val < 0) or (y.val >= t^.len) then MarkAt(y.pos, 'index ' + IntStr(y.val) + ' is out of range for a length of ' + IntStr(t^.len)); - x.off := x.off + y.val * s; - if x.base = bStack then begin - PopR(RAX); x.base := bReg; x.reg := RAX + if k in [kF32, kF64] then begin + f := k = kF32; + Operands; + MovqXR(0, RAX); + MovqXR(1, RCX); + case op of + sEql: begin Ucomis(0, 1, f); SetCC(ccE, RAX); SetCC(ccNP, RCX); Alu(aluAnd, RAX, RCX) end; + sNeq: begin Ucomis(0, 1, f); SetCC(ccNE, RAX); SetCC(ccP, RCX); Alu(aluOr, RAX, RCX) end; + sLss: begin Ucomis(1, 0, f); SetCC(ccA, RAX) end; + sLeq: begin Ucomis(1, 0, f); SetCC(ccAE, RAX) end; + sGtr: begin Ucomis(0, 1, f); SetCC(ccA, RAX) end; + sGeq: begin Ucomis(0, 1, f); SetCC(ccAE, RAX) end; end; - end else if t^.form = fArray then begin - Value(y); - if checks then begin - CmpI(RAX, t^.len); - Check(ccB, 0, y.pos, RAX, NoMem, t^.len, -1); - end; - if s <> 1 then ImulI(RAX, s); - if x.base = bStack then PopR(RCX) else Lea(RCX, MemOf(x, RCX)); - Alu(aluAdd, RAX, RCX); - if x.base <> bStack then x.off := 0; - x.base := bReg; x.reg := RAX; end else begin - Value(y); - m := MemOf(x, RCX); - ml := m; ml.disp := ml.disp + 8; - if checks then begin - AluM(aluCmp, RAX, ml); - Check(ccB, 0, y.pos, RAX, ml, 0, -1); + y := stack[depth - 1]; + if y.isConst then begin + dec(depth); + PopTo(RAX); + CmpI(RAX, y.val); + end else begin + Operands; + Alu(aluCmp, RAX, RCX); end; - if s <> 1 then ImulI(RAX, s); - AluM(aluAdd, RAX, m); - x.base := bReg; x.reg := RAX; x.off := 0; x.isVar := true; x.vol := false; x.ro := false; + if signed then SetCC(CcSigned[op], RAX) else SetCC(CcUnsigned[op], RAX); end; - x.typ := t^.base; + Computed(kWord); end; -procedure SliceLo(var lo: TItem); +procedure Neg(k: TKind; size: longint; signed: boolean); begin - if not IsInt(lo.typ) then MarkAt(lo.pos, 'an index is an integer, found ' + What(lo)); - Value(lo); - PushRax; + PopTo(RAX); + case k of + kF32: Btc(RAX, 31); + kF64: Btc(RAX, 63); + else + Unary(3, RAX); + if size < 8 then Extend(RAX, size, signed); + end; + Computed(k); end; -procedure Slice(var x, lo, hi: TItem); -var t, st: PType; s, tmp: int64; m, ml: TMem; +procedure Complement(size: longint; signed: boolean); begin - t := x.typ; - s := t^.base^.size; - if not IsInt(hi.typ) then MarkAt(hi.pos, 'an index is an integer, found ' + What(hi)); - if x.vol then MarkAt(x.pos, 'can''t make a slice through a volatile pointer'); - if x.odd then MarkAt(x.pos, 'can''t make a slice of a field of a packed record'); - if t^.form = fArray then NotReadOnly(x); - Value(hi); - MovRR(RDX, RAX); - PopR(RCX); - if t^.form = fPtr then begin - { the bounds can't be known, but a slice can't run backwards } - PopR(R8); - if checks then begin - Alu(aluCmp, RCX, RDX); - Check(ccLE, 3, lo.pos, RCX, NoMem, 0, -1); - end; - end else begin - m := MemOf(x, R8); - ml := m; ml.disp := ml.disp + 8; - if checks then begin - if t^.form = fArray then begin CmpI(RDX, t^.len); ml := NoMem end - else AluM(aluCmp, RDX, ml); - Check(ccBE, 1, lo.pos, RCX, ml, t^.len, -1); - Alu(aluCmp, RCX, RDX); - Check(ccBE, 1, lo.pos, RCX, ml, t^.len, -1); - end; - end; - tmp := AllocTemp(16, 8); - MovRR(RAX, RDX); - Alu(aluSub, RAX, RCX); - Store(Mem(RBP, tmp + 8), RAX, 8); - if s <> 1 then ImulI(RCX, s); - case t^.form of - fPtr: MovRR(RAX, R8); - fArray: Lea(RAX, m); - else Load(RAX, m, 8, false); - end; - Alu(aluAdd, RAX, RCX); - Store(Mem(RBP, tmp), RAX, 8); - st := NewType(fSlice, 16, 8); - st^.base := t^.base; - TempItem(x, st, tmp); + PopTo(RAX); + Unary(2, RAX); + if size < 8 then Extend(RAX, size, signed); + Computed(kWord); end; -{ Operators } - -procedure Neg(var x: TItem); +procedure NotBool; begin - if x.typ^.form = fReal then begin - if x.mode = mConst then x.val := x.val xor low(int64) - else begin Value(x); if IsF32(x.typ) then Btc(RAX, 31) else Btc(RAX, 63) end; - end else if IsInt(x.typ) then begin - if (x.mode = mConst) and (x.typ^.form = fConst) and (x.val = low(int64)) then - MarkAt(x.pos, 'the constant is too big for I64') - else if x.mode = mConst then x.val := Cut(-x.val, x.typ) - else begin Value(x); Unary(3, RAX); Norm(x.typ) end; - end else MarkAt(x.pos, 'can''t negate ' + TypeName(x.typ)); + PopTo(RAX); + AluI(aluXor, RAX, 1); + Computed(kWord); end; -procedure NotOp(var x: TItem); +{ The integer on top, brought to size bytes } +procedure Narrow(size: longint; signed: boolean); begin - if IsInt(x.typ) then MarkHelp(x.pos, '"not" needs a BOOL, found ' + What(x), 'the bits of an integer flip with ~'); - if x.typ^.form <> fBool then MarkAt(x.pos, '"not" needs a BOOL, found ' + What(x)); - if x.mode = mConst then x.val := 1 - x.val - else begin Value(x); AluI(aluXor, RAX, 1) end; + PopTo(RAX); + if size < 8 then Extend(RAX, size, signed); + Computed(kWord); end; -procedure Complement(var x: TItem); +{ 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 } +procedure IntToReal(k: TKind; big: boolean); +var L1, L2: longint; f: boolean; begin - if x.typ^.form = fBool then MarkHelp(x.pos, '"~" needs an integer, found ' + What(x), 'a BOOL is negated with not'); - if not IsInt(x.typ) then MarkAt(x.pos, '"~" needs an integer, found ' + What(x)); - if x.mode = mConst then x.val := Cut(not x.val, x.typ) - else begin Value(x); Unary(2, RAX); Norm(x.typ) end; + f := k = kF32; + PopTo(RAX); + if big then begin + { above high(I64): halve, keeping the low bit, and double } + L1 := NoLabel; L2 := NoLabel; + TestRR(RAX, RAX); + Jcc(ccS, L1); + Cvtsi2s(0, RAX, f); + Jmp(L2); + FixLink(L1); + MovRR(RCX, RAX); + ShiftI(shShr, RCX, 1); + AluI(aluAnd, RAX, 1); + Alu(aluOr, RCX, RAX); + Cvtsi2s(0, RCX, f); + Sse($58, 0, 0, f); + FixLink(L2); + end else Cvtsi2s(0, RAX, f); + MovqRX(RAX, 0); + Computed(k); end; -{ Arrays, slices and strings, which = and # compare element by element } -function IsSeq(t: PType): boolean; +{ The real of kind k on top, truncated to an integer } +procedure RealToInt(k: TKind); begin - IsSeq := t^.form in [fStr, fArray, fSlice]; + PopTo(RAX); + MovqXR(0, RAX); + Cvtts2si(RAX, 0, k = kF32); + Computed(kWord); end; -function ElemOf(t: PType): PType; +{ The real of kind k on top, as the other kind } +procedure RealToReal(k: TKind); begin - if t^.form = fStr then ElemOf := tU8 else ElemOf := t^.base; + PopTo(RAX); + MovqXR(0, RAX); + Sse($5A, 0, 0, k = kF32); + MovqRX(RAX, 0); + if k = kF32 then Computed(kF64) else Computed(kF32); end; -{ An array, slice or string as a slice in a temporary, for comparing. } -procedure SeqSlice(var x: TItem); -var t: PType; +{ Whether the slices in the frame at a and b are equal (or not, if not + eq): the lengths, then the bytes, len shl shift of them, compared + right where the comparison stands. } +procedure CompareSeq(a, b: int64; shift: longint; eq: boolean); +var differ: longint; begin - t := NewType(fSlice, 16, 8); - t^.base := ElemOf(x.typ); - if x.typ^.form = fSlice then begin - x.typ := t; CopyToTemp(x) - end else begin - if x.mode = mStr then begin Address(x, RAX); SliceOf(x, t, x.val) end - else begin - if x.vol then MarkAt(x.pos, 'can''t compare through a volatile pointer'); - Address(x, RAX); SliceOf(x, t, x.typ^.len) - end; - end; + Spill; + Load(RCX, Mem(RBP, b + 8), 8, false); + AluM(aluCmp, RCX, Mem(RBP, a + 8)); + differ := NoLabel; + Jcc(ccNE, differ); + Load(RSI, Mem(RBP, b), 8, false); + Load(RDI, Mem(RBP, a), 8, false); + if shift > 0 then ShiftI(shShl, RCX, shift); + Alu(aluCmp, RCX, RCX); { equal, if there are no bytes } + RepeCmpsb; + FixLink(differ); + if eq then SetCC(ccE, RAX) else SetCC(ccNE, RAX); + Computed(kWord); end; -procedure Op1(op: TSym; var x: TItem; var L: longint); -var tmp: TItem; +{ An error is the address of its length, followed by its message: pops + one, and makes the slice of its message at tmp, empty for nil. } +procedure ErrorText(tmp: int64); +var L: longint; begin + PopTo(RAX); + MovRI(RCX, 0); L := NoLabel; - if (op in [sAnd, sOr]) and (x.typ^.form = fBool) then begin - tmp := x; - Value(tmp); - if x.mode <> mConst then x := tmp; - TestRR(RAX, RAX); - if op = sAnd then Jcc(ccE, L) else Jcc(ccNE, L); - end else if (op in [sEql, sNeq]) and IsSeq(x.typ) then - SeqSlice(x) - else if (op = sPlus) and (x.mode = mStr) then - { two string constants to be joined: nothing to compute } - else if x.mode in [mType, mBuiltin, mNone, mCase, mStr] then - NotValue(x) - else if x.mode <> mConst then begin - Value(x); PushRax; x.mode := mStack - end; + TestRR(RAX, RAX); + Jcc(ccE, L); + Load(RCX, Mem(RAX, 0), 8, false); + Lea(RAX, Mem(RAX, 8)); + FixLink(L); + Store(Mem(RBP, tmp), RAX, 8); + Store(Mem(RBP, tmp + 8), RCX, 8); end; -function Log2(v: int64): longint; -var n: longint; +{ Pops a step and an integer variable's address, and adds the step to + it, or takes it away. } +procedure IncDec(size: longint; signed, dec: boolean); begin - n := 0; - while (v > 1) and (v and 1 = 0) do begin v := v shr 1; inc(n) end; - if v <> 1 then n := -1; - Log2 := n; + PopTo(RCX); + PopTo(RDX); + Spill; + Load(RAX, Mem(RDX, 0), size, signed); + if dec then Alu(aluSub, RAX, RCX) else Alu(aluAdd, RAX, RCX); + Store(Mem(RDX, 0), RAX, size); end; -{ rax 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). } -procedure DivPow2(op: TSym; k: longint; unsign: boolean); +{ The pointer on top, which NEW got, to size zero bytes unless nil } +procedure ZeroNew(size: int64); +var L: longint; begin - if unsign then begin - if op = sDiv then ShiftI(shShr, RAX, k) - else begin ShiftI(shShl, RAX, 64 - k); ShiftI(shShr, RAX, 64 - k) end; - exit; - end; - MovRR(RCX, RAX); - ShiftI(shSar, RCX, 63); - ShiftI(shShr, RCX, 64 - k); - Alu(aluAdd, RCX, RAX); - ShiftI(shSar, RCX, k); - if op = sDiv then MovRR(RAX, RCX) - else begin ShiftI(shShl, RCX, k); Alu(aluSub, RAX, RCX) end; + PopTo(RAX); + L := NoLabel; + TestRR(RAX, RAX); + Jcc(ccE, L); + MovRR(RDX, RAX); + MovRR(RDI, RAX); + MovRI(RCX, size); + MovRI(RAX, 0); + RepStosb; + MovRR(RAX, RDX); + FixLink(L); + Computed(kWord); end; -{ Whether a op b, for + - *, overflows an I64: an untyped constant - doesn't wrap, it is an error (report section 4). } -function Overflows(op: TSym; a, b: int64): boolean; +{ CAS(p, old, new), XCHG(p, v) or XADD(p, v), from the stack } +procedure Atomic(which: longint); begin - case op of - sPlus: Overflows := ((b > 0) and (a > high(int64) - b)) or ((b < 0) and (a < low(int64) - b)); - sMinus: Overflows := ((b < 0) and (a > high(int64) + b)) or ((b > 0) and (a < low(int64) + b)); - sTimes: - if (a = 0) or (b = 0) then Overflows := false - else if a = -1 then Overflows := b = low(int64) - else if b = -1 then Overflows := a = low(int64) - else Overflows := (a * b) div b <> a; - else Overflows := false; + if which = bCas then PopTo(RDX); + PopTo(RAX); + PopTo(RCX); + case which of + bCas: begin LockCmpxchg(Mem(RCX, 0), RDX); SetCC(ccE, RAX) end; + bXchg: Xchg(Mem(RCX, 0), RAX); + bXadd: LockXadd(Mem(RCX, 0), RAX); end; + Computed(kWord); end; -{ A type's width in bits; an untyped constant's is an I64's } -function Bits(t: PType): longint; +{ The system call and its arguments, n values on the stack } +procedure SysCall(n: longint); +const Regs: array[0..6] of longint = (RAX, RDI, RSI, RDX, R10, R8, R9); +var i: longint; begin - Bits := t^.size * 8; + for i := n - 1 downto 0 do PopTo(Regs[i]); + x64.Syscall; + Computed(kWord); end; -function FoldInt(op: TSym; a, b: int64; t: PType; const p: TPos): int64; -var u: boolean; +procedure Fence; begin - u := (t^.form = fInt) and not t^.signed; - if (t^.form = fConst) and Overflows(op, a, b) then MarkAt(p, 'the constant is too big for I64'); - case op of - sPlus: FoldInt := a + b; - sMinus: FoldInt := a - b; - sTimes: FoldInt := a * b; - sDiv, sMod: begin - if b = 0 then MarkAt(p, 'division by zero'); - if u then begin - if op = sDiv then FoldInt := int64(qword(a) div qword(b)) - else FoldInt := int64(qword(a) mod qword(b)); - end else if (b = -1) and (a = int64(-1) shl (Bits(t) - 1)) then MarkAt(p, 'division overflows') - else if op = sDiv then FoldInt := a div b - else FoldInt := a mod b; - end; - sAmp: FoldInt := a and b; - sBar: FoldInt := a or b; - sXor: FoldInt := a xor b; - sShl: FoldInt := a shl (b and (Bits(t) - 1)); - sShr: if u then FoldInt := int64(qword(a) shr (b and (Bits(t) - 1))) - else FoldInt := SarInt64(a, b and (Bits(t) - 1)); - sEql: FoldInt := ord(a = b); - sNeq: FoldInt := ord(a <> b); - sLss: if u then FoldInt := ord(qword(a) < qword(b)) else FoldInt := ord(a < b); - sLeq: if u then FoldInt := ord(qword(a) <= qword(b)) else FoldInt := ord(a <= b); - sGtr: if u then FoldInt := ord(qword(a) > qword(b)) else FoldInt := ord(a > b); - sGeq: if u then FoldInt := ord(qword(a) >= qword(b)) else FoldInt := ord(a >= b); - else MarkAt(p, 'bad operator'); FoldInt := 0; - end; + Mfence; end; -{ Folds x op y, of the real type t: an F32 rounded at each step, as - the machine would. } -function FoldReal(op: TSym; const x, y: TItem; t: PType; var r: TItem): boolean; -var a, b: double; +{ Jumps. A label is the chain of the jumps to it, until it is placed. } + +procedure Jump(var L: longint); begin - a := RealOf(x); b := RealOf(y); - FoldReal := true; - case op of - sPlus: MakeReal(r, a + b); - sMinus: MakeReal(r, a - b); - sTimes: MakeReal(r, a * b); - sSlash: MakeReal(r, a / b); - sEql: MakeConst(r, tBool, ord(a = b)); - sNeq: MakeConst(r, tBool, ord(a <> b)); - sLss: MakeConst(r, tBool, ord(a < b)); - sLeq: MakeConst(r, tBool, ord(a <= b)); - sGtr: MakeConst(r, tBool, ord(a > b)); - sGeq: MakeConst(r, tBool, ord(a >= b)); - else FoldReal := false; - end; - if r.typ^.form = fReal then RealTo(r, t); + Jmp(L); end; -{ and, or and not are for BOOLs; &, |, xor and ~ for the bits of - integers: x is the wrong kind for op, and the message names the - operator it may have meant } -{ Before rax div rcx, of a signed type narrower than 64 bits: 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. } -procedure DivTrap(t: PType); -var L: longint; +{ Pops a BOOL, and jumps if it is when } +procedure JumpIf(var L: longint; when: boolean); begin - L := NoLabel; - CmpI(RCX, -1); - Jcc(ccNE, L); - CmpI(RAX, int64(-1) shl (Bits(t) - 1)); - Jcc(ccNE, L); - ShiftI(shShl, RAX, 64 - Bits(t)); - FixLink(L); + PopTo(RAX); + TestRR(RAX, RAX); + if when then Jcc(ccNE, L) else Jcc(ccE, L); end; -procedure WrongLogic(op: TSym; var x: TItem); -const Bits = 'the bits of integers take '; +{ For and and or: jumps if the BOOL on top is when, keeping it for + where the jump goes, and drops it if not. } +procedure JumpKeep(var L: longint; when: boolean); begin - case op of - sAnd: if IsInt(x.typ) then MarkHelp(x.pos, '"and" needs BOOLs, found ' + What(x), Bits + '&'); - sOr: if IsInt(x.typ) then MarkHelp(x.pos, '"or" needs BOOLs, found ' + What(x), Bits + '|'); - sAmp: MarkHelp(x.pos, '"&" needs integers, found ' + What(x), 'BOOLs take and'); - sBar: MarkHelp(x.pos, '"|" needs integers, found ' + What(x), 'BOOLs take or'); - sXor: MarkHelp(x.pos, '"xor" needs integers, found ' + What(x), 'BOOLs that differ are #'); - end; - MarkAt(x.pos, SymText(op) + ' needs BOOLs, found ' + What(x)); + JumpIf(L, when); end; -{ x + y, of two string constants: one string, in a chunk of its own - (report section 4) } -procedure JoinStr(var x, y: TItem); -var p: PBytes; c: longint; +{ Where JumpKeep went: the BOOL on top is there, as it was there. } +procedure FixKeep(L: longint); begin - if y.mode <> mStr then MarkAt(y.pos, '"+" joins two strings, found ' + What(y)); - p := GetMem(x.val + y.val + 1); - Move(rodata^[chunks^[x.chunk].start], p^[0], x.val); - Move(rodata^[chunks^[y.chunk].start], p^[x.val], y.val + 1); - c := NewChunk(secRodata, -1, -1); - SetData(c, p, x.val + y.val + 1, 1); - FreeMem(p); - x.chunk := c; - x.val := x.val + y.val; + TopToRax; + FixLink(L); end; -procedure Op2(op: TSym; var x, y: TItem; L: longint); +{ Pops two integers, and jumps if the left op the right } +procedure JumpCmp(op: TSym; signed: boolean; var L: longint); const - Rel = [sEql, sNeq, sLss, sLeq, sGtr, sGeq]; CcSigned: array[sEql..sGeq] of longint = (ccE, ccNE, ccL, ccLE, ccG, ccGE); CcUnsigned: array[sEql..sGeq] of longint = (ccE, ccNE, ccB, ccBE, ccA, ccAE); -var - xt, yt, t, e: PType; r: TItem; scale, sh, k, differ: longint; isPtr, unsign, f: boolean; a, b: int64; +var y: TEntry; begin - xt := x.typ; yt := y.typ; - if y.mode in [mType, mBuiltin, mNone, mCase] then NotValue(y); - if (op = sPlus) and (x.mode = mStr) then begin JoinStr(x, y); exit end; - - if op in [sAnd, sOr] then begin - if xt^.form <> fBool then WrongLogic(op, x); - if yt^.form <> fBool then WrongLogic(op, y); - if (x.mode = mConst) and (y.mode = mConst) then begin - FixLink(L); - if op = sAnd then x.val := x.val and y.val else x.val := x.val or y.val; - exit; - end; - Value(y); - FixLink(L); - x.mode := mReg; x.typ := tBool; - exit; + y := stack[depth - 1]; + if y.isConst then begin + dec(depth); + PopTo(RAX); + CmpI(RAX, y.val); + end else begin + Operands; + Alu(aluCmp, RAX, RCX); end; + if signed then Jcc(CcSigned[op], L) else Jcc(CcUnsigned[op], L); +end; - if (op in [sAmp, sBar, sXor]) and (xt^.form = fBool) then WrongLogic(op, x); - if (op in [sAmp, sBar, sXor]) and (yt^.form = fBool) then WrongLogic(op, y); +procedure JumpBack(top: longint); +begin + JmpBack(top); +end; - { the lengths, then the bytes, LEN * SIZE(T) of them: the elements - are of types whose bytes say all there is to their values } - if (op in [sEql, sNeq]) and IsSeq(xt) then begin - e := ElemOf(xt); - if not IsSeq(yt) then - MarkAt(Join(x.pos, y.pos), 'can''t compare an array with ' + TypeName(yt)) - else if not Same(e, ElemOf(yt)) then - MarkAt(Join(x.pos, y.pos), 'can''t compare an array of ' + TypeName(e) + ' with one of ' + TypeName(ElemOf(yt))); - if e^.form = fReal then - MarkHelp(Join(x.pos, y.pos), 'can''t compare arrays of reals with ' + SymText(op), - '-0.0 = 0.0 and a NaN equals nothing, though their bytes say otherwise: write a loop') - else if not (e^.form in [fInt, fBool, fEnum, fSet, fPtr]) then - MarkHelp(Join(x.pos, y.pos), 'can''t compare arrays of ' + TypeName(e) + ' with ' + SymText(op), 'write a loop'); - SeqSlice(y); - Address(y, RSI); - Address(x, RDI); - Load(RCX, Mem(RSI, 8), 8, false); - AluM(aluCmp, RCX, Mem(RDI, 8)); - differ := NoLabel; - Jcc(ccNE, differ); - Load(RSI, Mem(RSI, 0), 8, false); - Load(RDI, Mem(RDI, 0), 8, false); - if e^.size > 1 then ShiftI(shShl, RCX, Log2(e^.size)); - Alu(aluCmp, RCX, RCX); { equal, if there are no bytes } - RepeCmpsb; - FixLink(differ); - if op = sEql then SetCC(ccE, RAX) else SetCC(ccNE, RAX); - MakeConst(x, tBool, 0); - x.mode := mReg; - exit; - end; +procedure Fix(L: longint); +begin + FixLink(L); +end; - { the type of the result, and the checks } - t := nil; scale := 1; isPtr := false; - if IsInt(xt) and IsInt(yt) then begin - if op = sSlash then MarkHelp(Join(x.pos, y.pos), '"/" divides reals, not integers', 'to divide integers, write ' + Source(x.pos) + ' div ' + Source(y.pos)); - if op in [sShl, sShr] then begin - if xt^.form = fConst then t := tConst else t := xt - end else if (xt^.form = fConst) and (yt^.form = fConst) then t := tConst - else if xt^.form = fConst then begin - if (x.mode = mConst) and not Fits(x.val, yt) then MarkAt(x.pos, IntStr(x.val) + ' doesn''t fit ' + TypeName(yt)); - t := yt - end else if yt^.form = fConst then begin - if (y.mode = mConst) and not Fits(y.val, xt) then MarkAt(y.pos, IntStr(y.val) + ' doesn''t fit ' + TypeName(xt)); - t := xt - end else if Same(xt, yt) then t := xt - else Mismatch(x, y, xt, yt); - end else if (xt^.form = fReal) and (yt^.form = fReal) then begin - if not (op in Rel + [sPlus, sMinus, sTimes, sSlash]) then MarkAt(Join(x.pos, y.pos), SymText(op) + ' doesn''t apply to ' + TypeName(xt)); - if xt = tRConst then t := yt - else if (yt = tRConst) or Same(xt, yt) then t := xt - else Mismatch(x, y, xt, yt); - if (x.mode = mConst) and (x.typ <> t) then RealTo(x, t); - if (y.mode = mConst) and (y.typ <> t) then RealTo(y, t); - end else if (xt^.form = fBool) and (yt^.form = fBool) then begin - if not (op in [sEql, sNeq]) then MarkAt(Join(x.pos, y.pos), SymText(op) + ' doesn''t apply to ' + TypeName(xt)); - t := tBool; - end else if (xt^.form = fPtr) and IsInt(yt) and (op in [sPlus, sMinus]) then begin - t := xt; scale := xt^.base^.size; isPtr := true; - if y.mode = mConst then y.typ := tInt; - end else if (xt^.form = fPtr) and (yt^.form = fPtr) and (op = sMinus) then begin - if not Same(xt, yt) then Mismatch(x, y, xt, yt); - t := tInt; scale := xt^.base^.size; isPtr := true; - end else if (xt^.form in [fPtr, fProc, fNil, fError]) and (yt^.form in [fPtr, fProc, fNil, fError]) then begin - if not (op in Rel) then MarkAt(Join(x.pos, y.pos), SymText(op) + ' doesn''t apply to ' + TypeName(xt)); - if (xt^.form in [fProc, fError]) or (yt^.form in [fProc, fError]) then - if not (op in [sEql, sNeq]) then MarkAt(Join(x.pos, y.pos), SymText(op) + ' doesn''t apply to ' + TypeName(xt)); - if (xt^.form <> fNil) and (yt^.form <> fNil) and not Same(xt, yt) then - if not ((xt^.form = fPtr) and (yt^.form = fPtr) and Same(xt^.base, yt^.base)) then - Mismatch(x, y, xt, yt); - t := tU64; - end else if (xt^.form = fEnum) and Same(xt, yt) then begin - if not (op in Rel) then MarkAt(Join(x.pos, y.pos), SymText(op) + ' doesn''t apply to ' + TypeName(xt)); - t := xt; - end else if (xt^.form = fSet) and Same(xt, yt) then begin - if not (op in [sPlus, sTimes, sMinus, sEql, sNeq, sLeq, sGeq]) then MarkAt(Join(x.pos, y.pos), SymText(op) + ' doesn''t apply to ' + TypeName(xt)); - t := xt; - end else if (op = sIn) and (yt^.form = fSet) and Same(xt, yt^.base) then - t := yt - else - Mismatch(x, y, xt, yt); - unsign := (t^.form = fInt) and not t^.signed; +procedure FixTo(L, top: longint); +begin + FixLinkTo(L, top); +end; - { constants } - if (x.mode = mConst) and (y.mode = mConst) and not isPtr then begin - if t^.form = fReal then begin - if not FoldReal(op, x, y, t, r) then MarkAt(Join(x.pos, y.pos), SymText(op) + ' doesn''t apply to ' + TypeName(xt)); - x := r; - end else if t^.form = fSet then begin - a := x.val; b := y.val; - case op of - sPlus: MakeConst(x, t, a or b); - sTimes: MakeConst(x, t, a and b); - sMinus: MakeConst(x, t, a and not b); - sIn: MakeConst(x, tBool, (b shr a) and 1); - sLeq: MakeConst(x, tBool, ord(a and not b = 0)); - sGeq: MakeConst(x, tBool, ord(b and not a = 0)); - else MakeConst(x, tBool, ord((a = b) = (op = sEql))); - end; - end else if op in Rel then - MakeConst(x, tBool, FoldInt(op, x.val, y.val, t, Join(x.pos, y.pos))) - else - MakeConst(x, t, Cut(FoldInt(op, x.val, y.val, t, Join(x.pos, y.pos)), t)); - exit; - end; +{ Checks } - { a power of two on the right: shifts instead of imul and idiv } - k := -1; - if (y.mode = mConst) and (op in [sTimes, sDiv, sMod]) and (t^.form = fInt) then k := Log2(y.val); +const + NoBase = -2; { a TMem that is no memory } - { x into rax, y into rcx; a left operand just pushed stays in rax when - the right one needs no code of its own } - if y.mode = mConst then begin - if x.mode <> mStack then Value(x) - else if not Unpush then PopR(RAX); - if k < 1 then ConstTo(RCX, y); - end else if (x.mode = mStack) and (y.mode = mVar) and (y.base in [bFrame, bGlobal]) - and Unpush then - LoadVar(y, RCX) - else begin - Value(y); - MovRR(RCX, RAX); - if x.mode = mConst then ConstTo(RAX, x) else PopR(RAX); - end; - - if t^.form = fReal then begin - MovqXR(0, RAX); - MovqXR(1, RCX); - f := IsF32(t); - case op of - sPlus: Sse($58, 0, 1, f); - sMinus: Sse($5C, 0, 1, f); - sTimes: Sse($59, 0, 1, f); - sSlash: Sse($5E, 0, 1, f); - sEql: begin Ucomis(0, 1, f); SetCC(ccE, RAX); SetCC(ccNP, RCX); Alu(aluAnd, RAX, RCX) end; - sNeq: begin Ucomis(0, 1, f); SetCC(ccNE, RAX); SetCC(ccP, RCX); Alu(aluOr, RAX, RCX) end; - sLss: begin Ucomis(1, 0, f); SetCC(ccA, RAX) end; - sLeq: begin Ucomis(1, 0, f); SetCC(ccAE, RAX) end; - sGtr: begin Ucomis(0, 1, f); SetCC(ccA, RAX) end; - sGeq: begin Ucomis(0, 1, f); SetCC(ccAE, RAX) end; - end; - if not (op in Rel) then MovqRX(RAX, 0); - end else if t^.form = fSet then begin - case op of - sPlus: Alu(aluOr, RAX, RCX); - sTimes: Alu(aluAnd, RAX, RCX); - sMinus: begin Unary(2, RCX); Alu(aluAnd, RAX, RCX) end; - sLeq, sGeq: begin - if op = sLeq then Unary(2, RCX) else Unary(2, RAX); - Alu(aluAnd, RAX, RCX); - TestRR(RAX, RAX); - SetCC(ccE, RAX); - end; - sIn: begin - MovRR(RDX, RCX); MovRR(RCX, RAX); MovRR(RAX, RDX); - Shift(shShr, RAX); - AluI(aluAnd, RAX, 1); - end; - else Alu(aluCmp, RAX, RCX); SetCC(CcUnsigned[op], RAX); - end; - end else if op in Rel then begin - Alu(aluCmp, RAX, RCX); - if (t^.form = fInt) and t^.signed or (t^.form = fConst) then SetCC(CcSigned[op], RAX) - else SetCC(CcUnsigned[op], RAX); - end else begin - case op of - sPlus: begin if scale <> 1 then ImulI(RCX, scale); Alu(aluAdd, RAX, RCX) end; - sMinus: begin - if (scale <> 1) and (t <> tInt) then ImulI(RCX, scale); - Alu(aluSub, RAX, RCX); - if (t = tInt) and isPtr and (scale <> 1) then begin - sh := Log2(scale); - if sh >= 0 then ShiftI(shSar, RAX, sh) - else begin MovRI(RCX, scale); Cqo; Unary(7, RCX) end; - end; - end; - sTimes: if k >= 1 then ShiftI(shShl, RAX, k) else Imul(RAX, RCX); - sDiv, sMod: if k >= 1 then DivPow2(op, k, unsign) else begin - if unsign then begin MovRI(RDX, 0); Unary(6, RCX) end - else begin - if (t^.size < 8) and ((y.mode <> mConst) or (y.val = -1)) then DivTrap(t); - Cqo; Unary(7, RCX) - end; - if op = sMod then MovRR(RAX, RDX); - end; - sAmp: Alu(aluAnd, RAX, RCX); - sBar: Alu(aluOr, RAX, RCX); - sXor: Alu(aluXor, RAX, RCX); - sShl, sShr: begin - { the count modulo the width: the machine takes it modulo 64 } - if Bits(t) < 64 then AluI(aluAnd, RCX, Bits(t) - 1); - if op = sShl then Shift(shShl, RAX) - else if unsign then Shift(shShr, RAX) else Shift(shSar, RAX); - end; - else MarkAt(Join(x.pos, y.pos), SymText(op) + ' doesn''t apply to ' + TypeName(t)); - end; - Norm(t); - end; - x.mode := mReg; - if op in Rel + [sIn] then x.typ := tBool else x.typ := t; +{ The program goes on if the condition cc holds, and otherwise stops + in Rt.fail(what, a, b, len, at, name), which says what failed at p, + found by at, the address of the call: an index a (what = 0), a slice + a..b (1), each for a length len, a position a of the enumeration + called name (2), or a slice of a pointer a..b that runs backwards + (3). a is in register ra, b in RDX; len is in memory at m, or n if + m.base is NoBase. The failing code has p for its place, and the code + after it the place before it again. } +procedure Check(cc, what: longint; const p: TPos; ra: longint; const m: TMem; n: int64; name: longint); +var L, line, col: longint; before: TLine; +begin + L := NoLabel; + Jcc(cc, L); + before := lines^[numLines - 1]; + LineCol(p.a, line, col); + NoteLine(line, col); + MovRR(RSI, ra); + if m.base = NoBase then MovRI(RCX, n) else Load(RCX, m, 8, false); + Lea(R8, Here); + MovRI(RDI, what); + if name >= 0 then Lea(R9, MemRip(name, 0)); + AluI(aluAnd, RSP, -16); + CallChunk(rtFail); + Ud2; + FixLink(L); + NoteLine(before.line, before.col); end; -{ INT and UINT, the integers as big as an address, through which - integers and pointers convert (report section 6.7) } -function IsWord(t: PType): boolean; +{ For Check: a length known here, not in memory } +function NoMem: TMem; begin - IsWord := Same(t, tInt) or Same(t, tUInt); + NoMem := Mem(NoBase, 0); end; -procedure Convert(var x: TItem; t: PType); -var s: PType; r: double; L1, L2: longint; f: boolean; +{ The index on top is below n, unsigned } +procedure CheckIndex(n: int64; const p: TPos); begin - s := x.typ; - if x.mode in [mType, mBuiltin, mNone, mCase, mStr] then begin - if x.mode = mStr then MarkAt(x.pos, 'can''t convert a string'); - NotValue(x); - end; - if Same(s, t) then exit; - if (IsInt(s) or (s^.form in [fEnum, fSet])) and (t^.form = fInt) then begin - if x.mode = mConst then x.val := Cut(x.val, t) - else begin Value(x); Norm(t) end; - end else if IsInt(s) and (t^.form = fEnum) then begin - if x.mode = mConst then begin - if (x.val < 0) or (x.val >= t^.len) then MarkAt(x.pos, IntStr(x.val) + ' isn''t a position of ' + TypeName(t)) - end else begin Value(x); CmpI(RAX, t^.len); Check(ccB, 2, x.pos, RAX, NoMem, t^.len, NameChunk(t)) end; - end else if IsInt(s) and (t^.form = fSet) then begin - if x.mode = mConst then begin - if t^.len < 64 then x.val := x.val and ((int64(1) shl t^.len) - 1) - end else begin - Value(x); - if t^.len < 64 then begin MovRI(RCX, (int64(1) shl t^.len) - 1); Alu(aluAnd, RAX, RCX) end; - end; - end else if IsInt(s) and (t^.form = fReal) then begin - f := IsF32(t); - if x.mode = mConst then begin - if (s^.form = fInt) and not s^.signed then r := qword(x.val) else r := x.val; - MakeReal(x, r); - RealTo(x, t); - end else begin - Value(x); - if (s^.form = fInt) and not s^.signed and (s^.size = 8) then begin - { above high(I64): halve, keeping the low bit, and double } - L1 := NoLabel; L2 := NoLabel; - TestRR(RAX, RAX); - Jcc(ccS, L1); - Cvtsi2s(0, RAX, f); - Jmp(L2); - FixLink(L1); - MovRR(RCX, RAX); - ShiftI(shShr, RCX, 1); - AluI(aluAnd, RAX, 1); - Alu(aluOr, RCX, RAX); - Cvtsi2s(0, RCX, f); - Sse($58, 0, 0, f); - FixLink(L2); - end else Cvtsi2s(0, RAX, f); - MovqRX(RAX, 0); - end; - end else if (s^.form = fReal) and (t^.form = fReal) then begin - { F32 to F64, F64 to F32, or a real constant to either } - if x.mode = mConst then RealTo(x, t) - else begin - Value(x); MovqXR(0, RAX); Sse($5A, 0, 0, IsF32(s)); MovqRX(RAX, 0) - end; - end else if (s^.form = fReal) and (t^.form = fInt) then begin - if x.mode = mConst then begin - r := RealOf(x); - if (r <> r) or (r >= 9.2233720368547758e18) or (r < -9.2233720368547758e18) then - x.val := Cut(low(int64), t) - else x.val := Cut(trunc(r), t); - end else begin - Value(x); MovqXR(0, RAX); Cvtts2si(RAX, 0, IsF32(s)); Norm(t) - end; - end else if (IsWord(s) or (s^.form in [fConst, fPtr, fProc, fNil])) and (t^.form in [fPtr, fProc]) then begin - if x.mode <> mConst then Value(x); - end else if (s^.form in [fPtr, fProc]) and IsWord(t) then - Value(x) - else - MarkAt(x.pos, 'can''t convert ' + TypeName(s) + ' to ' + TypeName(t)); - x.typ := t; + TopToRax; + CmpI(RAX, n); + Check(ccB, 0, p, RAX, NoMem, n, -1); end; -{ Calls } +{ The integer on top is a position of an enumeration of n names } +procedure CheckEnum(n: int64; name: longint; const p: TPos); +begin + TopToRax; + CmpI(RAX, n); + Check(ccB, 2, p, RAX, NoMem, n, name); +end; -procedure BeginCall(var c: TCall; var x: TItem); +{ 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. } +procedure IndexSlice(const a: TAdr; size: int64; checked: boolean; const p: TPos); +var m, ml: TMem; begin - if x.mode = mProc then begin - c.sig := x.obj^.typ; c.chunk := x.obj^.chunk; c.target := 0; - c.obj := x.obj; c.code := x.obj^.isCode; c.ext := x.obj^.ext; - end else begin - c.obj := nil; c.code := false; c.ext := false; - if x.typ^.form <> fProc then MarkAt(x.pos, 'expected a procedure, found ' + What(x)); - c.sig := x.typ; c.chunk := -1; - c.target := ToSlot(x); + PopTo(RAX); + m := Place(a, RCX); + ml := m; ml.disp := ml.disp + 8; + if checked then begin + AluM(aluCmp, RAX, ml); + Check(ccB, 0, p, RAX, ml, 0, -1); end; - c.param := c.sig^.fields; - c.n := 0; + if size <> 1 then ImulI(RAX, size); + AluM(aluAdd, RAX, m); + Computed(kWord); end; -{ Too many arguments or too few, at p } -procedure WrongCount(var c: TCall; const p: TPos; const what: shortstring); +{ 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. } +procedure Slice(const a: TAdr; isArray: boolean; n, size, tmp: int64; checked: boolean; const p: TPos); +var m, ml: TMem; begin - if c.obj = nil then MarkAt(p, what); - Error(p, what + ': ' + NameOf(c.obj^.name) + ' takes ' + IntStr(c.sig^.len)); - if c.obj^.module <> nil then Note(c.obj^.pos, 'the signature is here'); - Fail; + PopTo(RDX); + PopTo(RCX); + m := Place(a, R8); + ml := m; ml.disp := ml.disp + 8; + if checked then begin + if isArray then begin CmpI(RDX, n); ml := NoMem end + else AluM(aluCmp, RDX, ml); + Check(ccBE, 1, p, RCX, ml, n, -1); + Alu(aluCmp, RCX, RDX); + Check(ccBE, 1, p, RCX, ml, n, -1); + end; + Spill; + MovRR(RAX, RDX); + Alu(aluSub, RAX, RCX); + Store(Mem(RBP, tmp + 8), RAX, 8); + if size <> 1 then ImulI(RCX, size); + if isArray then Lea(RAX, m) else Load(RAX, m, 8, false); + Alu(aluAdd, RAX, RCX); + Store(Mem(RBP, tmp), RAX, 8); end; -procedure PassArg(var c: TCall; var a: TItem); -var p: PObj; s: int64; +{ 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. } +procedure SlicePtr(size, tmp: int64; checked: boolean; const p: TPos); begin - p := c.param; - if c.n > High(c.slots) then MarkAt(a.pos, 'too many arguments'); - if p = nil then begin - { past the parameters of a C procedure that ends in ...: a string - goes as a C string, an integer constant as an INT, a real - constant as an F64; C takes no F32 there } - if not c.sig^.variadic then WrongCount(c, a.pos, 'too many arguments'); - if a.mode = mStr then Coerce(a, tPtrU8) - else if a.typ^.form = fConst then Coerce(a, tInt) - else if a.typ = tRConst then Coerce(a, tReal) - else if IsF32(a.typ) then MarkAt(a.pos, 'an F32 goes to ... as F64(x)') - else if not IsScalar(a.typ) then MarkAt(a.pos, 'only a single value goes to ...'); - c.isF[c.n] := a.typ^.form = fReal; - c.slots[c.n] := ToSlot(a); - inc(c.n); - exit; - end; - c.isF[c.n] := (p^.typ^.form = fReal) and not p^.isVar; - if p^.isVar then begin - NotReadOnly(a); - if (a.mode <> mVar) or not a.isVar then MarkAt(a.pos, 'a var parameter needs a variable'); - if a.odd then MarkAt(a.pos, 'a field of a packed record can''t be a var parameter'); - if not Same(a.typ, p^.typ) then MarkAt(a.pos, 'a var parameter needs exactly ' + TypeName(p^.typ) + ', found ' + What(a)); - if a.vol then MarkAt(a.pos, 'can''t pass through a volatile pointer to a var parameter'); - Address(a, RAX); - s := AllocTemp(8, 8); - Store(Mem(RBP, s), RAX, 8); - end else if IsAggregate(p^.typ) then begin - Coerce(a, p^.typ); - if a.isVar or a.vol or (a.base <> bFrame) then CopyToTemp(a); - Address(a, RAX); - s := AllocTemp(8, 8); - Store(Mem(RBP, s), RAX, 8); - end else begin - Coerce(a, p^.typ); - s := ToSlot(a); + PopTo(RDX); + PopTo(RCX); + PopTo(R8); + if checked then begin + Alu(aluCmp, RCX, RDX); + Check(ccLE, 3, p, RCX, NoMem, 0, -1); end; - c.slots[c.n] := s; - inc(c.n); - c.param := p^.next; + Spill; + MovRR(RAX, RDX); + Alu(aluSub, RAX, RCX); + Store(Mem(RBP, tmp + 8), RAX, 8); + if size <> 1 then ImulI(RCX, size); + MovRR(RAX, R8); + Alu(aluAdd, RAX, RCX); + Store(Mem(RBP, tmp), RAX, 8); end; -procedure EndCall(var c: TCall; var x: TItem); +{ Calls } + +procedure Call(var c: TCall); var - res: PType; i, ni, nf, k, pad: longint; ret: int64; + res: PType; i, ni, nf, k, pad: longint; onStack: array[0..63] of boolean; begin - if c.param <> nil then WrongCount(c, TokPos, 'too few arguments'); + Spill; { the value in rax waits on the stack, past the call } res := c.sig^.base; - ret := 0; + c.ret := 0; ni := 0; nf := 0; if (res <> nil) and IsAggregate(res) then begin - ret := AllocTemp(res^.size, res^.align); + c.ret := AllocTemp(res^.size, res^.align); if not c.code then ni := 1; end; { the System V classes: each argument in the next free register of @@ -1436,7 +917,7 @@ else begin onStack[i] := ni >= 6; if ni < 6 then inc(ni) end; if onStack[i] then inc(k); end; - pad := ord(odd(depth + k)); + pad := ord(odd(pushed + k)); if pad <> 0 then AluI(aluSub, RSP, 8); for i := c.n - 1 downto 0 do if onStack[i] then begin @@ -1444,7 +925,7 @@ Push(RAX); end; ni := 0; nf := 0; - if (ret <> 0) and not c.code then begin Lea(RDI, Mem(RBP, ret)); ni := 1 end; + if (c.ret <> 0) and not c.code then begin Lea(RDI, Mem(RBP, c.ret)); ni := 1 end; for i := 0 to c.n - 1 do if not onStack[i] then if c.isF[i] then begin MovsdXM(nf, Mem(RBP, c.slots[i])); inc(nf) end @@ -1458,142 +939,67 @@ CallR(R11); end; if k + pad > 0 then AluI(aluAdd, RSP, 8 * (k + pad)); - if (ret <> 0) and c.code then begin - Store(Mem(RBP, ret), RAX, 8); - Store(Mem(RBP, ret + 8), RDX, 8); + if (c.ret <> 0) and c.code then begin + Store(Mem(RBP, c.ret), RAX, 8); + Store(Mem(RBP, c.ret + 8), RDX, 8); end; - FillChar(x, SizeOf(x), 0); - if res = nil then begin - x.mode := mNone; x.typ := tNone; x.obj := c.obj - end else if ret <> 0 then - TempItem(x, res, ret) - else begin - x.mode := mReg; x.typ := res; + if (res <> nil) and (c.ret = 0) then begin if res^.form = fReal then MovqRX(RAX, 0) else if res^.form = fBool then Extend(RAX, 1, false) - else Norm(res); + else if (res^.form = fInt) and (res^.size < 8) then Extend(RAX, res^.size, res^.signed); + Computed(KindOf(res)); end; end; -{ Variants } +{ Frames } -{ A temporary of type t, all zero: for variants and record literals. } -procedure ZeroTemp(var x: TItem; t: PType); -var tmp: int64; +function AllocTemp(size, align: int64): int64; begin - tmp := AllocTemp(t^.size, t^.align); - Lea(RDI, Mem(RBP, tmp)); - MovRI(RCX, t^.size); - MovRI(RAX, 0); - RepStosb; - TempItem(x, t, tmp); + if align < 1 then align := 1; + frameTop := AlignUp(frameTop + size, align); + if frameTop > frameMax then frameMax := frameTop; + AllocTemp := -frameTop; end; -procedure Construct(var x: TItem; c: PObj); +function AllocPerm(size, align: int64): int64; begin - ZeroTemp(x, c^.typ); - MovRI(RAX, c^.val); - Store(Mem(RBP, x.off), RAX, 8); + AllocPerm := AllocTemp(size, align); + permTop := frameTop; end; -procedure SetField(const x: TItem; f: PObj; var a: TItem); +function TempMark: int64; begin - Coerce(a, f^.typ); - if IsScalar(f^.typ) then begin - Value(a); - Store(Mem(RBP, x.off + f^.val), RAX, ScalarSize(f^.typ)); - end else begin - if a.vol then MarkAt(a.pos, 'can''t copy through a volatile pointer'); - Address(a, RSI); - Lea(RDI, Mem(RBP, x.off + f^.val)); - Copy(f^.typ^.size); - end; + TempMark := frameTop; end; -{ The slot match tests: a variant's address, or an enumeration's value. } -function MatchBegin(var x: TItem): int64; -var p: int64; +procedure ReleaseTemps(m: int64); begin - if x.typ^.form in [fEnum, fInt] then exit(ToSlot(x)); - if (x.mode <> mVar) or (x.typ^.form <> fVariant) then MarkAt(x.pos, 'match needs a variant, an enumeration or an integer, found ' + What(x)); - if x.ro then CopyToTemp(x); { its arms' names stand for a copy's fields } - Address(x, RAX); - p := AllocTemp(8, 8); - Store(Mem(RBP, p), RAX, 8); - MatchBegin := p; + if m < permTop then m := permTop; + frameTop := m; end; -procedure MatchTag(p: int64; tag: int64; var L: longint; isEnum: boolean); +{ Every slot used so far stays reserved for the rest of the procedure: + a deferred statement's temporaries live until it runs. } +procedure KeepTemps; begin - Load(RAX, Mem(RBP, p), 8, false); - if not isEnum then Load(RAX, Mem(RAX, 0), 8, false); - CmpI(RAX, tag); - Jcc(ccNE, L); + frameTop := frameMax; + permTop := frameMax; end; -{ To body if the integer in slot p is from lo to hi: less its lo, it is - then at most hi - lo, compared unsigned, which holds for a signed type - or not, with no second jump. } -procedure MatchRange(p, lo, hi: int64; var body: longint); -begin - Load(RAX, Mem(RBP, p), 8, false); - if lo = hi then begin - CmpI(RAX, lo); - Jcc(ccE, body); - exit; - end; - if lo <> 0 then begin MovRI(RCX, lo); Alu(aluSub, RAX, RCX) end; - CmpI(RAX, hi - lo); - Jcc(ccBE, body); -end; - -{ The end of a round of a for loop: stop if the step would pass the - limit, else step. Counting the distance left, rather than comparing - after the step, can't be fooled by the variable wrapping around. } -procedure ForNext(o: PObj; bslot, step: int64; var exitL: longint; top: longint); -var v, w: TItem; -begin - MakeItem(w, o); - Value(w); - Load(RCX, Mem(RBP, bslot), 8, false); - if step > 0 then begin - Alu(aluSub, RCX, RAX); - CmpI(RCX, step); - end else begin - Alu(aluSub, RAX, RCX); - CmpI(RAX, -step); - end; - Jcc(ccB, exitL); - MakeItem(v, o); - Save(v); - MakeItem(w, o); - Value(w); - MovRI(RCX, step); - Alu(aluAdd, RAX, RCX); - Norm(o^.typ); - Assign(v, w); - JmpBack(top); -end; - -procedure CondJump(var x: TItem; var L: longint); -begin - if x.typ^.form <> fBool then MarkAt(x.pos, 'a condition is a BOOL, found ' + What(x)); - Value(x); - TestRR(RAX, RAX); - Jcc(ccE, L); -end; - -{ Procedures } - +{ 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). } procedure BeginProc(sig: PType; params: PObj); var p: PObj; ni, nf: longint; stackOff: int64; f: boolean; begin - frameTop := 0; frameMax := 0; permTop := 0; depth := 0; + frameTop := 0; frameMax := 0; permTop := 0; + ResetStack(0, 0); exitL := NoLabel; numIn := 0; - result := sig^.base; + resType := sig^.base; ni := 0; nf := 0; stackOff := 16; - if (result <> nil) and IsAggregate(result) then begin + if (resType <> nil) and IsAggregate(resType) then begin retSlot := AllocPerm(8, 8); inReg[0] := RDI; inSlot[0] := retSlot; inSize[0] := 8; numIn := 1; ni := 1; @@ -1607,7 +1013,9 @@ if f then begin inReg[numIn] := -1 - nf; inc(nf) end else begin inReg[numIn] := IntRegs[ni]; inc(ni) end; inSlot[numIn] := p^.val; - if p^.ind then inSize[numIn] := 8 else inSize[numIn] := ScalarSize(p^.typ); + if p^.ind then inSize[numIn] := 8 + else if p^.typ^.form in [fInt, fBool, fEnum, fSet, fReal] then inSize[numIn] := p^.typ^.size + else inSize[numIn] := 8; inc(numIn); end else begin p^.val := stackOff; @@ -1618,10 +1026,10 @@ paramTop := frameTop; end; -{ The prologue, which is for the procedure's first line. } -{ Only the locals are zeroed: the parameters are stored over their - slots next, and every temporary is written before it is read. The - locals are all declared by now, below the parameters' slots. } +{ The prologue, which is for the procedure's first line. Only the + locals are zeroed: the parameters are stored over their slots next, + and every temporary is written before it is read. The locals are all + declared by now, below the parameters' slots. } procedure EnterBody(c, line: longint); var i, top: longint; n: int64; begin @@ -1649,127 +1057,48 @@ else Store(Mem(RBP, inSlot[i]), inReg[i], inSize[i]); end; -procedure ReturnValue(var x: TItem); +{ Pops one of several results, a value of size bytes, into its place + off bytes into the caller's, behind the hidden pointer. } +procedure ResultTo(off: int64; size: longint); begin - if result = nil then MarkAt(x.pos, 'this procedure returns nothing'); - Coerce(x, result); - if IsAggregate(result) then begin - if x.vol then MarkAt(x.pos, 'can''t copy through a volatile pointer'); - Address(x, RSI); - Load(RDI, Mem(RBP, retSlot), 8, false); - Copy(result^.size); - Load(RAX, Mem(RBP, retSlot), 8, false); - end else Value(x); + PopTo(RAX); + Load(RCX, Mem(RBP, retSlot), 8, false); + Store(Mem(RCX, off), RAX, size); end; -{ One of several results, into its place behind the hidden pointer. } -procedure ReturnField(f: PObj; var x: TItem); -begin - Coerce(x, f^.typ); - if IsScalar(f^.typ) then begin - Value(x); - Load(RCX, Mem(RBP, retSlot), 8, false); - Store(Mem(RCX, f^.val), RAX, ScalarSize(f^.typ)); - end else begin - if x.vol then MarkAt(x.pos, 'can''t copy through a volatile pointer'); - Address(x, RSI); - Load(RDI, Mem(RBP, retSlot), 8, false); - Lea(RDI, Mem(RDI, f^.val)); - Copy(f^.typ^.size); - end; -end; - -{ Several results at once, the call's that return f(x) passes on. } -procedure ReturnAll(var x: TItem); +{ Pops an address, and copies size bytes from it to the result, off + bytes into it. } +procedure CopyResult(off, size: int64); begin - Address(x, RSI); + PopTo(RSI); Load(RDI, Mem(RBP, retSlot), 8, false); - Copy(result^.size); + if off <> 0 then Lea(RDI, Mem(RDI, off)); + CopyBytes(size); end; -{ With the result in rax, as ReturnValue left it. } +{ return: the result, a value on top, goes in rax or xmm0; one behind + the hidden pointer goes back with that pointer in rax. } procedure ReturnJump; begin - if IsAggregate(result) then Load(RAX, Mem(RBP, retSlot), 8, false) - else if result^.form = fReal then MovqXR(0, RAX); + if resType <> nil then + if IsAggregate(resType) then Load(RAX, Mem(RBP, retSlot), 8, false) + else begin + PopTo(RAX); + if resType^.form = fReal then MovqXR(0, RAX); + end; Jmp(exitL); end; -{ Keeps a variable's address in a frame slot, rather than in a register - or on the stack, while other code runs. } -procedure Pin(var x: TItem); -var s: int64; -begin - if (x.mode = mVar) and (x.base in [bReg, bStack]) then begin - Address(x, RAX); - s := AllocTemp(8, 8); - Store(Mem(RBP, s), RAX, 8); - x.base := bSlot; - x.chunk := s; - end; -end; - -procedure IncDec(var v, k: TItem; dec: boolean); -var n: longint; -begin - CoerceExact(k, v.typ, ''); - Value(k); - MovRR(RCX, RAX); - Address(v, RDX); - n := ScalarSize(v.typ); - Load(RAX, Mem(RDX, 0), n, v.typ^.signed); - if dec then Alu(aluSub, RAX, RCX) else Alu(aluAdd, RAX, RCX); - Store(Mem(RDX, 0), RAX, n); -end; - -{ An error is the address of its length, followed by its message. } -function ErrorChunk(var x: TItem; module, name: longint): longint; -var c: longint; p: PBytes; -begin - if x.mode <> mStr then MarkAt(x.pos, 'an error is made from a string'); - p := GetMem(x.val + 8); - PInt64(p)^ := x.val; - Move(rodata^[chunks^[x.chunk].start], p^[8], x.val); - c := NewChunk(secRodata, module, name); - SetData(c, p, x.val + 8, 8); - FreeMem(p); - ErrorChunk := c; -end; - -procedure Msg(var x: TItem); -var L: longint; s: int64; -begin - Coerce(x, tError); - Value(x); - s := AllocTemp(16, 8); - MovRI(RCX, 0); - L := NoLabel; - TestRR(RAX, RAX); - Jcc(ccE, L); - Load(RCX, Mem(RAX, 0), 8, false); - Lea(RAX, Mem(RAX, 8)); - FixLink(L); - Store(Mem(RBP, s), RAX, 8); - Store(Mem(RBP, s + 8), RCX, 8); - TempItem(x, tBytes, s); -end; - -procedure ReturnNone; -begin - if result <> nil then Mark('return needs a result of ' + TypeName(result)); - Jmp(exitL); -end; - procedure EndProc(c: longint); var n: int64; begin codeChunk := -1; - if depth <> 0 then Fatal('internal error: stack depth'); + if (depth <> 0) or (pushed <> 0) then Fatal('internal error: stack depth'); { running off the end returns zeros } - if result <> nil then - if IsAggregate(result) then begin + if resType <> nil then + if IsAggregate(resType) then begin Load(RDI, Mem(RBP, retSlot), 8, false); - MovRI(RCX, result^.size); + MovRI(RCX, resType^.size); MovRI(RAX, 0); RepStosb; Load(RAX, Mem(RBP, retSlot), 8, false); @@ -1785,6 +1114,93 @@ if n > high(longint) then Mark('frame too big'); Put4At(frameFix, n); EndChunk(c); +end; + +{ A deferred statement is compiled where it stands, as a subroutine of + its procedure that the code jumps over; DeferBegin gives its address + and starts it, with the return address pushed. The stack is empty + where it is called, and where it begins. } +function DeferBegin(var L, saved: longint): longint; +begin + Jmp(L); + saved := pushed; + pushed := 1; + DeferBegin := pc; +end; + +procedure DeferEnd(L, saved: longint); +begin + KeepTemps; + Ret; + FixLink(L); + pushed := saved; end; +procedure RunDefer(at: longint); +begin + 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 Rt C's exit, in cExit. } +function EntryPoint(dynamic: boolean; first: PModule; main: PObj; cExit, places, placesVar, exitProc: longint): longint; +var entry, start: longint; m: PModule; +begin + entry := NewChunk(secText, -1, Intern('_start', 6)); + if dynamic then begin + start := NewChunk(secText, -1, Intern('main', 4)); + BeginChunk(entry); + MovRI(RBP, 0); + MovRR(R9, RDX); + Pop(RSI); + MovRR(RDX, RSP); + AluI(aluAnd, RSP, -16); + Push(RAX); + Push(RSP); + MovRI(R8, 0); + MovRI(RCX, 0); + Lea(RDI, MemRip(start, 0)); + CallM(MemRip(ExternChunk(Intern('__libc_start_main', 17)), 0)); + Ud2; + EndChunk(entry); + BeginChunk(start); + Push(RBP); { aligns the stack again } + Store(MemRip(argcChunk, 0), RDI, 8); + Store(MemRip(argvChunk, 0), RSI, 8); + Load(RAX, MemRip(ExternChunk(Intern('exit', 4)), 0), 8, false); + Store(MemRip(cExit, 0), RAX, 8); + end else begin + start := entry; + BeginChunk(entry); + Load(RAX, Mem(RSP, 0), 8, false); + Store(MemRip(argcChunk, 0), RAX, 8); + Lea(RAX, Mem(RSP, 8)); + Store(MemRip(argvChunk, 0), RAX, 8); + end; + Lea(RAX, MemRip(places, 0)); + Store(MemRip(placesVar, 0), RAX, 8); + m := first; + while m <> nil do begin + if m^.used and (m^.body >= 0) then CallChunk(m^.body); + m := m^.next; + end; + if main <> nil then CallChunk(main^.chunk); + if (main <> nil) and (main^.typ^.base <> nil) then MovRR(RDI, RAX) else MovRI(RDI, 0); + CallChunk(exitProc); + Ud2; + EndChunk(start); + EntryPoint := entry; +end; + +initialization + inRax := -1; + rtFail := NewChunk(secText, Intern('Rt', 2), Intern('fail', 4)); + argcChunk := NewChunk(secBss, -1, Intern('argc', 4)); + SetBss(argcChunk, 8, 8); + argvChunk := NewChunk(secBss, -1, Intern('argv', 4)); + SetBss(argvChunk, 8, 8); end. diff --git a/src/item.pas b/src/item.pas new file mode 100644 index 0000000..44d5156 --- /dev/null +++ b/src/item.pas @@ -0,0 +1,1303 @@ +{ item.pas: operands, their types, and what they mean. + + The parser describes each operand as an item (TItem), as in Wirth's + compilers: a constant, a variable at an address it can name, a value + on gen's stack, a procedure, a string. The routines here check the + items' types, fold constants, and have gen.pas make the code, as calls + of its stack machine; nothing here knows the machine. + + Depends on: scan for errors, sym for types, chunk for data, gen for + code. + Leaves out: the language's syntax, which is parse.pas; the machine, + which is gen.pas. } + +unit item; + +{$mode objfpc}{$H-} + +interface + +uses scan, diag, sym, chunk, gen; + +type + TMode = (mConst, mVar, mStack, mProc, mType, mStr, mBuiltin, mCase, mNone); + + TItem = record + mode: TMode; + typ: PType; + val: int64; { mConst: the value, an F64's bits; mStr: its length } + base: TBase; { mVar: what the address is relative to } + chunk: longint; { mVar with bGlobal, mStr: the chunk; bSlot: the slot } + off: int64; { mVar: added to the base } + vol: boolean; { mVar: reached through ^VOLATILE } + isVar: boolean; { mVar: a variable of the program, not a temporary } + odd: boolean; { mVar: in a packed record, so maybe misaligned } + ro: boolean; { mVar: another module's exported variable, or part + of one, which only that module changes } + obj: PObj; { mProc, mBuiltin, mCase; mVar: the variable named } + pos: TPos; { where it is in the source, for messages } + end; + +var + checks: boolean; { the module's index and slice checks are made: it + doesn't say check off } + +procedure MakeConst(var x: TItem; t: PType; v: int64); +function What(const x: TItem): shortstring; +procedure MakeReal(var x: TItem; r: double); +procedure MakeStr(var x: TItem); +procedure MakeItem(var x: TItem; o: PObj); +function RealOf(const x: TItem): double; +function FrameAdr(off: int64): TAdr; +function GlobalAdr(c: longint): TAdr; +function AdrOf(const x: TItem): TAdr; + +procedure UsesReals(const p: TPos); +procedure Value(var x: TItem); +procedure Address(var x: TItem); +procedure Discard(const x: TItem); +procedure Coerce(var x: TItem; t: PType); +procedure CoerceExact(var x: TItem; t: PType; const help: shortstring); +procedure NotReadOnly(const x: TItem); +procedure Assign(var dst, src: TItem); +procedure CopyToTemp(var x: TItem); +function ToSlot(var x: TItem): int64; + +procedure Deref(var x: TItem); +procedure Field(var x: TItem; f: PObj); +procedure IndexPrep(var x: TItem); +procedure Index(var x, y: TItem); +procedure SliceLo(var lo: TItem); +procedure Slice(var x, lo, hi: TItem); + +procedure Neg(var x: TItem); +procedure NotOp(var x: TItem); +procedure Complement(var x: TItem); +procedure Op1(op: TSym; var x: TItem; var L: longint); +procedure Op2(op: TSym; var x, y: TItem; L: longint); +function IsWord(t: PType): boolean; +procedure Convert(var x: TItem; t: PType); + +procedure BeginCall(var c: TCall; var x: TItem); +procedure PassArg(var c: TCall; var a: TItem); +procedure EndCall(var c: TCall; var x: TItem); + +procedure ZeroTemp(var x: TItem; t: PType); +procedure Construct(var x: TItem; c: PObj); +procedure SetField(const x: TItem; f: PObj; var a: TItem); +function MatchBegin(var x: TItem): int64; +procedure MatchTag(p: int64; tag: int64; var L: longint; isEnum: boolean); +procedure MatchRange(p, lo, hi: int64; var body: longint); +procedure CondJump(var x: TItem; var L: longint); + +procedure SliceOf(var x: TItem; t: PType; len: int64); +procedure TempItem(var x: TItem; t: PType; off: int64); +function ScalarSize(t: PType): longint; +procedure ForNext(o: PObj; bslot, step: int64; var exitL: longint; top: longint); + +procedure BeginProc(sig: PType; params: PObj); +procedure ReturnValue(var x: TItem); +procedure ReturnField(f: PObj; var x: TItem); +procedure ReturnAll(var x: TItem); +procedure ReturnNone; +procedure Pin(var x: TItem); +procedure IncDec(var v, k: TItem; dec: boolean); +procedure Msg(var x: TItem); +function ErrorChunk(var x: TItem; module, name: longint): longint; + +implementation + +var + result: PType; { the result of the procedure being compiled, or nil } + +{ Items } + +procedure MakeConst(var x: TItem; t: PType; v: int64); +var p: TPos; +begin + p := x.pos; + FillChar(x, SizeOf(x), 0); + x.pos := p; + x.mode := mConst; + x.typ := t; + x.val := v; +end; + +{ A real constant: untyped, unless typed later. Its value is an F64, + which for an F32 is one an F32 can hold. } +procedure MakeReal(var x: TItem; r: double); +begin + MakeConst(x, tRConst, 0); + Move(r, x.val, 8); +end; + +function IsF32(t: PType): boolean; +begin + IsF32 := (t^.form = fReal) and (t^.size = 4); +end; + +{ Gives a real constant the real type t, rounded to it. } +procedure RealTo(var x: TItem; t: PType); +var r: double; +begin + r := RealOf(x); + if IsF32(t) then MakeReal(x, single(r)) else MakeReal(x, r); + x.typ := t; +end; + +function RealOf(const x: TItem): double; +var r: double; +begin + Move(x.val, r, 8); + RealOf := r; +end; + +{ The current string literal, as an item of its own chunk. } +procedure MakeStr(var x: TItem); +begin + FillChar(x, SizeOf(x), 0); + x.mode := mStr; + x.typ := tStr; + x.val := slen; + x.chunk := NewChunk(secRodata, -1, -1); + SetData(x.chunk, @sbuf, slen + 1, 1); +end; + +function FrameAdr(off: int64): TAdr; +begin + FrameAdr.base := bFrame; + FrameAdr.chunk := -1; + FrameAdr.off := off; +end; + +function GlobalAdr(c: longint): TAdr; +begin + GlobalAdr.base := bGlobal; + GlobalAdr.chunk := c; + GlobalAdr.off := 0; +end; + +{ Where the variable x is, for gen } +function AdrOf(const x: TItem): TAdr; +begin + AdrOf.base := x.base; + AdrOf.chunk := x.chunk; + AdrOf.off := x.off; +end; + +{ An item for "found ...": a constant without a type of its own as it + is written, so that "found 1.5" says what is wrong; else its type. } +function What(const x: TItem): shortstring; +begin + if (x.mode = mConst) and ((x.typ = tConst) or (x.typ = tRConst)) then What := Source(x.pos) + else What := TypeName(x.typ); +end; + +{ Two operands of different types. Numbers convert, so say how. } +procedure Mismatch(const x, y: TItem; xt, yt: PType); +var msg: shortstring; +begin + msg := TypeName(xt) + ' and ' + TypeName(yt) + ' are different types'; + if (IsInt(xt) or (xt^.form = fReal)) and (IsInt(yt) or (yt^.form = fReal)) + and (xt <> tConst) and (xt <> tRConst) then + MarkHelp(Join(x.pos, y.pos), msg, 'convert one to the other''s type, as in ' + TypeName(xt) + '(' + Source(y.pos) + ')') + else MarkAt(Join(x.pos, y.pos), msg); +end; + +{ An item that is not a value, by what it is. } +procedure NotValue(const x: TItem); +begin + case x.mode of + mType: MarkAt(x.pos, TypeName(x.typ) + ' is a type, not a value'); + mBuiltin: MarkAt(x.pos, NameOf(x.obj^.name) + ' is a built-in procedure, not a value'); + mCase: MarkAt(x.pos, NameOf(x.obj^.name) + ' is a case, not a value'); + mNone: + if x.obj <> nil then MarkAt(x.pos, NameOf(x.obj^.name) + ' returns nothing') + else MarkAt(x.pos, 'the procedure returns nothing'); + else MarkAt(x.pos, 'a string can''t be an operand'); + end; +end; + +procedure MakeItem(var x: TItem; o: PObj); +begin + FillChar(x, SizeOf(x), 0); + x.typ := o^.typ; + x.obj := o; + case o^.cls of + oConst: + if o^.typ = tStr then begin + x.mode := mStr; x.val := o^.val; x.chunk := o^.chunk + end else if o^.typ^.form = fArray then begin + { an array constant: a variable in read-only data, not one of + the program's, so nothing can change it } + x.mode := mVar; x.base := bGlobal; x.chunk := o^.chunk + end else begin + x.mode := mConst; x.val := o^.val + end; + oVar: begin + x.mode := mVar; + x.ro := (o^.lev = 0) and (o^.module <> curModule); + x.isVar := not x.ro; + if o^.ext then begin + PushVar(GlobalAdr(o^.chunk), 8, false, kWord); + x.base := bStack; + end else if o^.lev = 0 then begin + x.base := bGlobal; x.chunk := o^.chunk + end else if o^.ind then begin + x.base := bSlot; x.chunk := o^.val; x.off := o^.off; + end else begin + x.base := bFrame; x.off := o^.val + end; + end; + oProc: x.mode := mProc; + oType: x.mode := mType; + oBuiltin: x.mode := mBuiltin; + oCase: x.mode := mCase; + else Mark(NameOf(o^.name) + ' is not a value'); + end; +end; + +function ScalarSize(t: PType): longint; +begin + if t^.form in [fInt, fBool, fEnum, fSet, fReal] then ScalarSize := t^.size + else ScalarSize := 8; +end; + +{ The width an operation on t is brought back to, and whether signed } +function IntSize(t: PType): longint; +begin + if t^.form = fInt then IntSize := t^.size else IntSize := 8; +end; + +function Signed(t: PType): boolean; +begin + Signed := ((t^.form = fInt) and t^.signed) or (t^.form = fConst); +end; + +function Cut(v: int64; t: PType): int64; +begin + Cut := v; + if t^.form <> fInt then exit; + case t^.size of + 1: if t^.signed then Cut := shortint(v) else Cut := byte(v); + 2: if t^.signed then Cut := smallint(v) else Cut := word(v); + 4: if t^.signed then Cut := longint(v) else Cut := longword(v); + end; +end; + +{ Code computing with a real is noted on its chunk, at the first place, + for a target without reals (report 5.1) to refuse if the chunk turns + out to be used. A real moved whole, as a record's bytes are copied, + needs nothing the target lacks, and isn't noted. } +procedure UsesReals(const p: TPos); +begin + if (codeChunk >= 0) and not chunks^[codeChunk].reals then begin + chunks^[codeChunk].reals := true; + chunks^[codeChunk].realsAt := p; + end; +end; + +{ x's value, on top of the stack } +procedure Value(var x: TItem); +var f: single; +begin + if x.typ^.form = fReal then UsesReals(x.pos); + case x.mode of + mConst: + if (x.typ^.form = fError) and (x.val > 0) then PushAdr(GlobalAdr(x.val - 1)) + else if IsF32(x.typ) then begin + f := RealOf(x); + PushConst(kF32, PLongword(@f)^); + end else PushConst(KindOf(x.typ), x.val); + mVar: begin + if not IsScalar(x.typ) then MarkAt(x.pos, 'expected a single value, found ' + What(x)); + PushVar(AdrOf(x), ScalarSize(x.typ), (x.typ^.form = fInt) and x.typ^.signed, KindOf(x.typ)); + end; + mStack: ; + mProc: begin + if x.obj^.isCode and (x.obj^.typ^.base <> nil) and x.obj^.typ^.base^.tuple then + MarkAt(x.pos, 'a code procedure with two results can only be called'); + PushProc(x.obj^.chunk, x.obj^.ext); + end; + else NotValue(x); + end; + x.mode := mStack; +end; + +{ The address of the variable or string x, on top of the stack } +procedure Address(var x: TItem); +begin + if x.mode = mStr then PushAdr(GlobalAdr(x.chunk)) + else if x.mode = mVar then begin + PushAdr(AdrOf(x)); + x.base := bStack; x.off := 0; + end else MarkAt(x.pos, 'expected a variable'); +end; + +{ x isn't wanted: what it has on the stack is dropped } +procedure Discard(const x: TItem); +begin + if (x.mode = mStack) or ((x.mode = mVar) and (x.base = bStack)) then Drop; +end; + +{ Frames } + +procedure TempItem(var x: TItem; t: PType; off: int64); +var p: TPos; +begin + p := x.pos; + FillChar(x, SizeOf(x), 0); + x.pos := p; + x.mode := mVar; x.typ := t; x.base := bFrame; x.off := off; +end; + +function ToSlot(var x: TItem): int64; +var s: int64; +begin + Value(x); + s := AllocTemp(8, 8); + PopVar(FrameAdr(s), 8); + ToSlot := s; +end; + +{ Copying } + +procedure CopyToTemp(var x: TItem); +var t: int64; +begin + if x.vol then MarkAt(x.pos, 'can''t copy through a volatile pointer'); + t := AllocTemp(x.typ^.size, x.typ^.align); + Address(x); + CopyTo(FrameAdr(t), x.typ^.size); + TempItem(x, x.typ, t); +end; + +{ A slice made from an address on the stack and a length. } +procedure SliceOf(var x: TItem; t: PType; len: int64); +var s: int64; +begin + s := AllocTemp(16, 8); + PopVar(FrameAdr(s), 8); + PushConst(kWord, len); + PopVar(FrameAdr(s + 8), 8); + TempItem(x, t, s); +end; + +{ An INT goes silently into an I64, and a UINT into a U64, losing + nothing on any target (report section 5.10). } +function Widens(s, t: PType): boolean; +begin + Widens := ((s = tInt) and Same(t, tI64)) or ((s = tUInt) and Same(t, tU64)); +end; + +{ Another module's exported variable can be read, not changed, nor + handed to anything that could change it (report section 3). } +procedure NotReadOnly(const x: TItem); +begin + if x.ro then MarkAt(x.pos, Source(x.pos) + ' is ' + NameOf(x.obj^.module^.name) + '''s, and can''t be changed outside it'); +end; + +procedure Coerce(var x: TItem; t: PType); +var s: PType; tmp: int64; +begin + s := x.typ; + if x.mode = mStr then begin + if (t^.form = fSlice) and (t^.base = tU8) then begin + Address(x); SliceOf(x, t, x.val) + end else if (t^.form = fPtr) and (t^.base = tU8) then begin + Address(x); x.mode := mStack; x.typ := t + end else if (t^.form = fArray) and (t^.base = tU8) and (t^.len >= x.val) then begin + tmp := AllocTemp(t^.size, 1); + Address(x); + CopyTo(FrameAdr(tmp), x.val); + if t^.len > x.val then ZeroVar(FrameAdr(tmp + x.val), t^.len - x.val); + TempItem(x, t, tmp); + end else MarkAt(x.pos, 'can''t use a string as ' + TypeName(t)); + exit; + end; + if x.mode in [mType, mBuiltin, mNone, mCase] then NotValue(x); + if Same(s, t) then exit; + if Widens(s, t) then x.typ := t { the same bits, on a 64-bit target } + else if (s = tRConst) and (t^.form = fReal) then RealTo(x, t) + else if (s^.form = fConst) and (t^.form = fInt) then begin + if (x.mode = mConst) and not Fits(x.val, t) then MarkAt(x.pos, IntStr(x.val) + ' doesn''t fit ' + TypeName(t)); + x.typ := t; + end else if (s^.form = fNil) and (t^.form in [fPtr, fProc, fError]) then + x.typ := t + else if (s^.form = fPtr) and (t^.form = fPtr) and t^.vol and not s^.vol + and Same(s^.base, t^.base) then + x.typ := t + else if (s^.form = fArray) and (t^.form = fSlice) and Same(s^.base, t^.base) then begin + NotReadOnly(x); + if x.vol then MarkAt(x.pos, 'can''t make a slice through a volatile pointer'); + if x.odd then MarkAt(x.pos, 'can''t make a slice of a field of a packed record'); + Address(x); + SliceOf(x, t, s^.len); + end else + MarkAt(x.pos, 'can''t use ' + TypeName(s) + ' as ' + TypeName(t)); +end; + +{ Coerce where the types must be the same, as in a for loop, INC and + several results, which don't widen an INT to an I64 (report sections + 5.10, 6.1 and 7.2); help, if not empty, says why. } +procedure CoerceExact(var x: TItem; t: PType; const help: shortstring); +var h: shortstring; +begin + if Widens(x.typ, t) then begin + h := help; + if h = '' then h := 'they don''t mix here: write ' + TypeName(t) + '(' + Source(x.pos) + ')'; + MarkHelp(x.pos, 'expected ' + TypeName(t) + ', found ' + What(x), h); + end; + Coerce(x, t); +end; + +{ dst := src. The address of dst, if it has to be computed, is on the + stack already, under src's. } +procedure Assign(var dst, src: TItem); +begin + Coerce(src, dst.typ); + if IsScalar(dst.typ) then begin + Value(src); + PopVar(AdrOf(dst), ScalarSize(dst.typ)); + end else begin + if dst.vol or src.vol then MarkAt(src.pos, 'can''t copy through a volatile pointer'); + Address(src); + if dst.base = bStack then CopyBlock(dst.typ^.size, dst.off) + else CopyTo(AdrOf(dst), dst.typ^.size); + end; +end; + +{ t's name, ending in a zero byte, for Rt.fail } +function NameChunk(t: PType): longint; +var s: shortstring; c: longint; +begin + s := TypeName(t) + #0; + c := NewChunk(secRodata, -1, -1); + SetData(c, @s[1], length(s), 1); + NameChunk := c; +end; + +{ Selectors } + +procedure Deref(var x: TItem); +var t: PType; +begin + t := x.typ; + if t^.form <> fPtr then MarkAt(x.pos, 'expected a pointer, found ' + TypeName(t)); + if t^.base = nil then MarkAt(x.pos, TypeName(t) + ' points to a type never declared'); + Value(x); + x.mode := mVar; x.base := bStack; x.off := 0; + x.typ := t^.base; x.vol := t^.vol; x.isVar := true; x.odd := false; x.ro := false; +end; + +{ A field of a packed record, of more than one byte's alignment, may + sit anywhere; it is read and written, but has no address and no + volatile access, which a machine that can't reach a misaligned word + couldn't make one access (report section 5.5). } +procedure Field(var x: TItem; f: PObj); +begin + if x.typ^.packd and (f^.typ^.align > 1) then begin + if x.vol then MarkAt(x.pos, 'a field of a packed record can''t be volatile'); + x.odd := true; + end; + x.off := x.off + f^.val; + x.typ := f^.typ; +end; + +procedure IndexPrep(var x: TItem); +begin + if x.mode = mStr then Coerce(x, tBytes); + if (x.typ^.form = fPtr) and (x.typ^.base^.form = fArray) then + MarkAt(x.pos, 'a pointer to an array is indexed as p^[i]'); + if x.typ^.form = fPtr then Value(x) + else if not ((x.mode = mVar) and (x.typ^.form in [fArray, fSlice])) then + MarkAt(x.pos, 'expected an array, a slice or a pointer, found ' + What(x)); +end; + +{ The index on top, times the size of an element } +procedure ScaleBy(s: int64); +begin + if s <> 1 then begin + PushConst(kWord, s); + gen.Op(sTimes, kWord, 8, true); + end; +end; + +procedure Index(var x, y: TItem); +var t: PType; s: int64; +begin + t := x.typ; + s := t^.base^.size; + if not IsInt(y.typ) then MarkAt(y.pos, 'an index is an integer, found ' + What(y)); + if t^.form = fPtr then begin + Value(y); + ScaleBy(s); + gen.Op(sPlus, kWord, 8, false); + x.mode := mVar; x.base := bStack; x.off := 0; + x.vol := t^.vol; x.isVar := true; x.odd := false; x.ro := false; + end else if (t^.form = fArray) and (y.mode = mConst) then begin + if (y.val < 0) or (y.val >= t^.len) then MarkAt(y.pos, 'index ' + IntStr(y.val) + ' is out of range for a length of ' + IntStr(t^.len)); + x.off := x.off + y.val * s; + end else if t^.form = fArray then begin + Value(y); + if checks then CheckIndex(t^.len, y.pos); + ScaleBy(s); + if x.base <> bStack then begin PushAdr(AdrOf(x)); x.off := 0 end; + gen.Op(sPlus, kWord, 8, false); + x.base := bStack; + end else begin + Value(y); + IndexSlice(AdrOf(x), s, checks, y.pos); + x.base := bStack; x.off := 0; x.isVar := true; x.vol := false; x.ro := false; + end; + x.typ := t^.base; +end; + +procedure SliceLo(var lo: TItem); +begin + if not IsInt(lo.typ) then MarkAt(lo.pos, 'an index is an integer, found ' + What(lo)); + Value(lo); +end; + +procedure Slice(var x, lo, hi: TItem); +var t, st: PType; tmp: int64; +begin + t := x.typ; + if not IsInt(hi.typ) then MarkAt(hi.pos, 'an index is an integer, found ' + What(hi)); + if x.vol then MarkAt(x.pos, 'can''t make a slice through a volatile pointer'); + if x.odd then MarkAt(x.pos, 'can''t make a slice of a field of a packed record'); + if t^.form = fArray then NotReadOnly(x); + Value(hi); + tmp := AllocTemp(16, 8); + if t^.form = fPtr then SlicePtr(t^.base^.size, tmp, checks, lo.pos) + else gen.Slice(AdrOf(x), t^.form = fArray, t^.len, t^.base^.size, tmp, checks, lo.pos); + st := NewType(fSlice, 16, 8); + st^.base := t^.base; + TempItem(x, st, tmp); +end; + +{ Operators } + +procedure Neg(var x: TItem); +begin + if x.typ^.form = fReal then begin + if x.mode = mConst then x.val := x.val xor low(int64) + else begin Value(x); gen.Neg(KindOf(x.typ), 8, false) end; + end else if IsInt(x.typ) then begin + if (x.mode = mConst) and (x.typ^.form = fConst) and (x.val = low(int64)) then + MarkAt(x.pos, 'the constant is too big for I64') + else if x.mode = mConst then x.val := Cut(-x.val, x.typ) + else begin Value(x); gen.Neg(kWord, IntSize(x.typ), Signed(x.typ)) end; + end else MarkAt(x.pos, 'can''t negate ' + TypeName(x.typ)); +end; + +procedure NotOp(var x: TItem); +begin + if IsInt(x.typ) then MarkHelp(x.pos, '"not" needs a BOOL, found ' + What(x), 'the bits of an integer flip with ~'); + if x.typ^.form <> fBool then MarkAt(x.pos, '"not" needs a BOOL, found ' + What(x)); + if x.mode = mConst then x.val := 1 - x.val + else begin Value(x); NotBool end; +end; + +procedure Complement(var x: TItem); +begin + if x.typ^.form = fBool then MarkHelp(x.pos, '"~" needs an integer, found ' + What(x), 'a BOOL is negated with not'); + if not IsInt(x.typ) then MarkAt(x.pos, '"~" needs an integer, found ' + What(x)); + if x.mode = mConst then x.val := Cut(not x.val, x.typ) + else begin Value(x); gen.Complement(IntSize(x.typ), Signed(x.typ)) end; +end; + +{ Arrays, slices and strings, which = and # compare element by element } +function IsSeq(t: PType): boolean; +begin + IsSeq := t^.form in [fStr, fArray, fSlice]; +end; + +function ElemOf(t: PType): PType; +begin + if t^.form = fStr then ElemOf := tU8 else ElemOf := t^.base; +end; + +{ An array, slice or string as a slice in a temporary, for comparing. } +procedure SeqSlice(var x: TItem); +var t: PType; +begin + t := NewType(fSlice, 16, 8); + t^.base := ElemOf(x.typ); + if x.typ^.form = fSlice then begin + x.typ := t; CopyToTemp(x) + end else begin + if x.mode = mStr then begin Address(x); SliceOf(x, t, x.val) end + else begin + if x.vol then MarkAt(x.pos, 'can''t compare through a volatile pointer'); + Address(x); SliceOf(x, t, x.typ^.len) + end; + end; +end; + +procedure Op1(op: TSym; var x: TItem; var L: longint); +var tmp: TItem; +begin + L := NoLabel; + if (op in [sAnd, sOr]) and (x.typ^.form = fBool) then begin + tmp := x; + Value(tmp); + if x.mode <> mConst then x := tmp; + JumpKeep(L, op = sOr); + end else if (op in [sEql, sNeq]) and IsSeq(x.typ) then + SeqSlice(x) + else if (op = sPlus) and (x.mode = mStr) then + { two string constants to be joined: nothing to compute } + else if x.mode in [mType, mBuiltin, mNone, mCase, mStr] then + NotValue(x) + else if x.mode <> mConst then + Value(x); +end; + +function Log2(v: int64): longint; +var n: longint; +begin + n := 0; + while (v > 1) and (v and 1 = 0) do begin v := v shr 1; inc(n) end; + if v <> 1 then n := -1; + Log2 := n; +end; + +{ Whether a op b, for + - *, overflows an I64: an untyped constant + doesn't wrap, it is an error (report section 4). } +function Overflows(op: TSym; a, b: int64): boolean; +begin + case op of + sPlus: Overflows := ((b > 0) and (a > high(int64) - b)) or ((b < 0) and (a < low(int64) - b)); + sMinus: Overflows := ((b < 0) and (a > high(int64) + b)) or ((b > 0) and (a < low(int64) + b)); + sTimes: + if (a = 0) or (b = 0) then Overflows := false + else if a = -1 then Overflows := b = low(int64) + else if b = -1 then Overflows := a = low(int64) + else Overflows := (a * b) div b <> a; + else Overflows := false; + end; +end; + +{ A type's width in bits; an untyped constant's is an I64's } +function Bits(t: PType): longint; +begin + Bits := t^.size * 8; +end; + +function FoldInt(op: TSym; a, b: int64; t: PType; const p: TPos): int64; +var u: boolean; +begin + u := (t^.form = fInt) and not t^.signed; + if (t^.form = fConst) and Overflows(op, a, b) then MarkAt(p, 'the constant is too big for I64'); + case op of + sPlus: FoldInt := a + b; + sMinus: FoldInt := a - b; + sTimes: FoldInt := a * b; + sDiv, sMod: begin + if b = 0 then MarkAt(p, 'division by zero'); + if u then begin + if op = sDiv then FoldInt := int64(qword(a) div qword(b)) + else FoldInt := int64(qword(a) mod qword(b)); + end else if (b = -1) and (a = int64(-1) shl (Bits(t) - 1)) then MarkAt(p, 'division overflows') + else if op = sDiv then FoldInt := a div b + else FoldInt := a mod b; + end; + sAmp: FoldInt := a and b; + sBar: FoldInt := a or b; + sXor: FoldInt := a xor b; + sShl: FoldInt := a shl (b and (Bits(t) - 1)); + sShr: if u then FoldInt := int64(qword(a) shr (b and (Bits(t) - 1))) + else FoldInt := SarInt64(a, b and (Bits(t) - 1)); + sEql: FoldInt := ord(a = b); + sNeq: FoldInt := ord(a <> b); + sLss: if u then FoldInt := ord(qword(a) < qword(b)) else FoldInt := ord(a < b); + sLeq: if u then FoldInt := ord(qword(a) <= qword(b)) else FoldInt := ord(a <= b); + sGtr: if u then FoldInt := ord(qword(a) > qword(b)) else FoldInt := ord(a > b); + sGeq: if u then FoldInt := ord(qword(a) >= qword(b)) else FoldInt := ord(a >= b); + else MarkAt(p, 'bad operator'); FoldInt := 0; + end; +end; + +{ Folds x op y, of the real type t: an F32 rounded at each step, as + the machine would. } +function FoldReal(op: TSym; const x, y: TItem; t: PType; var r: TItem): boolean; +var a, b: double; +begin + a := RealOf(x); b := RealOf(y); + FoldReal := true; + case op of + sPlus: MakeReal(r, a + b); + sMinus: MakeReal(r, a - b); + sTimes: MakeReal(r, a * b); + sSlash: MakeReal(r, a / b); + sEql: MakeConst(r, tBool, ord(a = b)); + sNeq: MakeConst(r, tBool, ord(a <> b)); + sLss: MakeConst(r, tBool, ord(a < b)); + sLeq: MakeConst(r, tBool, ord(a <= b)); + sGtr: MakeConst(r, tBool, ord(a > b)); + sGeq: MakeConst(r, tBool, ord(a >= b)); + else FoldReal := false; + end; + if r.typ^.form = fReal then RealTo(r, t); +end; + +{ and, or and not are for BOOLs; &, |, xor and ~ for the bits of + integers: x is the wrong kind for op, and the message names the + operator it may have meant } +procedure WrongLogic(op: TSym; var x: TItem); +const Bits = 'the bits of integers take '; +begin + case op of + sAnd: if IsInt(x.typ) then MarkHelp(x.pos, '"and" needs BOOLs, found ' + What(x), Bits + '&'); + sOr: if IsInt(x.typ) then MarkHelp(x.pos, '"or" needs BOOLs, found ' + What(x), Bits + '|'); + sAmp: MarkHelp(x.pos, '"&" needs integers, found ' + What(x), 'BOOLs take and'); + sBar: MarkHelp(x.pos, '"|" needs integers, found ' + What(x), 'BOOLs take or'); + sXor: MarkHelp(x.pos, '"xor" needs integers, found ' + What(x), 'BOOLs that differ are #'); + end; + MarkAt(x.pos, SymText(op) + ' needs BOOLs, found ' + What(x)); +end; + +{ x + y, of two string constants: one string, in a chunk of its own + (report section 4) } +procedure JoinStr(var x, y: TItem); +var p: PBytes; c: longint; +begin + if y.mode <> mStr then MarkAt(y.pos, '"+" joins two strings, found ' + What(y)); + p := GetMem(x.val + y.val + 1); + Move(rodata^[chunks^[x.chunk].start], p^[0], x.val); + Move(rodata^[chunks^[y.chunk].start], p^[x.val], y.val + 1); + c := NewChunk(secRodata, -1, -1); + SetData(c, p, x.val + y.val + 1, 1); + FreeMem(p); + x.chunk := c; + x.val := x.val + y.val; +end; + +{ A set's operations, as operations on its bits: the two values on top } +procedure SetOp(op: TSym); +begin + case op of + sPlus: gen.Op(sBar, kWord, 8, false); + sTimes: gen.Op(sAmp, kWord, 8, false); + sMinus: begin gen.Complement(8, false); gen.Op(sAmp, kWord, 8, false) end; + sLeq, sGeq: begin + { x <= y has no bit of x outside y } + if op = sGeq then Swap; + gen.Complement(8, false); + gen.Op(sAmp, kWord, 8, false); + PushConst(kWord, 0); + Compare(sEql, kWord, false); + end; + sIn: begin + Swap; + gen.Op(sShr, kWord, 8, false); + PushConst(kWord, 1); + gen.Op(sAmp, kWord, 8, false); + end; + else Compare(op, kWord, false); + end; +end; + +procedure Op2(op: TSym; var x, y: TItem; L: longint); +const + Rel = [sEql, sNeq, sLss, sLeq, sGtr, sGeq]; +var + xt, yt, t, e: PType; r: TItem; scale: longint; isPtr: boolean; a, b: int64; +begin + xt := x.typ; yt := y.typ; + if y.mode in [mType, mBuiltin, mNone, mCase] then NotValue(y); + if (op = sPlus) and (x.mode = mStr) then begin JoinStr(x, y); exit end; + + if op in [sAnd, sOr] then begin + if xt^.form <> fBool then WrongLogic(op, x); + if yt^.form <> fBool then WrongLogic(op, y); + if (x.mode = mConst) and (y.mode = mConst) then begin + Fix(L); + if op = sAnd then x.val := x.val and y.val else x.val := x.val or y.val; + exit; + end; + Value(y); + FixKeep(L); + x.mode := mStack; x.typ := tBool; + exit; + end; + + if (op in [sAmp, sBar, sXor]) and (xt^.form = fBool) then WrongLogic(op, x); + if (op in [sAmp, sBar, sXor]) and (yt^.form = fBool) then WrongLogic(op, y); + + { the lengths, then the bytes, LEN * SIZE(T) of them: the elements + are of types whose bytes say all there is to their values } + if (op in [sEql, sNeq]) and IsSeq(xt) then begin + e := ElemOf(xt); + if not IsSeq(yt) then + MarkAt(Join(x.pos, y.pos), 'can''t compare an array with ' + TypeName(yt)) + else if not Same(e, ElemOf(yt)) then + MarkAt(Join(x.pos, y.pos), 'can''t compare an array of ' + TypeName(e) + ' with one of ' + TypeName(ElemOf(yt))); + if e^.form = fReal then + MarkHelp(Join(x.pos, y.pos), 'can''t compare arrays of reals with ' + SymText(op), + '-0.0 = 0.0 and a NaN equals nothing, though their bytes say otherwise: write a loop') + else if not (e^.form in [fInt, fBool, fEnum, fSet, fPtr]) then + MarkHelp(Join(x.pos, y.pos), 'can''t compare arrays of ' + TypeName(e) + ' with ' + SymText(op), 'write a loop'); + SeqSlice(y); + CompareSeq(x.off, y.off, Log2(e^.size), op = sEql); + MakeConst(x, tBool, 0); + x.mode := mStack; + exit; + end; + + { the type of the result, and the checks } + t := nil; scale := 1; isPtr := false; + if IsInt(xt) and IsInt(yt) then begin + if op = sSlash then MarkHelp(Join(x.pos, y.pos), '"/" divides reals, not integers', 'to divide integers, write ' + Source(x.pos) + ' div ' + Source(y.pos)); + if op in [sShl, sShr] then begin + if xt^.form = fConst then t := tConst else t := xt + end else if (xt^.form = fConst) and (yt^.form = fConst) then t := tConst + else if xt^.form = fConst then begin + if (x.mode = mConst) and not Fits(x.val, yt) then MarkAt(x.pos, IntStr(x.val) + ' doesn''t fit ' + TypeName(yt)); + t := yt + end else if yt^.form = fConst then begin + if (y.mode = mConst) and not Fits(y.val, xt) then MarkAt(y.pos, IntStr(y.val) + ' doesn''t fit ' + TypeName(xt)); + t := xt + end else if Same(xt, yt) then t := xt + else Mismatch(x, y, xt, yt); + if not (op in Rel + [sPlus, sMinus, sTimes, sDiv, sMod, sAmp, sBar, sXor, sShl, sShr]) then + MarkAt(Join(x.pos, y.pos), SymText(op) + ' doesn''t apply to ' + TypeName(t)); + end else if (xt^.form = fReal) and (yt^.form = fReal) then begin + if not (op in Rel + [sPlus, sMinus, sTimes, sSlash]) then MarkAt(Join(x.pos, y.pos), SymText(op) + ' doesn''t apply to ' + TypeName(xt)); + if xt = tRConst then t := yt + else if (yt = tRConst) or Same(xt, yt) then t := xt + else Mismatch(x, y, xt, yt); + if (x.mode = mConst) and (x.typ <> t) then RealTo(x, t); + if (y.mode = mConst) and (y.typ <> t) then RealTo(y, t); + end else if (xt^.form = fBool) and (yt^.form = fBool) then begin + if not (op in [sEql, sNeq]) then MarkAt(Join(x.pos, y.pos), SymText(op) + ' doesn''t apply to ' + TypeName(xt)); + t := tBool; + end else if (xt^.form = fPtr) and IsInt(yt) and (op in [sPlus, sMinus]) then begin + t := xt; scale := xt^.base^.size; isPtr := true; + if y.mode = mConst then y.typ := tInt; + end else if (xt^.form = fPtr) and (yt^.form = fPtr) and (op = sMinus) then begin + if not Same(xt, yt) then Mismatch(x, y, xt, yt); + t := tInt; scale := xt^.base^.size; isPtr := true; + end else if (xt^.form in [fPtr, fProc, fNil, fError]) and (yt^.form in [fPtr, fProc, fNil, fError]) then begin + if not (op in Rel) then MarkAt(Join(x.pos, y.pos), SymText(op) + ' doesn''t apply to ' + TypeName(xt)); + if (xt^.form in [fProc, fError]) or (yt^.form in [fProc, fError]) then + if not (op in [sEql, sNeq]) then MarkAt(Join(x.pos, y.pos), SymText(op) + ' doesn''t apply to ' + TypeName(xt)); + if (xt^.form <> fNil) and (yt^.form <> fNil) and not Same(xt, yt) then + if not ((xt^.form = fPtr) and (yt^.form = fPtr) and Same(xt^.base, yt^.base)) then + Mismatch(x, y, xt, yt); + t := tU64; + end else if (xt^.form = fEnum) and Same(xt, yt) then begin + if not (op in Rel) then MarkAt(Join(x.pos, y.pos), SymText(op) + ' doesn''t apply to ' + TypeName(xt)); + t := xt; + end else if (xt^.form = fSet) and Same(xt, yt) then begin + if not (op in [sPlus, sTimes, sMinus, sEql, sNeq, sLeq, sGeq]) then MarkAt(Join(x.pos, y.pos), SymText(op) + ' doesn''t apply to ' + TypeName(xt)); + t := xt; + end else if (op = sIn) and (yt^.form = fSet) and Same(xt, yt^.base) then + t := yt + else + Mismatch(x, y, xt, yt); + + { constants } + if (x.mode = mConst) and (y.mode = mConst) and not isPtr then begin + if t^.form = fReal then begin + if not FoldReal(op, x, y, t, r) then MarkAt(Join(x.pos, y.pos), SymText(op) + ' doesn''t apply to ' + TypeName(xt)); + x := r; + end else if t^.form = fSet then begin + a := x.val; b := y.val; + case op of + sPlus: MakeConst(x, t, a or b); + sTimes: MakeConst(x, t, a and b); + sMinus: MakeConst(x, t, a and not b); + sIn: MakeConst(x, tBool, (b shr a) and 1); + sLeq: MakeConst(x, tBool, ord(a and not b = 0)); + sGeq: MakeConst(x, tBool, ord(b and not a = 0)); + else MakeConst(x, tBool, ord((a = b) = (op = sEql))); + end; + end else if op in Rel then + MakeConst(x, tBool, FoldInt(op, x.val, y.val, t, Join(x.pos, y.pos))) + else + MakeConst(x, t, Cut(FoldInt(op, x.val, y.val, t, Join(x.pos, y.pos)), t)); + exit; + end; + + { x and y on the stack, x under y; a constant x goes on after y } + Value(y); + if x.mode = mConst then begin Value(x); Swap end; + + if t^.form = fReal then begin + if op in Rel then Compare(op, KindOf(t), false) else gen.Op(op, KindOf(t), 8, false) + end else if t^.form = fSet then + SetOp(op) + else if op in Rel then + Compare(op, kWord, Signed(t)) + else if isPtr then begin + if t <> tInt then ScaleBy(scale); + gen.Op(op, kWord, 8, false); + if (t = tInt) and (scale <> 1) then begin + PushConst(kWord, scale); + gen.Op(sDiv, kWord, 8, true); + end; + end else + gen.Op(op, KindOf(t), IntSize(t), Signed(t)); + x.mode := mStack; + if op in Rel + [sIn] then x.typ := tBool else x.typ := t; +end; + +{ INT and UINT, the integers as big as an address, through which + integers and pointers convert (report section 6.7) } +function IsWord(t: PType): boolean; +begin + IsWord := Same(t, tInt) or Same(t, tUInt); +end; + +procedure Convert(var x: TItem; t: PType); +var s: PType; r: double; +begin + s := x.typ; + if x.mode in [mType, mBuiltin, mNone, mCase, mStr] then begin + if x.mode = mStr then MarkAt(x.pos, 'can''t convert a string'); + NotValue(x); + end; + if Same(s, t) then exit; + if (IsInt(s) or (s^.form in [fEnum, fSet])) and (t^.form = fInt) then begin + if x.mode = mConst then x.val := Cut(x.val, t) + else begin Value(x); Narrow(t^.size, t^.signed) end; + end else if IsInt(s) and (t^.form = fEnum) then begin + if x.mode = mConst then begin + if (x.val < 0) or (x.val >= t^.len) then MarkAt(x.pos, IntStr(x.val) + ' isn''t a position of ' + TypeName(t)) + end else begin Value(x); CheckEnum(t^.len, NameChunk(t), x.pos) end; + end else if IsInt(s) and (t^.form = fSet) then begin + if x.mode = mConst then begin + if t^.len < 64 then x.val := x.val and ((int64(1) shl t^.len) - 1) + end else begin + Value(x); + if t^.len < 64 then begin + PushConst(kWord, (int64(1) shl t^.len) - 1); + gen.Op(sAmp, kWord, 8, false); + end; + end; + end else if IsInt(s) and (t^.form = fReal) then begin + if x.mode = mConst then begin + if (s^.form = fInt) and not s^.signed then r := qword(x.val) else r := x.val; + MakeReal(x, r); + RealTo(x, t); + end else begin + Value(x); + IntToReal(KindOf(t), (s^.form = fInt) and not s^.signed and (s^.size = 8)); + end; + end else if (s^.form = fReal) and (t^.form = fReal) then begin + { F32 to F64, F64 to F32, or a real constant to either } + if x.mode = mConst then RealTo(x, t) + else begin Value(x); RealToReal(KindOf(s)) end; + end else if (s^.form = fReal) and (t^.form = fInt) then begin + if x.mode = mConst then begin + r := RealOf(x); + if (r <> r) or (r >= 9.2233720368547758e18) or (r < -9.2233720368547758e18) then + x.val := Cut(low(int64), t) + else x.val := Cut(trunc(r), t); + end else begin + Value(x); RealToInt(KindOf(s)); Narrow(t^.size, t^.signed) + end; + end else if (IsWord(s) or (s^.form in [fConst, fPtr, fProc, fNil])) and (t^.form in [fPtr, fProc]) then begin + if x.mode <> mConst then Value(x); + end else if (s^.form in [fPtr, fProc]) and IsWord(t) then + Value(x) + else + MarkAt(x.pos, 'can''t convert ' + TypeName(s) + ' to ' + TypeName(t)); + x.typ := t; +end; + +{ Calls } + +procedure BeginCall(var c: TCall; var x: TItem); +begin + if x.mode = mProc then begin + c.sig := x.obj^.typ; c.chunk := x.obj^.chunk; c.target := 0; + c.obj := x.obj; c.code := x.obj^.isCode; c.ext := x.obj^.ext; + end else begin + c.obj := nil; c.code := false; c.ext := false; + if x.typ^.form <> fProc then MarkAt(x.pos, 'expected a procedure, found ' + What(x)); + c.sig := x.typ; c.chunk := -1; + c.target := ToSlot(x); + end; + c.param := c.sig^.fields; + c.n := 0; +end; + +{ Too many arguments or too few, at p } +procedure WrongCount(var c: TCall; const p: TPos; const what: shortstring); +begin + if c.obj = nil then MarkAt(p, what); + Error(p, what + ': ' + NameOf(c.obj^.name) + ' takes ' + IntStr(c.sig^.len)); + if c.obj^.module <> nil then Note(c.obj^.pos, 'the signature is here'); + Fail; +end; + +procedure PassArg(var c: TCall; var a: TItem); +var p: PObj; s: int64; +begin + p := c.param; + if c.n > High(c.slots) then MarkAt(a.pos, 'too many arguments'); + if p = nil then begin + { past the parameters of a C procedure that ends in ...: a string + goes as a C string, an integer constant as an INT, a real + constant as an F64; C takes no F32 there } + if not c.sig^.variadic then WrongCount(c, a.pos, 'too many arguments'); + if a.mode = mStr then Coerce(a, tPtrU8) + else if a.typ^.form = fConst then Coerce(a, tInt) + else if a.typ = tRConst then Coerce(a, tReal) + else if IsF32(a.typ) then MarkAt(a.pos, 'an F32 goes to ... as F64(x)') + else if not IsScalar(a.typ) then MarkAt(a.pos, 'only a single value goes to ...'); + c.isF[c.n] := a.typ^.form = fReal; + c.slots[c.n] := ToSlot(a); + inc(c.n); + exit; + end; + c.isF[c.n] := (p^.typ^.form = fReal) and not p^.isVar; + if p^.isVar then begin + NotReadOnly(a); + if (a.mode <> mVar) or not a.isVar then MarkAt(a.pos, 'a var parameter needs a variable'); + if a.odd then MarkAt(a.pos, 'a field of a packed record can''t be a var parameter'); + if not Same(a.typ, p^.typ) then MarkAt(a.pos, 'a var parameter needs exactly ' + TypeName(p^.typ) + ', found ' + What(a)); + if a.vol then MarkAt(a.pos, 'can''t pass through a volatile pointer to a var parameter'); + Address(a); + s := AllocTemp(8, 8); + PopVar(FrameAdr(s), 8); + end else if IsAggregate(p^.typ) then begin + Coerce(a, p^.typ); + if a.isVar or a.vol or (a.base <> bFrame) then CopyToTemp(a); + Address(a); + s := AllocTemp(8, 8); + PopVar(FrameAdr(s), 8); + end else begin + Coerce(a, p^.typ); + s := ToSlot(a); + end; + c.slots[c.n] := s; + inc(c.n); + c.param := p^.next; +end; + +procedure EndCall(var c: TCall; var x: TItem); +var res: PType; +begin + if c.param <> nil then WrongCount(c, TokPos, 'too few arguments'); + Call(c); + res := c.sig^.base; + FillChar(x, SizeOf(x), 0); + if res = nil then begin + x.mode := mNone; x.typ := tNone; x.obj := c.obj + end else if c.ret <> 0 then + TempItem(x, res, c.ret) + else begin + x.mode := mStack; x.typ := res; + end; +end; + +{ Variants } + +{ A temporary of type t, all zero: for variants and record literals. } +procedure ZeroTemp(var x: TItem; t: PType); +var tmp: int64; +begin + tmp := AllocTemp(t^.size, t^.align); + ZeroVar(FrameAdr(tmp), t^.size); + TempItem(x, t, tmp); +end; + +procedure Construct(var x: TItem; c: PObj); +begin + ZeroTemp(x, c^.typ); + PushConst(kWord, c^.val); + PopVar(FrameAdr(x.off), 8); +end; + +procedure SetField(const x: TItem; f: PObj; var a: TItem); +begin + Coerce(a, f^.typ); + if IsScalar(f^.typ) then begin + Value(a); + PopVar(FrameAdr(x.off + f^.val), ScalarSize(f^.typ)); + end else begin + if a.vol then MarkAt(a.pos, 'can''t copy through a volatile pointer'); + Address(a); + CopyTo(FrameAdr(x.off + f^.val), f^.typ^.size); + end; +end; + +{ The slot match tests: a variant's address, or an enumeration's or an + integer's value. } +function MatchBegin(var x: TItem): int64; +var p: int64; +begin + if x.typ^.form in [fEnum, fInt] then exit(ToSlot(x)); + if (x.mode <> mVar) or (x.typ^.form <> fVariant) then MarkAt(x.pos, 'match needs a variant, an enumeration or an integer, found ' + What(x)); + if x.ro then CopyToTemp(x); { its arms' names stand for a copy's fields } + Address(x); + p := AllocTemp(8, 8); + PopVar(FrameAdr(p), 8); + MatchBegin := p; +end; + +{ To L unless the tag of the variant whose address is in slot p, or the + enumeration in it, is tag } +procedure MatchTag(p: int64; tag: int64; var L: longint; isEnum: boolean); +var a: TAdr; +begin + PushVar(FrameAdr(p), 8, false, kWord); + if not isEnum then begin + a.base := bStack; a.chunk := -1; a.off := 0; + PushVar(a, 8, false, kWord); + end; + PushConst(kWord, tag); + JumpCmp(sNeq, false, L); +end; + +{ To body if the integer in slot p is from lo to hi: less its lo, it is + then at most hi - lo, compared unsigned, which holds for a signed type + or not, with no second jump. } +procedure MatchRange(p, lo, hi: int64; var body: longint); +begin + PushVar(FrameAdr(p), 8, false, kWord); + if lo = hi then begin + PushConst(kWord, lo); + JumpCmp(sEql, false, body); + exit; + end; + if lo <> 0 then begin + PushConst(kWord, lo); + gen.Op(sMinus, kWord, 8, false); + end; + PushConst(kWord, hi - lo); + JumpCmp(sLeq, false, body); +end; + +{ The end of a round of a for loop: stop if the step would pass the + limit, else step. Counting the distance left, rather than comparing + after the step, can't be fooled by the variable wrapping around. } +procedure ForNext(o: PObj; bslot, step: int64; var exitL: longint; top: longint); +var v, w: TItem; +begin + MakeItem(w, o); + if step > 0 then begin + PushVar(FrameAdr(bslot), 8, false, kWord); + Value(w); + end else begin + Value(w); + PushVar(FrameAdr(bslot), 8, false, kWord); + end; + gen.Op(sMinus, kWord, 8, false); + PushConst(kWord, abs(step)); + JumpCmp(sLss, false, exitL); + MakeItem(v, o); + MakeItem(w, o); + Value(w); + PushConst(kWord, step); + gen.Op(sPlus, kWord, IntSize(o^.typ), Signed(o^.typ)); + Assign(v, w); + JumpBack(top); +end; + +procedure CondJump(var x: TItem; var L: longint); +begin + if x.typ^.form <> fBool then MarkAt(x.pos, 'a condition is a BOOL, found ' + What(x)); + Value(x); + JumpIf(L, false); +end; + +{ Procedures } + +procedure BeginProc(sig: PType; params: PObj); +begin + result := sig^.base; + gen.BeginProc(sig, params); +end; + +{ The result of return x: a value on top, or one copied behind the + hidden pointer } +procedure ReturnValue(var x: TItem); +begin + if result = nil then MarkAt(x.pos, 'this procedure returns nothing'); + Coerce(x, result); + if IsAggregate(result) then begin + if x.vol then MarkAt(x.pos, 'can''t copy through a volatile pointer'); + Address(x); + CopyResult(0, result^.size); + end else Value(x); +end; + +{ One of several results, into its place behind the hidden pointer. } +procedure ReturnField(f: PObj; var x: TItem); +begin + Coerce(x, f^.typ); + if IsScalar(f^.typ) then begin + Value(x); + ResultTo(f^.val, ScalarSize(f^.typ)); + end else begin + if x.vol then MarkAt(x.pos, 'can''t copy through a volatile pointer'); + Address(x); + CopyResult(f^.val, f^.typ^.size); + end; +end; + +{ Several results at once, the call's that return f(x) passes on. } +procedure ReturnAll(var x: TItem); +begin + Address(x); + CopyResult(0, result^.size); +end; + +procedure ReturnNone; +begin + if result <> nil then Mark('return needs a result of ' + TypeName(result)); + ReturnJump; +end; + +{ Keeps a variable's address in a frame slot, rather than on the stack, + while other code runs. } +procedure Pin(var x: TItem); +var s: int64; +begin + if (x.mode = mVar) and (x.base = bStack) then begin + Address(x); + s := AllocTemp(8, 8); + PopVar(FrameAdr(s), 8); + x.base := bSlot; + x.chunk := s; + end; +end; + +{ INC(v, k) or DEC: v's address is on the stack, from Address. } +procedure IncDec(var v, k: TItem; dec: boolean); +begin + CoerceExact(k, v.typ, ''); + Value(k); + gen.IncDec(ScalarSize(v.typ), v.typ^.signed, dec); +end; + +{ An error is the address of its length, followed by its message. } +function ErrorChunk(var x: TItem; module, name: longint): longint; +var c: longint; p: PBytes; +begin + if x.mode <> mStr then MarkAt(x.pos, 'an error is made from a string'); + p := GetMem(x.val + 8); + PInt64(p)^ := x.val; + Move(rodata^[chunks^[x.chunk].start], p^[8], x.val); + c := NewChunk(secRodata, module, name); + SetData(c, p, x.val + 8, 8); + FreeMem(p); + ErrorChunk := c; +end; + +procedure Msg(var x: TItem); +var s: int64; +begin + Coerce(x, tError); + Value(x); + s := AllocTemp(16, 8); + ErrorText(s); + TempItem(x, tBytes, s); +end; + +end. diff --git a/src/link.pas b/src/link.pas index a410762..5721a48 100644 --- a/src/link.pas +++ b/src/link.pas @@ -12,7 +12,7 @@ loader's other tables come at the end of rodata; elf.pas writes them in the room left there. - Depends on: x64 for chunks and fixups, scan for names and errors. + Depends on: chunk for chunks and fixups, scan for names and errors. Leaves out: the file format; that is elf.pas. } unit link; @@ -21,7 +21,7 @@ interface -uses scan, diag, x64; +uses scan, diag, chunk; const Base = $400000; diff --git a/src/parse.pas b/src/parse.pas index 9adca52..dfea876 100644 --- a/src/parse.pas +++ b/src/parse.pas @@ -11,7 +11,7 @@ are read for their declarations only, and must export the same interface. - Depends on: scan, sym, x64, gen. + Depends on: scan, sym, chunk for data, item and gen for code. Leaves out: linking; a module only records the libraries it names, and whether it uses C or says link static. } @@ -21,7 +21,7 @@ interface -uses scan, diag, sym, x64, gen; +uses scan, diag, sym, chunk, gen, item; const Target = 'linux-x86_64'; @@ -178,7 +178,7 @@ jb: jmp_buf; outer: ^jmp_buf; scan: TScanState; - scopes, depth, numDefers: longint; + scopes, depth, pushed, numDefers: longint; loop: PLoop; result: PType; deferring, directDefer, quiet: boolean; @@ -188,7 +188,7 @@ begin r.outer := recovery; SaveScan(r.scan); - r.scopes := ScopeDepth; r.depth := depth; r.numDefers := numDefers; + r.scopes := ScopeDepth; r.depth := depth; r.pushed := pushed; r.numDefers := numDefers; r.loop := curLoop; r.result := curResult; r.deferring := deferring; r.directDefer := directDefer; r.quiet := quiet; recovery := @r.jb; @@ -208,7 +208,7 @@ begin RestoreScan(r.scan); skipping := true; - CutScopes(r.scopes); depth := r.depth; numDefers := r.numDefers; + CutScopes(r.scopes); ResetStack(r.depth, r.pushed); numDefers := r.numDefers; curLoop := r.loop; curResult := r.result; deferring := r.deferring; directDefer := r.directDefer; inTypes := false; declExported := false; inExtern := false; making := false; @@ -664,20 +664,8 @@ EndCall(c, x); end; -procedure Args(n: longint; var slots: array of int64); -var i: longint; a: TItem; -begin - for i := 0 to n - 1 do begin - if i > 0 then Expect(sComma); - Expression(a, nil); - if not (IsScalar(a.typ) and (a.typ^.form <> fReal)) then MarkAt(a.pos, 'expected an integer or a pointer, found ' + What(a)); - if a.typ^.form = fConst then Coerce(a, tInt); - slots[i] := ToSlot(a); - end; -end; - procedure Atomic(var x: TItem; which: longint); -var p, a: TItem; t: PType; s: array[0..2] of int64; i, n: longint; +var p, a: TItem; t: PType; i, n: longint; begin Expression(p, nil); if p.typ^.form <> fPtr then MarkAt(p.pos, 'expected a pointer, found ' + What(p)); @@ -685,40 +673,29 @@ if not (IsWord(t) or ((t^.form = fPtr) and (which <> bXadd))) then if which = bXadd then MarkAt(p.pos, 'expected a pointer to an INT or a UINT, found ' + TypeName(p.typ)) else MarkAt(p.pos, 'expected a pointer to an INT, a UINT or a pointer, found ' + TypeName(p.typ)); - s[0] := ToSlot(p); + Value(p); if which = bCas then n := 2 else n := 1; for i := 1 to n do begin Expect(sComma); Expression(a, t); Coerce(a, t); - s[i] := ToSlot(a); + Value(a); end; - Load(RCX, Mem(RBP, s[0]), 8, false); - Load(RAX, Mem(RBP, s[1]), 8, false); + gen.Atomic(which); MakeConst(x, t, 0); - case which of - bCas: begin - Load(RDX, Mem(RBP, s[2]), 8, false); - LockCmpxchg(Mem(RCX, 0), RDX); - SetCC(ccE, RAX); - x.typ := tBool; - end; - bXchg: Xchg(Mem(RCX, 0), RAX); - bXadd: LockXadd(Mem(RCX, 0), RAX); - end; - x.mode := mReg; + if which = bCas then x.typ := tBool; + x.mode := mStack; end; { NEW(p, a): p := a^.alloc(a, SIZE(T), alignment), zeroed if not nil. a is a ^Mem.Allocator, the one interface the compiler knows. } procedure New_(var x: TItem); -var y, z: TItem; t: PType; f: PObj; s: int64; c: TCall; L: longint; +var y, z: TItem; t: PType; f: PObj; s: int64; c: TCall; begin Expression(x, nil); NotReadOnly(x); if (x.mode <> mVar) or not x.isVar or (x.typ^.form <> fPtr) then MarkAt(x.pos, 'NEW needs a pointer variable'); t := x.typ^.base; - Save(x); Expect(sComma); Expression(y, nil); if (y.typ^.form <> fPtr) or (y.typ^.base^.obj = nil) or (y.typ^.base^.obj^.module = nil) @@ -726,29 +703,20 @@ or (NameOf(y.typ^.base^.obj^.module^.name) <> 'Mem') then MarkAt(y.pos, 'NEW needs a ^Mem.Allocator, found ' + What(y)); f := Find(y.typ^.base^.scope, Name('alloc')); s := ToSlot(y); - Load(RAX, Mem(RBP, s), 8, false); + PushVar(FrameAdr(s), 8, false, kWord); MakeConst(z, f^.typ, 0); - z.mode := mVar; z.base := bReg; z.reg := RAX; z.off := f^.val; + z.mode := mVar; z.base := bStack; z.off := f^.val; BeginCall(c, z); - Load(RAX, Mem(RBP, s), 8, false); + PushVar(FrameAdr(s), 8, false, kWord); MakeConst(z, y.typ, 0); - z.mode := mReg; + z.mode := mStack; PassArg(c, z); MakeConst(z, tInt, t^.size); PassArg(c, z); MakeConst(z, tInt, t^.align); PassArg(c, z); EndCall(c, z); - L := NoLabel; - TestRR(RAX, RAX); - Jcc(ccE, L); - MovRR(RDX, RAX); - MovRR(RDI, RAX); - MovRI(RCX, t^.size); - MovRI(RAX, 0); - RepStosb; - MovRR(RAX, RDX); - FixLink(L); + ZeroNew(t^.size); z.typ := x.typ; Assign(x, z); MakeConst(x, tNone, 0); @@ -761,17 +729,16 @@ end; procedure Builtin(var x: TItem); -const SysRegs: array[0..6] of longint = (RAX, RDI, RSI, RDX, R10, R8, R9); -var which, n, i: longint; y: TItem; t: PType; slots: array[0..6] of int64; +var which, n: longint; y: TItem; t: PType; begin which := x.obj^.val; if which in [bFence, bArgc, bArgv] then begin if tok = sLparen then begin Next; Expect(sRparen) end; MakeConst(x, tNone, 0); case which of - bFence: begin Mfence; x.mode := mNone end; - bArgc: begin Load(RAX, MemRip(argcChunk, 0), 8, false); x.typ := tInt; x.mode := mReg end; - bArgv: begin Load(RAX, MemRip(argvChunk, 0), 8, false); x.typ := tArgv; x.mode := mReg end; + bFence: begin Fence; x.mode := mNone end; + bArgc: begin PushVar(GlobalAdr(argcChunk), 8, false, kWord); x.typ := tInt; x.mode := mStack end; + bArgv: begin PushVar(GlobalAdr(argvChunk), 8, false, kWord); x.typ := tArgv; x.mode := mStack end; end; exit; end; @@ -787,36 +754,37 @@ if (y.mode <> mVar) or not y.isVar then MarkAt(y.pos, 'ADR needs a variable'); if y.odd then MarkAt(y.pos, 'a field of a packed record has no address'); t := NewPtr(y.typ, y.vol); - Address(y, RAX); + Address(y); MakeConst(x, t, 0); - x.mode := mReg; + x.mode := mStack; end; bLen: begin Expression(y, nil); if y.mode = mStr then MakeConst(x, tConst, y.val) - else if y.typ^.form = fArray then MakeConst(x, tConst, y.typ^.len) - else if (y.typ^.form = fSlice) and (y.mode = mVar) then begin - Address(y, RAX); - Load(RAX, Mem(RAX, 8), 8, false); - MakeConst(x, tInt, 0); - x.mode := mReg; + else if y.typ^.form = fArray then begin + Discard(y); + MakeConst(x, tConst, y.typ^.len) + end else if (y.typ^.form = fSlice) and (y.mode = mVar) then begin + { its length, the word after its pointer } + y.off := y.off + 8; + y.typ := tInt; + Value(y); + x := y; end else MarkAt(y.pos, 'LEN needs an array or a slice, found ' + What(y)); end; bSyscall: begin - n := 1; - Args(1, slots); - while (tok = sComma) and (n < 7) do begin - Next; + n := 0; + repeat + if n > 0 then Next; Expression(y, nil); if not (IsScalar(y.typ) and (y.typ^.form <> fReal)) then MarkAt(y.pos, 'expected an integer or a pointer, found ' + What(y)); if y.typ^.form = fConst then Coerce(y, tInt); - slots[n] := ToSlot(y); + Value(y); inc(n); - end; - for i := 0 to n - 1 do Load(SysRegs[i], Mem(RBP, slots[i]), 8, false); - Syscall; + until (tok <> sComma) or (n = 7); + SysCall(n); MakeConst(x, tInt, 0); - x.mode := mReg; + x.mode := mStack; end; bCas, bXchg, bXadd: Atomic(x, which); bMsg: begin Expression(x, tError); Msg(x) end; @@ -825,7 +793,7 @@ NotReadOnly(x); if (x.mode <> mVar) or not x.isVar or (x.typ^.form <> fInt) then MarkAt(x.pos, IncOrDec(which) + ' needs an integer variable'); - Save(x); + Address(x); if tok = sComma then begin Next; Expression(y, x.typ); @@ -946,7 +914,7 @@ Expect(sRbrak); if (want^.form = fArray) and (n <> want^.len) then MarkAt(SpanFrom(start), 'expected ' + IntStr(want^.len) + ' elements, found ' + IntStr(n)); if n = 0 then begin - MovRI(RAX, 0); + PushConst(kWord, 0); SliceOf(x, want, 0); exit; end; @@ -961,13 +929,11 @@ end; for i := 0 to n - 1 do if IsScalar(et) then begin - Load(RAX, Mem(RBP, slots[i]), 8, false); - Store(Mem(RBP, off + i * es), RAX, ScalarSize(et)); + PushVar(FrameAdr(slots[i]), 8, false, KindOf(et)); + PopVar(FrameAdr(off + i * es), ScalarSize(et)); end else begin - Lea(RSI, Mem(RBP, slots[i])); - Lea(RDI, Mem(RBP, off + i * es)); - MovRI(RCX, es); - RepMovsb; + PushAdr(FrameAdr(slots[i])); + CopyTo(FrameAdr(off + i * es), es); end; TempItem(x, at, off); end; @@ -1021,15 +987,16 @@ else begin if slot = 0 then begin slot := AllocTemp(8, 8); - MovRI(RAX, 0); - Store(Mem(RBP, slot), RAX, 8); + PushConst(kWord, 0); + PopVar(FrameAdr(slot), 8); end; Value(e); - MovRR(RCX, RAX); - MovRI(RAX, 1); - Shift(shShl, RAX); - AluM(aluOr, RAX, Mem(RBP, slot)); - Store(Mem(RBP, slot), RAX, 8); + PushConst(kWord, 1); + Swap; + Op(sShl, kWord, 8, false); + PushVar(FrameAdr(slot), 8, false, kWord); + Op(sBar, kWord, 8, false); + PopVar(FrameAdr(slot), 8); end; if tok <> sComma then break; Next; @@ -1038,10 +1005,10 @@ if t = nil then MarkAt(SpanFrom(start), '{} needs a known set type'); MakeConst(x, t, bits); if slot <> 0 then begin - Load(RAX, Mem(RBP, slot), 8, false); - MovRI(RCX, bits); - Alu(aluOr, RAX, RCX); - x.mode := mReg; + PushVar(FrameAdr(slot), 8, false, kWord); + PushConst(kWord, bits); + Op(sBar, kWord, 8, false); + x.mode := mStack; end; end; @@ -1183,7 +1150,7 @@ procedure RunDefers(base: longint); var i: longint; begin - for i := numDefers - 1 downto base do CallBack(defers[i]); + for i := numDefers - 1 downto base do RunDefer(defers[i]); end; procedure IfStatement; @@ -1197,8 +1164,8 @@ Statements; endL := NoLabel; while tok = sElsif do begin - Jmp(endL); - FixLink(L); + Jump(endL); + Fix(L); Next; Expression(x, nil); Expect(sThen); @@ -1207,13 +1174,13 @@ Statements; end; if tok = sElse then begin - Jmp(endL); - FixLink(L); + Jump(endL); + Fix(L); Next; Statements; - end else FixLink(L); + end else Fix(L); Expect(sEnd); - FixLink(endL); + Fix(endL); end; procedure WhileStatement; @@ -1227,10 +1194,10 @@ CondJump(x, L); Loop(lp, old); Statements; - JmpBack(top); + JumpBack(top); Expect(sEnd); - FixLink(L); - FixLink(lp.brk); + Fix(L); + Fix(lp.brk); curLoop := old; end; @@ -1246,8 +1213,8 @@ Expression(x, nil); L := NoLabel; CondJump(x, L); - FixLinkTo(L, top); - FixLink(lp.brk); + FixTo(L, top); + Fix(lp.brk); end; procedure ForStatement; @@ -1267,7 +1234,6 @@ Next; Expect(sBecomes); MakeItem(v, o); - Save(v); Expression(a, o^.typ); CoerceExact(a, o^.typ, ''); Assign(v, a); @@ -1287,20 +1253,16 @@ top := pc; MakeItem(v, o); Value(v); - Load(RCX, Mem(RBP, bslot), 8, false); - Alu(aluCmp, RAX, RCX); - if o^.typ^.signed then begin - if step > 0 then Jcc(ccG, exitL) else Jcc(ccL, exitL) - end else begin - if step > 0 then Jcc(ccA, exitL) else Jcc(ccB, exitL) - end; + PushVar(FrameAdr(bslot), 8, false, kWord); + if step > 0 then JumpCmp(sGtr, o^.typ^.signed, exitL) + else JumpCmp(sLss, o^.typ^.signed, exitL); Loop(lp, old); Statements; curLoop := old; Expect(sEnd); ForNext(o, bslot, step, exitL, top); - FixLink(exitL); - FixLink(lp.brk); + Fix(exitL); + Fix(lp.brk); end; type @@ -1348,12 +1310,12 @@ Next; until false; L := NoLabel; - Jmp(L); - FixLink(body); + Jump(L); + Fix(body); Expect(sColon); Statements; - Jmp(endL); - FixLink(L); + Jump(endL); + Fix(L); end; procedure MatchStatement; @@ -1415,8 +1377,8 @@ Expect(sColon); Statements; CloseScope; - Jmp(endL); - FixLink(L); + Jump(endL); + Fix(L); end; end; endAt := TokPos; @@ -1430,7 +1392,7 @@ c := c^.next; end; end; - FixLink(endL); + Fix(endL); end; { What a message calls x: its name n when x is just that name, else what @@ -1521,32 +1483,28 @@ { defer s: s is compiled where it stands, as a little subroutine of the procedure, jumped over; each way out of the statement list calls it. } procedure Defer; -var L, pos, oldDepth: longint; oldLoop: PLoop; oldDeferring: boolean; start: TPos; +var L, pos, saved: longint; oldLoop: PLoop; oldDeferring: boolean; start: TPos; begin start := TokPos; Next; if directDefer then MarkAt(SpanFrom(start), 'defer can''t be deferred'); if numDefers > High(defers) then MarkAt(SpanFrom(start), 'more than ' + IntStr(High(defers) + 1) + ' deferred statements in one procedure'); L := NoLabel; - Jmp(L); - pos := pc; - oldDepth := depth; oldLoop := curLoop; oldDeferring := deferring; - depth := 1; { the return address } + pos := DeferBegin(L, saved); + oldLoop := curLoop; oldDeferring := deferring; curLoop := nil; deferring := true; directDefer := true; Statement; directDefer := false; - KeepTemps; - depth := oldDepth; curLoop := oldLoop; deferring := oldDeferring; - Ret; - FixLink(L); + curLoop := oldLoop; deferring := oldDeferring; + DeferEnd(L, saved); defers[numDefers] := pos; inc(numDefers); end; procedure OneStatement; -var x, y: TItem; called: boolean; m: int64; c: TCall; start: TPos; first: longint; +var x, y: TItem; called, scalar: boolean; m: int64; c: TCall; start: TPos; first: longint; begin start := TokPos; first := id; @@ -1558,20 +1516,20 @@ if tok = sBecomes then begin NotReadOnly(x); Assignable(x, first); - Save(x); Next; Expression(y, x.typ); Assign(x, y); end else if tok = sComma then MultiAssign(x, first) else if not called then begin - if (x.mode = mProc) or ((x.mode in [mVar, mReg]) and (x.typ^.form = fProc)) then begin + if (x.mode = mProc) or ((x.mode in [mVar, mStack]) and (x.typ^.form = fProc)) then begin BeginCall(c, x); EndCall(c, x); + Discard(x); end else if tok = sEql then MarkHelp(x.pos, Subject(x, first) + ' isn''t a statement', 'assignment is written :=') else MarkAt(x.pos, Subject(x, first) + ' isn''t a statement'); - end; + end else Discard(x); end; sIf: IfStatement; sWhile: WhileStatement; @@ -1590,12 +1548,14 @@ Expression(x, curResult); ReturnValue(x); end; - if numDefers > 0 then begin + { the result waits in the frame while the deferred statements run } + scalar := (curResult <> nil) and not IsAggregate(curResult); + if (numDefers > 0) and scalar then begin if deferSlot = 0 then deferSlot := AllocPerm(8, 8); - Store(Mem(RBP, deferSlot), RAX, 8); + PopVar(FrameAdr(deferSlot), 8); RunDefers(0); - Load(RAX, Mem(RBP, deferSlot), 8, false); - end; + PushVar(FrameAdr(deferSlot), 8, false, KindOf(curResult)); + end else RunDefers(0); ReturnJump; end; end; @@ -1603,7 +1563,7 @@ Next; if curLoop = nil then MarkAt(SpanFrom(start), 'break outside a loop'); RunDefers(curLoop^.base); - Jmp(curLoop^.brk); + Jump(curLoop^.brk); end; sDefer: Defer; else if AtLineStart then Expected('"end"') @@ -2569,11 +2529,6 @@ nameStatic := Name('static'); nameCheck := Name('check'); nameOff := Name('off'); - rtFail := NewChunk(secText, nameRt, nameFail); - argcChunk := NewChunk(secBss, -1, Name('argc')); - SetBss(argcChunk, 8, 8); - argvChunk := NewChunk(secBss, -1, Name('argv')); - SetBss(argvChunk, 8, 8); tArgv := NewPtr(NewPtr(tU8, false), false); tBodySig := NewType(fProc, 8, 8); curLoop := nil; diff --git a/src/raz.pas b/src/raz.pas index 0ad9cc7..4efe0e2 100644 --- a/src/raz.pas +++ b/src/raz.pas @@ -25,7 +25,7 @@ {$mode objfpc}{$H-} -uses math, BaseUnix, syscall, scan, diag, sym, x64, gen, parse, link, elf; +uses math, BaseUnix, syscall, scan, diag, sym, chunk, gen, parse, link, elf; const { what git describe says, made by make: 0.3.0 at the tag v0.3.0, @@ -90,10 +90,10 @@ var path, outPath, dir, s: shortstring; - i, first, entry, start, fd: longint; + i, first, entry, fd: longint; m, rt: PModule; main: PObj; - hasResult, dynamic, run: boolean; + run: boolean; begin { constants fold as the machine computes: NaN and infinities, no traps } @@ -150,67 +150,21 @@ if rt <> nil then Use(rt); main := Find(m^.scope, Intern('main', 4)); - hasResult := false; if main <> nil then begin if (main^.cls <> oProc) or not main^.exported then Error(main^.pos, 'main must be an exported procedure') else if (main^.typ^.len <> 0) or ((main^.typ^.base <> nil) and (main^.typ^.base <> tInt)) then Error(main^.pos, 'main must be proc main* or proc main*: INT'); if errors > 0 then Finish; - hasResult := main^.typ^.base <> nil; end; Finish; if rt = nil then Fatal('can''t find module Rt'); - dynamic := UsesC; - entry := NewChunk(secText, -1, Intern('_start', 6)); - if dynamic then begin - { _start as C's crt1 does it: __libc_start_main(main, argc, argv, - nil, nil, rtld_fini, stack_end), with rsp aligned } - start := NewChunk(secText, -1, Intern('main', 4)); - BeginChunk(entry); - MovRI(RBP, 0); - MovRR(R9, RDX); - Pop(RSI); - MovRR(RDX, RSP); - AluI(aluAnd, RSP, -16); - Push(RAX); - Push(RSP); - MovRI(R8, 0); - MovRI(RCX, 0); - Lea(RDI, MemRip(start, 0)); - CallM(MemRip(ExternChunk(Intern('__libc_start_main', 17)), 0)); - Ud2; - EndChunk(entry); - BeginChunk(start); - Push(RBP); { aligns the stack again } - Store(MemRip(argcChunk, 0), RDI, 8); - Store(MemRip(argvChunk, 0), RSI, 8); - Load(RAX, MemRip(ExternChunk(Intern('exit', 4)), 0), 8, false); - Store(MemRip(RtObj(rt, 'cExit')^.chunk, 0), RAX, 8); - end else begin - start := entry; - BeginChunk(entry); - Load(RAX, Mem(RSP, 0), 8, false); - Store(MemRip(argcChunk, 0), RAX, 8); - Lea(RAX, Mem(RSP, 8)); - Store(MemRip(argvChunk, 0), RAX, 8); - end; { the places, which the linker makes, for Rt to say where a failed check or a signal was } placesChunk := NewChunk(secRodata, -1, -1); SetData(placesChunk, nil, 0, 8); - Lea(RAX, MemRip(placesChunk, 0)); - Store(MemRip(RtObj(rt, 'places')^.chunk, 0), RAX, 8); - m := firstModule; - while m <> nil do begin - if m^.used and (m^.body >= 0) then CallChunk(m^.body); - m := m^.next; - end; - if main <> nil then CallChunk(main^.chunk); - if hasResult then MovRR(RDI, RAX) else MovRI(RDI, 0); - CallChunk(RtObj(rt, 'exit')^.chunk); - Ud2; - EndChunk(start); + entry := EntryPoint(UsesC, firstModule, main, RtObj(rt, 'cExit')^.chunk, placesChunk, + RtObj(rt, 'places')^.chunk, RtObj(rt, 'exit')^.chunk); MarkLive(entry); if not HasReals then diff --git a/src/x64.pas b/src/x64.pas index 4a62a7b..63ebfec 100644 --- a/src/x64.pas +++ b/src/x64.pas @@ -1,17 +1,11 @@ -{ x64.pas: machine code. - - The code of a program is a set of chunks: one per procedure, module - variable and string. A chunk's bytes go in one of three sections: - text (code), rodata (strings), bss (variables, which are all zero). - A reference from code to another chunk (a call, or a rip-relative - address) is a fixup, patched once the linker has placed every chunk. - Jumps within a procedure are patched here, as soon as their target - is known. +{ x64.pas: machine code for x86-64. The encoder writes the instructions the code generator needs, and - no others. Registers are numbered as the hardware numbers them. + no others, into the text of chunk.pas. Registers are numbered as the + hardware numbers them. Jumps within a procedure are patched here, as + soon as their target is known. - Depends on: scan, for errors. + Depends on: scan, for errors; chunk, for the code buffer and fixups. Leaves out: choosing instructions; that is gen.pas. } unit x64; @@ -20,7 +14,7 @@ interface -uses scan, diag; +uses scan, diag, chunk; const RAX = 0; RCX = 1; RDX = 2; RBX = 3; RSP = 4; RBP = 5; RSI = 6; RDI = 7; @@ -41,8 +35,6 @@ NoLabel = -1; type - TSection = (secText, secRodata, secBss); - TMem = record base: longint; { a register, or RIP } index: longint; { a register, or NoIndex } @@ -51,66 +43,10 @@ chunk: longint; { with RIP: the chunk addressed } end; - TChunk = record - sec: TSection; - start, size, align: longint; { in its section's buffer } - firstFix, numFix: longint; { its fixups, text chunks only } - module, name: longint; { for the symbol table; -1 if none } - adr: int64; { its address, set by the linker } - live: boolean; { reached from the entry point } - ext: boolean; { bss: the address of a C symbol, its name } - reals: boolean; { code: computes with reals, first at realsAt } - realsAt: TPos; - end; - - { A place in the source whose code starts at a place in text: for - gdb, and for Rt to say where a failed check or a signal was } - TLine = record - at, chunk: longint; { the place in text, and its chunk } - path, line, col: longint; { the file's path, interned, the line and column } - end; - - TFixup = record - at: longint; { the rel32 field, as an offset in text } - chunk: longint; { the chunk it refers to } - addend: longint; { added to the chunk's address } - end; - - PChunks = ^TChunkArray; - TChunkArray = array[0..MaxInt div SizeOf(TChunk) - 1] of TChunk; - PLines = ^TLineArray; - TLineArray = array[0..MaxInt div SizeOf(TLine) - 1] of TLine; - PFixups = ^TFixupArray; - TFixupArray = array[0..MaxInt div SizeOf(TFixup) - 1] of TFixup; - var - code: PBytes; { text } - pc: longint; { its length } - rodata: PBytes; - rolen: longint; - chunks: PChunks; - numChunks: longint; - fixups: PFixups; - numFixups: longint; - lines: PLines; - numLines: longint; - curFile: longint; { the file being compiled, for NoteLine } labelAt: longint; { the last place a jump was made to land } -function NewChunk(sec: TSection; module, name: longint): longint; -procedure BeginChunk(c: longint); -procedure EndChunk(c: longint); -procedure SetData(c: longint; p: PBytes; n, align: longint); -procedure SetBss(c: longint; size, align: longint); -function ExternChunk(name: longint): longint; -procedure NoteLine(line, col: longint); function Here: TMem; - -procedure Put1(b: longint); -procedure Put4(v: longint); -procedure Put4At(at, v: longint); -function Get4At(at: longint): longint; - function Mem(base: longint; disp: int64): TMem; function MemRip(chunk: longint; disp: longint): TMem; function MemIdx(base, index, scale: longint; disp: int64): TMem; @@ -169,151 +105,6 @@ implementation -var - codeCap, roCap, chunkCap, fixCap, lineCap: longint; - curChunk: longint; - -{ Buffers and chunks } - -procedure Room(n: longint); -begin - if pc + n > codeCap then begin - codeCap := codeCap * 2 + n; - code := ReAllocMem(code, codeCap); - end; -end; - -procedure Put1(b: longint); -begin - if pc + 16 > codeCap then Room(16); - code^[pc] := byte(b); - inc(pc); -end; - -procedure Put4(v: longint); -begin - if pc + 16 > codeCap then Room(16); - PLongint(@code^[pc])^ := v; - inc(pc, 4); -end; - -procedure Put4At(at, v: longint); -begin - PLongint(@code^[at])^ := v; -end; - -function Get4At(at: longint): longint; -begin - Get4At := PLongint(@code^[at])^; -end; - -procedure Put8(v: int64); -begin - Put4(longint(v and $FFFFFFFF)); - Put4(longint(v shr 32)); -end; - -function NewChunk(sec: TSection; module, name: longint): longint; -begin - if numChunks = chunkCap then begin - chunkCap := chunkCap * 2; - chunks := ReAllocMem(chunks, chunkCap * SizeOf(TChunk)); - end; - FillChar(chunks^[numChunks], SizeOf(TChunk), 0); - chunks^[numChunks].sec := sec; - chunks^[numChunks].module := module; - chunks^[numChunks].name := name; - chunks^[numChunks].align := 1; - chunks^[numChunks].size := -1; { not yet defined } - NewChunk := numChunks; - inc(numChunks); -end; - -procedure BeginChunk(c: longint); -begin - { code is aligned to 16 bytes, padded with int3 } - while pc and 15 <> 0 do Put1($CC); - curChunk := c; - chunks^[c].start := pc; - chunks^[c].align := 16; - chunks^[c].firstFix := numFixups; -end; - -procedure EndChunk(c: longint); -begin - chunks^[c].size := pc - chunks^[c].start; - chunks^[c].numFix := numFixups - chunks^[c].firstFix; -end; - -procedure SetData(c: longint; p: PBytes; n, align: longint); -begin - if rolen + n > roCap then begin - roCap := roCap * 2 + n; - rodata := ReAllocMem(rodata, roCap); - end; - Move(p^, rodata^[rolen], n); - chunks^[c].start := rolen; - chunks^[c].size := n; - chunks^[c].align := align; - inc(rolen, n); -end; - -procedure SetBss(c: longint; size, align: longint); -begin - chunks^[c].size := size; - chunks^[c].align := align; -end; - -{ The code from here on is for line and column of the current file. A - place with no code of its own gives way to the next. } -procedure NoteLine(line, col: longint); -begin - if (numLines > 0) and (lines^[numLines - 1].at = pc) then dec(numLines); - if (numLines > 0) and (lines^[numLines - 1].chunk = curChunk) and (lines^[numLines - 1].line = line) - and (lines^[numLines - 1].col = col) and (lines^[numLines - 1].path = curFile) then exit; - if numLines = lineCap then begin - lineCap := lineCap * 2; - lines := ReAllocMem(lines, lineCap * SizeOf(TLine)); - end; - lines^[numLines].at := pc; - lines^[numLines].chunk := curChunk; - lines^[numLines].path := curFile; - lines^[numLines].line := line; - lines^[numLines].col := col; - inc(numLines); -end; - -{ The address of the code about to be written, as an operand } -function Here: TMem; -begin - Here := MemRip(curChunk, pc - chunks^[curChunk].start); -end; - -{ The quadword that holds the address of C's symbol name, filled in - when the program starts; one for each name. } -function ExternChunk(name: longint): longint; -var c: longint; -begin - for c := 0 to numChunks - 1 do - if chunks^[c].ext and (chunks^[c].name = name) then exit(c); - c := NewChunk(secBss, -1, name); - SetBss(c, 8, 8); - chunks^[c].ext := true; - ExternChunk := c; -end; - -procedure AddFixup(at, chunk, addend: longint); -begin - if numFixups = fixCap then begin - fixCap := fixCap * 2; - fixups := ReAllocMem(fixups, fixCap * SizeOf(TFixup)); - end; - fixups^[numFixups].at := at; - fixups^[numFixups].chunk := chunk; - fixups^[numFixups].addend := addend; - inc(numFixups); -end; - { Operands } function Mem(base: longint; disp: int64): TMem; @@ -336,6 +127,12 @@ MemIdx.scale := scale; end; +{ The address of the code about to be written, as an operand } +function Here: TMem; +begin + Here := MemRip(curChunk, pc - chunks^[curChunk].start); +end; + { Encoding. An instruction is: a legacy prefix, REX, the opcode, ModRM, SIB and displacement. Opcodes of more than one byte are given with their first byte in the low eight bits. } @@ -676,20 +473,4 @@ FixLinkTo(L, pc); end; -initialization - codeCap := 1 shl 20; - code := GetMem(codeCap); - pc := 0; - roCap := 1 shl 16; - rodata := GetMem(roCap); - rolen := 0; - chunkCap := 1 shl 10; - chunks := GetMem(chunkCap * SizeOf(TChunk)); - numChunks := 0; - fixCap := 1 shl 12; - fixups := GetMem(fixCap * SizeOf(TFixup)); - numFixups := 0; - lineCap := 1 shl 12; - lines := GetMem(lineCap * SizeOf(TLine)); - numLines := 0; end. diff --git a/test/enctest.pas b/test/enctest.pas index 07668c1..4179683 100644 --- a/test/enctest.pas +++ b/test/enctest.pas @@ -2,7 +2,7 @@ of the encoder in x64.pas. } program enctest; {$mode objfpc}{$H-} -uses scan, x64, link, elf; +uses scan, chunk, x64, link, elf; var e, d: longint; L: longint; begin d := NewChunk(secBss, -1, Intern('data', 4)); SetBss(d, 8, 8); @@ -29,5 +29,6 @@ Cvtts2si(RAX, 0, false); Cvtts2si(RAX, 0, true); Btc(RAX, 63); L := NoLabel; Jcc(ccE, L); Jmp(L); FixLink(L); JmpBack(chunks^[e].start); JccBack(ccNE, chunks^[e].start); EndChunk(e); + MarkLive(e); WriteElf(ParamStr(1), e); end. diff --git a/test/handtest.pas b/test/handtest.pas index 509808a..833d963 100644 --- a/test/handtest.pas +++ b/test/handtest.pas @@ -5,7 +5,7 @@ left out. } program handtest; {$mode objfpc}{$H-} -uses scan, x64, link, elf; +uses scan, chunk, x64, link, elf; var entry, msg, count, bump, unused: longint; s: shortstring; begin s := 'hand'#10; @@ -41,5 +41,6 @@ Syscall; EndChunk(entry); + MarkLive(entry); WriteElf(ParamStr(1), entry); end.