From e514b2392778dfb478f3ed2c2031a2a999ac04c8 Mon Sep 17 00:00:00 2001 From: Luis <42945842+ldiaz94@users.noreply.github.com> Date: Mon, 12 Oct 2026 10:01:48 +0100 Subject: [PATCH] Step 9b: assembly procedures in place of byte procedures x64.pas's Assemble reads a code procedure's instructions, Intel syntax as NASM writes it (report 2026-10.12, section 8 and appendix A), up to end, and encodes them with OpM/OpR: two-operand ALU ops, mov, test, xchg, cmpxchg, xadd (with lock), lea, movzx/movsx/movsxd, the F7/FF group, imul, shifts, push/pop, call/jmp, setcc, cmovcc, jumps to labels (chains as the compiler's own), SSE sd/ss arithmetic, movsd, movss, movq/movd, ucomis, the conversions, and a table of plain ones (ret, syscall, cpuid, rdtsc, pause, fences, ...); db for the rest. Registers by name in four sizes and xmm0-15; [base + index * scale + disp] with byte/word/dword/qword; constants through parse's ConstExpr, which gen's CodeProc hands in. OpR takes byte registers spl-dil. Every code procedure in lib, examples and tests is assembly now; Pretty indents a code block as begin's, Doc skips it, vim and emacs indent it. test/run/Asm checks what each kind computes; test/err/Asm* the assembler's errors. --- diff --git a/PLAN.md b/PLAN.md index 242bce8..e737a49 100644 --- a/PLAN.md +++ b/PLAN.md @@ -147,7 +147,7 @@ before a division; chosen per target. A `nil` test is left out only where the offset falls in the unmapped page at address 0. On x86-64 that means a field past 4,095 bytes still gets one. -- [ ] 9b. Assembly procedures in place of byte procedures: the +- [x] 9b. Assembly procedures in place of byte procedures: the target's own syntax (appendix A), for the instructions the encoder knows and a few of the system's, bytes for the rest. - [ ] 9c. `raz -S`: each line of source with its instructions, named diff --git a/doc/compiler.md b/doc/compiler.md index caa44dc..a642271 100644 --- a/doc/compiler.md +++ b/doc/compiler.md @@ -12,10 +12,10 @@ | `src/scan.pas` | 851 | 722 | Symbols, literals, comments, positions | | `src/sym.pas` | 596 | 497 | Types, objects, scopes, layout | | `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,290 | 1,020 | 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/x64.pas` | 834 | 694 | The instruction encoder, jumps within a procedure, the assembler | +| `src/gen.pas` | 1,319 | 1,037 | The stack machine, for x86-64: values, operations, checks, calls, frames | +| `src/item.pas` | 1,318 | 1,100 | Items: types, constants, variables, operators, conversions, calls | +| `src/parse.pas` | 2,529 | 2,267 | 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` | 188 | 141 | The command line | @@ -234,6 +234,15 @@ `test/enctest.pas` emits one of each for `objdump` to check. `Here` is the address of the code being written, as an operand. +The assembler, `Assemble`, reads a code procedure's instructions with +the scanner, Intel's syntax as NASM writes it, and encodes them with +`OpM` and `OpR`: `Operand` reads a register, a memory operand or a +constant (by the parser's `ConstExpr`, handed in), and a few tables +give the operations of a kind their opcodes (`Alus`, `Unaries`, +`Shifts`, `SseOps`, `Plain`). Labels are chains of jumps, as below. +`db` gives bytes it doesn't know. `RegNames` and `CondNames` are the +names of the registers and conditions. + 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 @@ -414,7 +423,8 @@ Then declarations: `Declarations` reads `const`, `type`, `var`, `proc` and `extern`, each one through `Declaration`, a recovery point, which calls `ConstDecl`, `TypeDecl`, `VarDecl`, `ProcDecl` or `ExternDecl`. `ProcDecl` handles forward declarations, code procedures -(`CodeBody`, which just copies the bytes) and bodies (`Body`). +(`CodeBody`, which checks the signature and has gen's `CodeProc` run +the target's assembler) and bodies (`Body`). `ParseType` and its helpers (`RecordType`, `VariantType`, `Signature`, `EnumType`) build `TType`s. diff --git a/editor/emacs/raz-mode.el b/editor/emacs/raz-mode.el index 8775d86..e264480 100644 --- a/editor/emacs/raz-mode.el +++ b/editor/emacs/raz-mode.el @@ -62,10 +62,10 @@ ;;; Indenting (defconst raz--decl - "^[ \t]*\\(?:module\\|import\\|link\\|extern\\|proc\\|const\\|type\\|var\\|begin\\)\\_>") + "^[ \t]*\\(?:module\\|import\\|link\\|extern\\|proc\\|const\\|type\\|var\\|begin\\|code\\)\\_>") (defconst raz--leading "^[ \t]*\\(?:or\\|and\\)\\_>") (defconst raz--block-word - "\\_<\\(if\\|while\\|for\\|match\\|record\\|variant\\|begin\\|repeat\\|end\\|until\\)\\_>") + "\\_<\\(if\\|while\\|for\\|match\\|record\\|variant\\|begin\\|repeat\\|code\\|end\\|until\\)\\_>") (defun raz--line (n) "The text of line N." diff --git a/editor/vim/indent/raz.vim b/editor/vim/indent/raz.vim index 8df276d..ccb433a 100644 --- a/editor/vim/indent/raz.vim +++ b/editor/vim/indent/raz.vim @@ -19,10 +19,10 @@ endif " searchpair() needs groups that don't capture -let s:opener = '\C\<\%(if\|while\|for\|match\|record\|variant\|begin\|repeat\)\>' +let s:opener = '\C\<\%(if\|while\|for\|match\|record\|variant\|begin\|repeat\|code\)\>' let s:closer = '\C\<\%(end\|until\)\>' let s:skip = 'synIDattr(synID(line("."), col("."), 1), "name") =~? "string\\|char\\|comment"' -let s:decl = '^\s*\%(module\|import\|link\|extern\|proc\|const\|type\|var\|begin\)\>' +let s:decl = '^\s*\%(module\|import\|link\|extern\|proc\|const\|type\|var\|begin\|code\)\>' " The line's code, without strings, characters and comments. function! s:Code(lnum) @@ -81,7 +81,7 @@ let n = 0 let i = 0 while 1 - let m = matchstrpos(a:code, '\C\<\%(if\|while\|for\|record\|variant\|begin\|repeat\|end\|until\)\>', i) + let m = matchstrpos(a:code, '\C\<\%(if\|while\|for\|record\|variant\|begin\|repeat\|code\|end\|until\)\>', i) if m[1] < 0 return n endif diff --git a/examples/Cpu.raz b/examples/Cpu.raz index df62220..29ae5cd 100644 --- a/examples/Cpu.raz +++ b/examples/Cpu.raz @@ -5,15 +5,17 @@ (* cpuid leaf 0: puts the 12 bytes of the vendor in buf, rdi. *) proc vendor(buf: ^U8); -code 53H, (* push rbx *) - 49H, 89H, 0F8H, (* mov r8, rdi *) - 31H, 0C0H, (* xor eax, eax *) - 0FH, 0A2H, (* cpuid *) - 41H, 89H, 18H, (* mov [r8], ebx *) - 41H, 89H, 50H, 04H, (* mov [r8+4], edx *) - 41H, 89H, 48H, 08H, (* mov [r8+8], ecx *) - 5BH, (* pop rbx *) - 0C3H; (* ret *) +code + push rbx; + mov r8, rdi; + xor eax, eax; + cpuid; + mov [r8], ebx; + mov [r8 + 4], edx; + mov [r8 + 8], ecx; + pop rbx; + ret; +end vendor; proc main*; var buf: [12]U8; i: INT; ok: BOOL; diff --git a/lib/Math.raz b/lib/Math.raz index a081eda..7bd72a6 100644 --- a/lib/Math.raz +++ b/lib/Math.raz @@ -36,8 +36,10 @@ end; proc sqrt*(x: F64): F64; -code 0F2H, 0FH, 51H, 0C0H, (* sqrtsd xmm0, xmm0 *) - 0C3H; (* ret *) +code + sqrtsd xmm0, xmm0; + ret; +end sqrt; (* The largest whole number not above x. One of 2^52 or more is whole already, and so are an infinity and NaN. *) @@ -109,9 +111,11 @@ (* a times b: the low 64 bits of the product, and the high. *) proc mul(a, b: U64): (U64, U64); -code 48H, 89H, 0F8H, (* mov rax, rdi *) - 48H, 0F7H, 0E6H, (* mul rsi *) - 0C3H; (* ret *) +code + mov rax, rdi; + mul rsi; + ret; +end mul; (* 64 bits of t from bit s on, the first bit of t[0] being 0. *) proc window(t: []U64; s: INT): U64; diff --git a/lib/Rt.raz b/lib/Rt.raz index e5c23b1..0b98b86 100644 --- a/lib/Rt.raz +++ b/lib/Rt.raz @@ -194,8 +194,10 @@ (* Returns from a signal handler: rt_sigreturn *) proc sigReturn; -code 0B8H, 0FH, 0, 0, 0, (* mov eax, 15 *) - 0FH, 05H; (* syscall *) +code + mov eax, 15; + syscall; +end sigReturn; (* A signal stops the program: says where it was and why on standard error, and returns to the instruction that faulted. The handler was diff --git a/lib/Thread.linux-x86_64.raz b/lib/Thread.linux-x86_64.raz index a102d01..f9817fe 100644 --- a/lib/Thread.linux-x86_64.raz +++ b/lib/Thread.linux-x86_64.raz @@ -41,22 +41,25 @@ registers but rsp of its own to find them by. Returns the new thread's id, or minus an errno. *) proc start(flags: INT; stack: ^U8; ptid, ctid: ^INT; fn: proc(arg: ^U8); arg: ^U8): INT; -code 48H, 83H, 0EEH, 10H, (* sub rsi, 16 *) - 4CH, 89H, 06H, (* mov [rsi], r8 *) - 4CH, 89H, 4EH, 08H, (* mov [rsi + 8], r9 *) - 49H, 89H, 0CAH, (* mov r10, rcx *) - 45H, 31H, 0C0H, (* xor r8d, r8d: no tls *) - 0B8H, 38H, 0, 0, 0, (* mov eax, 56: clone *) - 0FH, 05H, (* syscall *) - 48H, 85H, 0C0H, (* test rax, rax *) - 75H, 0DH, (* jnz parent *) - 58H, (* pop rax: fn *) - 5FH, (* pop rdi: arg *) - 0FFH, 0D0H, (* call rax *) - 31H, 0FFH, (* xor edi, edi *) - 0B8H, 3CH, 0, 0, 0, (* mov eax, 60: exit, this thread only *) - 0FH, 05H, (* syscall *) - 0C3H; (* parent: ret *) +code + sub rsi, 16; + mov [rsi], r8; + mov [rsi + 8], r9; + mov r10, rcx; + xor r8d, r8d; (* no tls *) + mov eax, 56; (* clone *) + syscall; + test rax, rax; + jnz parent; + pop rax; (* fn *) + pop rdi; (* arg *) + call rax; + xor edi, edi; + mov eax, 60; (* exit, this thread only *) + syscall; + parent: + ret; +end start; proc futex(word: ^INT; op, val: INT): INT; begin diff --git a/src/gen.pas b/src/gen.pas index dbf4adc..4b3476e 100644 --- a/src/gen.pas +++ b/src/gen.pas @@ -147,6 +147,7 @@ procedure RunDefer(at: longint); function EntryPoint(dynamic: boolean; first: PModule; main: PObj; cExit, places, placesVar, exitProc: longint): longint; +procedure CodeProc(c: longint; constExpr: TConstFn); implementation @@ -1297,6 +1298,15 @@ Ud2; EndChunk(start); EntryPoint := entry; +end; + +{ A code procedure: its instructions, read by the assembler (x64.pas), + are the whole of chunk c } +procedure CodeProc(c: longint; constExpr: TConstFn); +begin + BeginChunk(c); + Assemble(constExpr); + EndChunk(c); end; initialization diff --git a/src/parse.pas b/src/parse.pas index c4e65f0..db36858 100644 --- a/src/parse.pas +++ b/src/parse.pas @@ -1671,7 +1671,7 @@ end; procedure CodeBody(p: PObj; sig: PType; const at: TPos); -var q: PObj; ni, nf: longint; v: int64; start: TPos; +var q: PObj; ni, nf: longint; begin ni := 0; nf := 0; q := sig^.fields; @@ -1690,16 +1690,8 @@ or (q^.typ^.form = fReal) or (q^.next^.typ^.form = fReal) then MarkAt(at, 'a code procedure returns two results only in rax and rdx'); end else if not IsScalar(sig^.base) then MarkAt(at, 'a code procedure returns a single value'); - BeginChunk(p^.chunk); - repeat - start := TokPos; - v := ConstExpr; - if (v < 0) or (v > 255) then MarkAt(SpanFrom(start), 'expected a byte from 0 to 255, found ' + IntStr(v)); - Put1(v); - if tok <> sComma then break; - Next; - until false; - EndChunk(p^.chunk); + CodeProc(p^.chunk, @ConstExpr); + Expect(sEnd); end; procedure ProcDecl; @@ -1738,9 +1730,7 @@ Next; p^.isCode := true; CodeBody(p, sig, at); - exit; - end; - if checkMode then SkipBody else Body(p, sig, line); + end else if checkMode then SkipBody else Body(p, sig, line); if tok = sIdent then begin if id <> n then Mark('expected ' + NameOf(n) + ', found ' + NameOf(id)); Next; diff --git a/src/x64.pas b/src/x64.pas index 63ebfec..4a34e27 100644 --- a/src/x64.pas +++ b/src/x64.pas @@ -103,6 +103,24 @@ procedure FixLink(L: longint); procedure FixLinkTo(L, target: longint); +type + TConstFn = function: int64; + +const + RegNames: array[0..3, 0..15] of string[5] = ( + ('rax', 'rcx', 'rdx', 'rbx', 'rsp', 'rbp', 'rsi', 'rdi', + 'r8', 'r9', 'r10', 'r11', 'r12', 'r13', 'r14', 'r15'), + ('eax', 'ecx', 'edx', 'ebx', 'esp', 'ebp', 'esi', 'edi', + 'r8d', 'r9d', 'r10d', 'r11d', 'r12d', 'r13d', 'r14d', 'r15d'), + ('ax', 'cx', 'dx', 'bx', 'sp', 'bp', 'si', 'di', + 'r8w', 'r9w', 'r10w', 'r11w', 'r12w', 'r13w', 'r14w', 'r15w'), + ('al', 'cl', 'dl', 'bl', 'spl', 'bpl', 'sil', 'dil', + 'r8b', 'r9b', 'r10b', 'r11b', 'r12b', 'r13b', 'r14b', 'r15b')); + CondNames: array[0..15] of string[3] = ('o', 'no', 'b', 'ae', 'e', 'ne', + 'be', 'a', 's', 'ns', 'p', 'np', 'l', 'ge', 'le', 'g'); + +procedure Assemble(constExpr: TConstFn); + implementation { Operands } @@ -145,7 +163,10 @@ until op = 0; end; -procedure Prefix(pfx: longint; w: boolean; reg, index, base: longint; byteReg: boolean); +{ The legacy prefix pfx, if any, and REX: wide is REX.W; byte4 says + a byte register of 4 to 7 is used, spl to dil, which exist only with + a REX prefix. } +procedure Prefix(pfx: longint; w: boolean; reg, index, base: longint; byte4: boolean); var rex: longint; begin if pfx <> 0 then Put1(pfx); @@ -154,14 +175,14 @@ if reg >= 8 then rex := rex or 4; if index >= 8 then rex := rex or 2; if base >= 8 then rex := rex or 1; - { sil and dil exist only with a REX prefix } - if (rex <> 0) or (byteReg and (reg >= 4) and (reg <= 7)) then Put1($40 or rex); + if (rex <> 0) or byte4 then Put1($40 or rex); end; { op reg, [mem] } procedure OpM(pfx: longint; w: boolean; op, reg: longint; const m: TMem; byteReg: boolean = false); var md, b, sc: longint; begin + byteReg := byteReg and (reg >= 4) and (reg <= 7); if m.base = RIP then Prefix(pfx, w, reg, NoIndex, 0, byteReg) else Prefix(pfx, w, reg, m.index, m.base, byteReg); Opcode(op); @@ -190,9 +211,9 @@ end; { op reg, rm (both registers) } -procedure OpR(pfx: longint; w: boolean; op, reg, rm: longint); +procedure OpR(pfx: longint; w: boolean; op, reg, rm: longint; byteReg: boolean = false); begin - Prefix(pfx, w, reg, NoIndex, rm, false); + Prefix(pfx, w, reg, NoIndex, rm, byteReg and ((reg in [4..7]) or (rm in [4..7]))); Opcode(op); Put1($C0 or (reg and 7) shl 3 or (rm and 7)); end; @@ -471,6 +492,343 @@ procedure FixLink(L: longint); begin FixLinkTo(L, pc); +end; + + +{ The assembler, for code procedures: x86-64 in Intel's syntax as NASM + writes it (report, appendix A). It reads instructions with the + scanner up to end, and encodes them with OpM and OpR; constants are + read by the parser's constExpr. } + +const + NoBase = -3; { a memory operand's base, not yet read } + +type + TOpKind = (oReg, oXmm, oMem, oImm); + TOpd = record + kind: TOpKind; + r, size: longint; { oReg, oXmm: the register and its size; oMem: its size, or 0 } + m: TMem; + v: int64; { oImm } + end; + +{ The current symbol as a word: an identifier, or a reserved word that + is also an instruction } +function AsmWord: shortstring; +begin + case tok of + sIdent: AsmWord := NameOf(id); + sAnd: AsmWord := 'and'; + sOr: AsmWord := 'or'; + sXor: AsmWord := 'xor'; + sNot: AsmWord := 'not'; + sDiv: AsmWord := 'div'; + sShl: AsmWord := 'shl'; + sShr: AsmWord := 'shr'; + else AsmWord := ''; + end; +end; + +{ Whether w names a register: rax, eax, ax, al and so on, or xmm0 to + xmm15 (size 16) } +function IsReg(const w: shortstring; var r, size: longint): boolean; +const Sizes: array[0..3] of longint = (8, 4, 2, 1); +var i, j, e: longint; +begin + IsReg := true; + for i := 0 to 3 do + for j := 0 to 15 do + if RegNames[i, j] = w then begin r := j; size := Sizes[i]; exit end; + size := 16; + Val(copy(w, 4, 2), r, e); + IsReg := (copy(w, 1, 3) = 'xmm') and (length(w) > 3) and (e = 0) and (r in [0..15]); +end; + +{ Which word of list, a list of words each with a space either side, + w is, from 0; -1 if none } +function WordIndex(const w, list: shortstring): longint; +var i, k: longint; +begin + k := pos(' ' + w + ' ', list); + WordIndex := -1; + if k = 0 then exit; + WordIndex := 0; + for i := 2 to k do if list[i] = ' ' then inc(WordIndex); +end; + +{ The condition a name ends in: e of je, nz of jnz } +function Cond(const w: shortstring): longint; +const + Alias: array[0..11] of string[3] = ('c', 'nae', 'nc', 'nb', 'z', 'nz', 'na', 'nbe', 'nge', 'nl', 'ng', 'nle'); + AliasCc: array[0..11] of longint = (2, 2, 3, 3, 4, 5, 6, 7, 12, 13, 14, 15); +var i: longint; +begin + for i := 0 to 15 do if CondNames[i] = w then exit(i); + for i := 0 to 11 do if Alias[i] = w then exit(AliasCc[i]); + Cond := -1; +end; + +procedure Operand(var o: TOpd; constExpr: TConstFn); +var w: shortstring; r, size, sz: longint; st: TScanState; +begin + FillChar(o, SizeOf(o), 0); + w := AsmWord; + sz := 0; + if w = 'byte' then sz := 1 else if w = 'word' then sz := 2 + else if w = 'dword' then sz := 4 else if w = 'qword' then sz := 8; + if sz <> 0 then begin Next; w := AsmWord end; + if tok = sLbrak then begin + { [base + index * scale + disp], the displacement last } + Next; + o.kind := oMem; o.size := sz; + o.m := Mem(NoBase, 0); + repeat + if IsReg(AsmWord, r, size) and (size = 8) then begin + Next; + if tok = sTimes then begin Next; o.m.index := r; o.m.scale := constExpr() end + else if o.m.base = NoBase then o.m.base := r + else begin o.m.index := r; o.m.scale := 1 end; + end else o.m.disp := o.m.disp + constExpr(); + if not (tok in [sPlus, sMinus]) then break; + SaveScan(st); + Next; + if not IsReg(AsmWord, r, size) and (st.tok = sMinus) then RestoreScan(st); + until false; + if (tok <> sRbrak) or (o.m.base = NoBase) or not (o.m.scale in [1, 2, 4, 8]) then + Mark('expected a memory operand, [base + index * scale + disp]'); + Next; + end else if IsReg(w, o.r, o.size) then begin + if o.size = 16 then o.kind := oXmm else o.kind := oReg; + Next; + end else begin + o.kind := oImm; + o.v := constExpr(); + end; +end; + +{ op with register reg and the register or memory operand o } +procedure RM(pfx: longint; w: boolean; op, reg: longint; const o: TOpd; byteReg: boolean = false); +begin + if o.kind = oMem then OpM(pfx, w, op, reg, o.m, byteReg) + else OpR(pfx, w, op, reg, o.r, byteReg); +end; + +procedure PutImm(v: int64; size: longint); +begin + case size of + 1: Put1(v); + 2: begin Put1(v); Put1(v shr 8) end; + else Put4(v); + end; +end; + +procedure Assemble(constExpr: TConstFn); +const + Alus = ' add or adc sbb and sub xor cmp '; + Unaries = ' not neg mul imul div idiv '; + Shifts = ' rol ror rcl rcr shl shr sal sar '; + SseOps = ' sqrt add mul sub min div max '; + SseCodes: array[0..6] of longint = ($51, $58, $59, $5C, $5D, $5E, $5F); + Plain: array[0..14] of string[7] = ('ret', 'leave', 'syscall', 'cpuid', 'rdtsc', + 'pause', 'nop', 'ud2', 'int3', 'hlt', 'cqo', 'cdq', 'mfence', 'lfence', 'sfence'); + PlainOp: array[0..14] of longint = ($C3, $C9, $050F, $A20F, $310F, + $90F3, $90, $0B0F, $CC, $F4, $9948, $99, $F0AE0F, $E8AE0F, $F8AE0F); +var + w: shortstring; o: array[0..2] of TOpd; n, i, k, size, pfx, cc: longint; + wide, byteOp: boolean; at, start: TPos; v: int64; + names, places, chains: array[0..63] of longint; numLabels: longint; + usedAt: array[0..63] of TPos; + + { the label called n, entered if new } + function Lab(n: longint): longint; + var i: longint; + begin + for i := 0 to numLabels - 1 do if names[i] = n then exit(i); + if numLabels > High(names) then Mark('more than 64 labels'); + names[numLabels] := n; places[numLabels] := -1; chains[numLabels] := NoLabel; + usedAt[numLabels] := TokPos; + Lab := numLabels; + inc(numLabels); + end; + + procedure Bad; + begin + MarkAt(at, 'can''t assemble ' + w + ' with these operands'); + end; + + { an instruction of two operands: a register or memory, and a + register (opcode toRM), the other way (fromRM), or an immediate + (opImm /digit, or none if opImm < 0) } + procedure Two(toRM, fromRM, opImm, digit: longint); + begin + if n <> 2 then Bad; + if o[1].kind = oImm then begin + if (o[0].kind = oImm) or (opImm < 0) then Bad; + if (opImm = $81) and not byteOp and (o[1].v >= -128) and (o[1].v <= 127) then begin + RM(pfx, wide, $83, digit, o[0]); { a byte, sign-extended } + Put1(o[1].v); + end else begin + RM(pfx, wide, opImm - ord(byteOp), digit, o[0]); + PutImm(o[1].v, size); + end; + end else if (o[1].kind = oReg) and (o[0].kind in [oReg, oMem]) then + RM(pfx, wide, toRM - ord(byteOp), o[1].r, o[0], byteOp) + else if (o[0].kind = oReg) and (o[1].kind = oMem) then + RM(pfx, wide, fromRM - ord(byteOp), o[0].r, o[1], byteOp) + else Bad; + end; + +begin + numLabels := 0; + while not (tok in [sEnd, sEof]) do begin + at := TokPos; + w := AsmWord; + if tok = sSemicolon then begin Next; continue end; + if w = '' then Mark('expected an instruction'); + Next; + if tok = sColon then begin + k := Lab(Intern(@w[1], length(w))); + if places[k] >= 0 then MarkAt(at, 'label ' + w + ' is defined twice'); + places[k] := pc; + FixLink(chains[k]); + Next; + continue; + end; + if w = 'lock' then begin + Put1($F0); + w := AsmWord; + Next; + end; + cc := -1; + if w = 'db' then + repeat + start := TokPos; + v := constExpr(); + if (v < -128) or (v > 255) then MarkAt(SpanFrom(start), 'expected a byte from 0 to 255, found ' + IntStr(v)); + Put1(v); + if tok <> sComma then break; + Next; + until false + else if (w[1] = 'j') and ((w = 'jmp') or (Cond(copy(w, 2, 3)) >= 0)) and (tok = sIdent) then begin + { a jump to a label } + k := Lab(id); + Next; + if w <> 'jmp' then cc := Cond(copy(w, 2, 3)); + if places[k] >= 0 then begin + if cc < 0 then JmpBack(places[k]) else JccBack(cc, places[k]) + end else if cc < 0 then Jmp(chains[k]) else Jcc(cc, chains[k]); + end else begin + n := 0; + if tok <> sSemicolon then + repeat + if n > High(o) then Mark('too many operands'); + Operand(o[n], constExpr); + inc(n); + if tok <> sComma then break; + Next; + until false; + { the size: a register's, or what the memory operand says } + size := 8; + for i := n - 1 downto 0 do + if (o[i].kind = oReg) or (o[i].kind = oMem) and (o[i].size <> 0) then size := o[i].size; + if n > 0 then + if (o[0].kind = oReg) or (o[0].kind = oMem) and (o[0].size <> 0) then size := o[0].size; + wide := size = 8; + byteOp := size = 1; + if size = 2 then pfx := $66 else pfx := 0; + if WordIndex(w, Alus) >= 0 then begin + k := WordIndex(w, Alus); + Two(k * 8 + 1, k * 8 + 3, $81, k) + end + else if w = 'mov' then begin + if (n = 2) and (o[0].kind = oReg) and (o[1].kind = oImm) and (size >= 4) then begin + if wide then MovRI(o[0].r, o[1].v) + else begin Prefix(0, false, 0, NoIndex, o[0].r, false); Put1($B8 + o[0].r and 7); Put4(o[1].v) end; + end else Two($89, $8B, $C7, 0); + end else if w = 'test' then Two($85, $85, $F7, 0) + else if w = 'xchg' then Two($87, $87, -1, 0) + else if (w = 'cmpxchg') or (w = 'xadd') then begin + if (n <> 2) or (o[1].kind <> oReg) then Bad; + if w = 'xadd' then k := $C10F else k := $B10F; + RM(pfx, wide, k - ord(byteOp) shl 8, o[1].r, o[0], byteOp); + end else if w = 'lea' then begin + if (n <> 2) or (o[0].kind <> oReg) or (o[1].kind <> oMem) then Bad; + RM(pfx, wide, $8D, o[0].r, o[1]); + end else if (w = 'movzx') or (w = 'movsx') or (w = 'movsxd') then begin + if (n <> 2) or (o[0].kind <> oReg) or (o[1].kind = oImm) then Bad; + if w = 'movsxd' then k := $63 + else if o[1].size = 1 then k := $B60F + else if o[1].size = 2 then k := $B70F + else Bad; + if w = 'movsx' then k := k + $0800; + RM(pfx, wide, k, o[0].r, o[1], o[1].size = 1); + end else if ((WordIndex(w, Unaries) >= 0) and (n = 1)) or (w = 'inc') or (w = 'dec') then begin + if o[0].kind = oImm then Bad; + if w = 'inc' then RM(pfx, wide, $FF - ord(byteOp), 0, o[0], byteOp) + else if w = 'dec' then RM(pfx, wide, $FF - ord(byteOp), 1, o[0], byteOp) + else RM(pfx, wide, $F7 - ord(byteOp), WordIndex(w, Unaries) + 2, o[0], byteOp); + end else if w = 'imul' then begin + if (n < 2) or (o[0].kind <> oReg) or (o[1].kind = oImm) then Bad; + if n = 2 then RM(pfx, wide, $AF0F, o[0].r, o[1]) + else begin RM(pfx, wide, $69, o[0].r, o[1]); PutImm(o[2].v, size) end; + end else if WordIndex(w, Shifts) >= 0 then begin + k := WordIndex(w, Shifts); + if k = 6 then k := 4; { sal is shl } + if (n <> 2) or (o[0].kind = oImm) then Bad; + if o[1].kind = oImm then begin RM(pfx, wide, $C1 - ord(byteOp), k, o[0], byteOp); Put1(o[1].v) end + else if (o[1].kind = oReg) and (o[1].r = RCX) and (o[1].size = 1) then RM(pfx, wide, $D3 - ord(byteOp), k, o[0], byteOp) + else Bad; + end else if (w = 'push') or (w = 'pop') then begin + if (n <> 1) or (o[0].kind <> oReg) or not wide then Bad; + if w = 'push' then Push(o[0].r) else Pop(o[0].r); + end else if (w = 'call') or (w = 'jmp') then begin + if (n <> 1) or (o[0].kind = oImm) then Bad; + if w = 'call' then RM(0, false, $FF, 2, o[0]) else RM(0, false, $FF, 4, o[0]); + end else if (copy(w, 1, 3) = 'set') and (Cond(copy(w, 4, 3)) >= 0) then begin + if (n <> 1) or (o[0].kind = oImm) or (size <> 1) then Bad; + RM(0, false, $900F + Cond(copy(w, 4, 3)) shl 8, 0, o[0], true); + end else if (copy(w, 1, 4) = 'cmov') and (Cond(copy(w, 5, 3)) >= 0) then begin + if (n <> 2) or (o[0].kind <> oReg) or (o[1].kind = oImm) then Bad; + RM(pfx, wide, $400F + Cond(copy(w, 5, 3)) shl 8, o[0].r, o[1]); + end else if (length(w) > 2) and (WordIndex(copy(w, 1, length(w) - 2), SseOps) >= 0) + and ((copy(w, length(w) - 1, 2) = 'sd') or (copy(w, length(w) - 1, 2) = 'ss')) then begin + { sqrtsd, addss and the like: xmm, xmm or memory } + if (n <> 2) or (o[0].kind <> oXmm) or not (o[1].kind in [oXmm, oMem]) then Bad; + k := $0F or SseCodes[WordIndex(copy(w, 1, length(w) - 2), SseOps)] shl 8; + RM(RealPfx[w[length(w)] = 's'], false, k, o[0].r, o[1]); + end else if (w = 'movsd') or (w = 'movss') then begin + if w = 'movsd' then k := $F2 else k := $F3; + if (n = 2) and (o[0].kind = oXmm) and (o[1].kind in [oXmm, oMem]) then RM(k, false, $100F, o[0].r, o[1]) + else if (n = 2) and (o[0].kind = oMem) and (o[1].kind = oXmm) then RM(k, false, $110F, o[1].r, o[0]) + else Bad; + end else if (w = 'movq') or (w = 'movd') then begin + if (n = 2) and (o[0].kind = oXmm) and (o[1].kind in [oReg, oMem]) then RM($66, w = 'movq', $6E0F, o[0].r, o[1]) + else if (n = 2) and (o[1].kind = oXmm) and (o[0].kind in [oReg, oMem]) then RM($66, w = 'movq', $7E0F, o[1].r, o[0]) + else Bad; + end else if (w = 'ucomisd') or (w = 'ucomiss') then begin + if (n <> 2) or (o[0].kind <> oXmm) or not (o[1].kind in [oXmm, oMem]) then Bad; + if w = 'ucomisd' then RM($66, false, $2E0F, o[0].r, o[1]) else RM(0, false, $2E0F, o[0].r, o[1]); + end else if (w = 'cvtsi2sd') or (w = 'cvtsi2ss') then begin + if (n <> 2) or (o[0].kind <> oXmm) or not (o[1].kind in [oReg, oMem]) then Bad; + RM(RealPfx[w = 'cvtsi2ss'], o[1].size <> 4, $2A0F, o[0].r, o[1]); + end else if (w = 'cvttsd2si') or (w = 'cvttss2si') then begin + if (n <> 2) or (o[0].kind <> oReg) or not (o[1].kind in [oXmm, oMem]) then Bad; + RM(RealPfx[w = 'cvttss2si'], wide, $2C0F, o[0].r, o[1]); + end else if (w = 'cvtsd2ss') or (w = 'cvtss2sd') then begin + if (n <> 2) or (o[0].kind <> oXmm) or not (o[1].kind in [oXmm, oMem]) then Bad; + RM(RealPfx[w = 'cvtss2sd'], false, $5A0F, o[0].r, o[1]); + end else begin + k := 0; + while (k <= High(Plain)) and (Plain[k] <> w) do inc(k); + if (k > High(Plain)) or (n <> 0) then MarkAt(at, 'unknown instruction ' + w); + Opcode(PlainOp[k]); + end; + end; + if tok <> sSemicolon then Mark('expected ";"'); + Next; + end; + for k := 0 to numLabels - 1 do + if places[k] < 0 then MarkAt(usedAt[k], 'label ' + NameOf(names[k]) + ' isn''t defined'); end; end. diff --git a/test/err/AsmLabel.err b/test/err/AsmLabel.err new file mode 100644 index 0000000..f014608 --- /dev/null +++ b/test/err/AsmLabel.err @@ -0,0 +1,4 @@ +test/err/AsmLabel.raz:4:9: error: label nowhere isn't defined + 4 | jmp nowhere; + | ^^^^^^^ +raz: 1 error diff --git a/test/err/AsmLabel.raz b/test/err/AsmLabel.raz new file mode 100644 index 0000000..972d441 --- /dev/null +++ b/test/err/AsmLabel.raz @@ -0,0 +1,6 @@ +module AsmLabel; +proc f; +code + jmp nowhere; +end f; +end AsmLabel. diff --git a/test/err/AsmMemory.err b/test/err/AsmMemory.err new file mode 100644 index 0000000..bb99c29 --- /dev/null +++ b/test/err/AsmMemory.err @@ -0,0 +1,4 @@ +test/err/AsmMemory.raz:4:16: error: expected a memory operand, [base + index * scale + disp] + 4 | mov rax, [8]; + | ^ +raz: 1 error diff --git a/test/err/AsmMemory.raz b/test/err/AsmMemory.raz new file mode 100644 index 0000000..6bea013 --- /dev/null +++ b/test/err/AsmMemory.raz @@ -0,0 +1,6 @@ +module AsmMemory; +proc f; +code + mov rax, [8]; +end f; +end AsmMemory. diff --git a/test/err/AsmOperands.err b/test/err/AsmOperands.err new file mode 100644 index 0000000..3ace6e6 --- /dev/null +++ b/test/err/AsmOperands.err @@ -0,0 +1,4 @@ +test/err/AsmOperands.raz:4:5: error: can't assemble lea with these operands + 4 | lea rax, rbx; + | ^^^ +raz: 1 error diff --git a/test/err/AsmOperands.raz b/test/err/AsmOperands.raz new file mode 100644 index 0000000..fc8dc02 --- /dev/null +++ b/test/err/AsmOperands.raz @@ -0,0 +1,7 @@ +module AsmOperands; +proc f; +code + lea rax, rbx; + ret; +end f; +end AsmOperands. diff --git a/test/err/AsmUnknown.err b/test/err/AsmUnknown.err new file mode 100644 index 0000000..080d72a --- /dev/null +++ b/test/err/AsmUnknown.err @@ -0,0 +1,4 @@ +test/err/AsmUnknown.raz:4:5: error: unknown instruction frob + 4 | frob rax; + | ^^^^ +raz: 1 error diff --git a/test/err/AsmUnknown.raz b/test/err/AsmUnknown.raz new file mode 100644 index 0000000..140b7d8 --- /dev/null +++ b/test/err/AsmUnknown.raz @@ -0,0 +1,7 @@ +module AsmUnknown; +proc f; +code + frob rax; + ret; +end f; +end AsmUnknown. diff --git a/test/err/AtPByte.err b/test/err/AtPByte.err index f9a421d..ad851ce 100644 --- a/test/err/AtPByte.err +++ b/test/err/AtPByte.err @@ -1,4 +1,4 @@ -test/err/AtPByte.raz:3:6: error: expected a byte from 0 to 255, found 300 - 3 | code 300; - | ^^^ +test/err/AtPByte.raz:4:11: error: expected a byte from 0 to 255, found 300 + 4 | db 1, 300; + | ^^^ raz: 1 error diff --git a/test/err/AtPByte.raz b/test/err/AtPByte.raz index 936fdbc..1e07068 100644 --- a/test/err/AtPByte.raz +++ b/test/err/AtPByte.raz @@ -1,4 +1,6 @@ module AtPByte; proc f(a: I64); -code 300; +code + db 1, 300; +end; end AtPByte. diff --git a/test/err/GenCodeValue.raz b/test/err/GenCodeValue.raz index a05bfc9..b5c7926 100644 --- a/test/err/GenCodeValue.raz +++ b/test/err/GenCodeValue.raz @@ -1,5 +1,5 @@ module GenCodeValue; -type F = proc(): (I64, I64); proc Two(): (I64, I64); code 0C3H; +type F = proc(): (I64, I64); proc Two(): (I64, I64); code ret; end; proc main*; var f: F; begin diff --git a/test/err/StmtCodeParams.raz b/test/err/StmtCodeParams.raz index d42bd57..c84f606 100644 --- a/test/err/StmtCodeParams.raz +++ b/test/err/StmtCodeParams.raz @@ -1,4 +1,4 @@ module StmtCodeParams; proc f(a, b, c, d, e, f, g: I64); -code 0C3H; +code ret; end; end StmtCodeParams. diff --git a/test/err/StmtCodeResult.raz b/test/err/StmtCodeResult.raz index d972b73..6b27150 100644 --- a/test/err/StmtCodeResult.raz +++ b/test/err/StmtCodeResult.raz @@ -1,5 +1,5 @@ module StmtCodeResult; type R = record a: I64; end; proc f: R; -code 0C3H; +code ret; end; end StmtCodeResult. diff --git a/test/err/StmtCodeTakes.raz b/test/err/StmtCodeTakes.raz index 54fb107..fe26242 100644 --- a/test/err/StmtCodeTakes.raz +++ b/test/err/StmtCodeTakes.raz @@ -1,5 +1,5 @@ module StmtCodeTakes; type R = record a: I64; end; proc f(r: R); -code 0C3H; +code ret; end; end StmtCodeTakes. diff --git a/test/err/StmtCodeTwo.raz b/test/err/StmtCodeTwo.raz index 808af64..4682ba5 100644 --- a/test/err/StmtCodeTwo.raz +++ b/test/err/StmtCodeTwo.raz @@ -1,4 +1,4 @@ module StmtCodeTwo; proc f: (F64, I64); -code 0C3H; +code ret; end; end StmtCodeTwo. diff --git a/test/run/Asm.expect b/test/run/Asm.expect new file mode 100644 index 0000000..b2d7498 --- /dev/null +++ b/test/run/Asm.expect @@ -0,0 +1,9 @@ +35 +4321 0 +98 azc +142 6 +3 9 below +2 +13 +40 42 +42 42 diff --git a/test/run/Asm.raz b/test/run/Asm.raz new file mode 100644 index 0000000..1d421be --- /dev/null +++ b/test/run/Asm.raz @@ -0,0 +1,132 @@ +module Asm; +(* Code procedures in assembly: the instructions the assembler knows, + each checked by what it computes *) +import Out; + +const Seven = 7; + +(* a * 10 + b - 7, by lea, shifts and adds *) +proc tens(a, b: I64): I64; +code + lea rax, [rdi + rdi * 4]; + shl rax, 1; + add rax, rsi; + sub rax, Seven; + ret; +end tens; + +(* the sum of n quadwords at p, by a loop back to a label *) +proc sum(p: ^I64; n: INT): I64; +code + xor eax, eax; + test rsi, rsi; + jz done; + again: + add rax, [rdi]; + add rdi, 8; + dec rsi; + jnz again; + done: + ret; +end sum; + +(* the byte at p + i, zero-extended, and the byte there set to v *) +proc swapByte(p: ^U8; i: INT; v: U8): I64; +code + movzx eax, byte [rdi + rsi]; + mov [rdi + rsi * 1], dl; + ret; +end swapByte; + +(* a div b and a mod b, unsigned; two results in rax and rdx *) +proc udivmod(a, b: U64): (U64, U64); +code + mov rax, rdi; + xor edx, edx; + div rsi; + ret; +end udivmod; + +(* the larger of a and b, signed, by cmov; and whether a < b by setl *) +proc max(a, b: I64): I64; +code + cmp rdi, rsi; + mov rax, rdi; + cmovl rax, rsi; + ret; +end max; + +proc below(a, b: I64): BOOL; +code + xor eax, eax; + cmp rdi, rsi; + setl al; + ret; +end below; + +(* (x + y) * x, then its square root *) +proc real(x, y: F64): F64; +code + movsd xmm2, xmm0; + addsd xmm0, xmm1; + mulsd xmm0, xmm2; + sqrtsd xmm0, xmm0; + ret; +end real; + +(* -a, ~a and a * 3 + 1 for an I32, through eax *) +proc mix(a: I32): I64; +code + mov eax, edi; + neg eax; + not eax; + imul eax, eax, 3; + inc eax; + movsxd rax, eax; + ret; +end mix; + +(* XADD by hand: the old value of p^, which goes up by v *) +proc fetchAdd(p: ^INT; v: INT): INT; +code + mov rax, rsi; + lock xadd [rdi], rax; + ret; +end fetchAdd; + +(* the real 2.0, from its bits, through a general register *) +proc two: F64; +code + mov rax, 4000000000000000H; + movq xmm0, rax; + ret; +end two; + +(* bytes the assembler is given as they are: mov eax, 42; ret *) +proc answer: I64; +code + db 0B8H, 42, 0, 0, 0; + db 0C3H; +end answer; + +proc main*; +var a: [4]I64; s: [3]U8; q, r: U64; c: INT; +begin + Out.int(tens(4, 2)); Out.ln; + a := [1, 20, 300, 4000]; + Out.int(sum(ADR(a[0]), 4)); Out.str(" "); Out.int(sum(ADR(a[0]), 0)); Out.ln; + s := "abc"; + Out.int(swapByte(ADR(s[0]), 1, 'z')); Out.str(" "); Out.str(s[0..3]); Out.ln; + q, r := udivmod(1000, 7); + Out.int(I64(q)); Out.str(" "); Out.int(I64(r)); Out.ln; + Out.int(max(-5, 3)); Out.str(" "); Out.int(max(9, 3)); Out.str(" "); + if below(-1, 1) and not below(1, -1) then Out.str("below"); end; + Out.ln; + Out.int(I64(real(1.0, 3.0))); Out.ln; + Out.int(mix(5)); Out.ln; + c := 40; + Out.int(fetchAdd(ADR(c), 2)); Out.str(" "); Out.int(c); Out.ln; + Out.int(I64(two() * 21.0)); Out.str(" "); Out.int(answer()); Out.ln; +end; + +end Asm. diff --git a/test/run/Atomic.raz b/test/run/Atomic.raz index ccd5314..c4be7f6 100644 --- a/test/run/Atomic.raz +++ b/test/run/Atomic.raz @@ -4,9 +4,11 @@ var counter: INT; flag: UINT; p: ^INT; proc add3*(a, b, c: I64): I64; -code 48H, 8DH, 04H, 37H, (* lea rax, [rdi+rsi] *) - 48H, 01H, 0D0H, (* add rax, rdx *) - 0C3H; (* ret *) +code + lea rax, [rdi + rsi]; + add rax, rdx; + ret; +end add3; proc main*; var old: INT; ok: BOOL; v: ^VOLATILE INT; x: INT; diff --git a/test/run/Edge.raz b/test/run/Edge.raz index 227264b..cb84a64 100644 --- a/test/run/Edge.raz +++ b/test/run/Edge.raz @@ -10,9 +10,11 @@ (* rsp mod 16 at the call, as the callee sees it after its return address: always 8 when the caller keeps the stack aligned *) proc rspmod: I64; -code 48H, 89H, 0E0H, (* mov rax, rsp *) - 48H, 83H, 0E0H, 0FH, (* and rax, 15 *) - 0C3H; +code + mov rax, rsp; + and rax, 15; + ret; +end rspmod; proc next: I64; begin diff --git a/test/run/Results.raz b/test/run/Results.raz index ad3b514..f588c01 100644 --- a/test/run/Results.raz +++ b/test/run/Results.raz @@ -32,13 +32,16 @@ end; proc minmax(a, b: I64): (I64, I64); -code 48H, 89H, 0F8H, (* mov rax, rdi *) - 48H, 89H, 0F2H, (* mov rdx, rsi *) - 48H, 39H, 0F7H, (* cmp rdi, rsi *) - 7EH, 06H, (* jle +6 *) - 48H, 89H, 0F0H, (* mov rax, rsi *) - 48H, 89H, 0FAH, (* mov rdx, rdi *) - 0C3H; +code + mov rax, rdi; + mov rdx, rsi; + cmp rdi, rsi; + jle done; + mov rax, rsi; + mov rdx, rdi; + done: + ret; +end minmax; proc nothing: (I64, ERROR); begin diff --git a/test/run/Single.raz b/test/run/Single.raz index 32ce2ab..34349aa 100644 --- a/test/run/Single.raz +++ b/test/run/Single.raz @@ -15,9 +15,12 @@ extern proc fabsf(x: F32): F32; extern proc sqrt(x: F64): F64; -(* addss xmm0, xmm0; ret *) +(* x + x, by hand *) proc twice(x: F32): F32; -code 0F3H, 0FH, 58H, 0C0H, 0C3H; +code + addss xmm0, xmm0; + ret; +end twice; proc dot(a, b: Vec): F32; begin diff --git a/tools/Doc.raz b/tools/Doc.raz index 8f58dd0..1af4f69 100644 --- a/tools/Doc.raz +++ b/tools/Doc.raz @@ -146,15 +146,15 @@ return false; end; -(* A procedure's body: to the end that closes its begin, the procedure - name after it and its ;. *) +(* A procedure's body: to the end that closes its begin or code, the + procedure name after it and its ;. *) proc skipBody; var depth: INT; sawBegin: BOOL; begin depth := 0; sawBegin := false; while sc.kind # Scan.eof do - if is("begin") then + if is("begin") or is("code") then if depth = 0 then sawBegin := true; end; INC(depth); elsif is("if") or is("while") or is("for") or is("match") or is("record") or is("variant") then @@ -178,7 +178,7 @@ exp := name(); stop := toSemicolon(); next; - if is("forward") or is("code") then toSemicolon(); + if is("forward") then toSemicolon(); else skipBody; end; declaration("", exp, start, ds, de, stop); diff --git a/tools/Pretty.raz b/tools/Pretty.raz index e2eecce..14112eb 100644 --- a/tools/Pretty.raz +++ b/tools/Pretty.raz @@ -8,8 +8,8 @@ Every line break and comment stays where it is. A line is indented 4 spaces for each block it stands in: the statements of if, while, - for, repeat and begin, the fields of a record or variant, the - declarations of const, type and var. end, until, else, elsif and a + for, repeat and begin, the instructions of code, the fields of a + record or variant, the declarations of const, type and var. end, until, else, elsif and a match's arms stand at the level of the statement that opened them; module, import, proc, the sections and begin at the margin, with the comment just before them. A line that goes on with the expression of @@ -25,7 +25,7 @@ const width = 4; (* the spaces of a level *) - openers = "if while for match record variant begin repeat"; + openers = "if while for match record variant begin repeat code"; declarations = "module import link extern proc const type var begin code"; binaryWords = "div mod and or xor shl shr in"; binarySymbols = "+ - * / & | = # < <= > >= :=";