From ae086c9a5573670420299eb72353fc306c9a7f49 Mon Sep 17 00:00:00 2001 From: Luis <42945842+ldiaz94@users.noreply.github.com> Date: Tue, 13 Oct 2026 16:18:44 +0100 Subject: [PATCH] Seed: match on an integer or an enumeration by a jump table The arms come first and Dispatch after them: a table for four labels or more close together (JumpTable in gen: rip-relative, no relocations), else the chain of compares, each jumping back to its arm. Co-Authored-By: Claude Sonnet 5.5 --- diff --git a/doc/compiler.md b/doc/compiler.md index a820852..747b5e7 100644 --- a/doc/compiler.md +++ b/doc/compiler.md @@ -1017,9 +1017,15 @@ no declaration or expression takes it: `_ := e` loads a single value and drops it, and `MultiAssign` skips the results it stands for. 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 +labels in `IntArm`, which refuses a value in two of them. The arms +come first and the test after them: the match starts with a jump to +`Dispatch`, placed after the last arm, since a jump table can only be +made once every arm's place is known (an enumeration's arms are +picked the same way; a variant's, by its tag, arm by arm). +`Dispatch` makes a jump table (gen's `JumpTable`, whose comment shows +the code) for four labels or more that lie close together, else +compares and branches one label after another with `MatchRange`, each +jumping back to its arm. `Defer` is worth reading: a deferred statement is compiled where it stands, as a little subroutine of the procedure 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: diff --git a/self/README.md b/self/README.md index 94d5764..22f6162 100644 --- a/self/README.md +++ b/self/README.md @@ -47,7 +47,8 @@ comparison `a[0..n] = b[0..n]` (97 ms), a 256-entry table for the bytes of a name (84), and one for the symbols that are a byte each (75). What is left for the code generator, which would help every - module: a `match` on an integer is a chain of compares, each loading - the selector from the frame and jumping over a `jmp` (`je L1; jmp L2`), - where FPC makes a jump table; and the slice comparison is slower than - the loop it stands for. + module: the slice comparison is slower than the loop it stands for. + (The seed's `match` on an integer was a chain of compares, each + loading the selector from the frame and jumping over a `jmp`, where + FPC makes a jump table; now it makes one too, and the seed's `Scan` + runs on it.) diff --git a/src/gen.pas b/src/gen.pas index dfa5c8e..aeed68b 100644 --- a/src/gen.pas +++ b/src/gen.pas @@ -171,6 +171,8 @@ procedure JumpOut(op: TSym; signed: boolean; var L: longint); procedure CondValue(notOp: TSym; signed: boolean; fj, tj: longint); procedure JumpBack(top: longint); +function JumpTable(slot, lo: int64; n, elseAt: longint; var endL: longint): longint; +procedure TableEntry(table, target: longint); procedure AlignLoop; procedure Fix(L: longint); procedure FixTo(L, top: longint); @@ -1344,6 +1346,51 @@ procedure Fix(L: longint); begin FixLink(L); +end; + +{ A jump table, for a match on the integer in frame slot slot, whose + labels run from lo up for n values. The selector less lo, compared + unsigned (so below lo is above n too), is out of the table if it + isn't below n, and goes to the else arm at elseAt, or, if there is + none, to endL, the end of the match. Else it indexes a table of + 4-byte offsets, each from the start of the lea, that follows the + jump, and the code jumps to its start plus the entry: + + mov rax, [slot] + sub rax, lo + cmp rax, n - 1 + ja else + lea rcx, [rip + start] start: this very lea + movsxd rax, [rcx + rax*4 + 17] + add rax, rcx + jmp rax + table: .long arm0 - start, arm1 - start, ... + + The four instructions after the compare are 7, 5, 3 and 2 bytes, so + the table is 17 bytes on, which JumpTable checks. It returns start; + the caller then makes the n entries with TableEntry. } +function JumpTable(slot, lo: int64; n, elseAt: longint; var endL: longint): longint; +const TableAt = 17; +var start: longint; +begin + Load(RAX, Mem(RBP, slot), 8, false); + if lo <> 0 then AluI(aluSub, RAX, lo); + AluI(aluCmp, RAX, n - 1); + if elseAt <> NoLabel then JccBack(ccA, elseAt) else Jcc(ccA, endL); + start := pc; + Lea(RCX, Here); + Load(RAX, MemIdx(RCX, RAX, 4, TableAt), 4, true); + Alu(aluAdd, RAX, RCX); + JmpR(RAX); + if pc <> start + TableAt then Fatal('internal error: the jump table is not where it was said'); + JumpTable := start; +end; + +{ The next entry of the table that JumpTable started at table: the + code at target } +procedure TableEntry(table, target: longint); +begin + Put4(target - table); end; procedure AlignLoop; diff --git a/src/item.pas b/src/item.pas index 0cafaee..e2afc4f 100644 --- a/src/item.pas +++ b/src/item.pas @@ -100,7 +100,7 @@ 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 MatchTag(p: int64; tag: int64; var L: longint); procedure MatchRange(p, lo, hi: int64; var body: longint); procedure CondJump(var x: TItem; var L: longint); procedure CondJumpTrue(var x: TItem; var L: longint); @@ -1316,16 +1316,13 @@ 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); +{ To L unless the tag of the variant whose address is in slot p is tag } +procedure MatchTag(p: int64; tag: int64; var L: longint); 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; + a.base := bStack; a.chunk := -1; a.off := 0; + PushVar(a, 8, false, kWord); PushConst(kWord, tag); JumpCmp(sNeq, false, L); end; diff --git a/src/parse.pas b/src/parse.pas index 349ce1a..0c00972 100644 --- a/src/parse.pas +++ b/src/parse.pas @@ -1506,7 +1506,8 @@ type TLabels = record - lo, hi: array[0..1023] of int64; { the ranges of the arms so far } + lo, hi: array[0..1023] of int64; { the ranges of the labels so far } + at: array[0..1023] of longint; { where the arm of each starts } n: longint; end; @@ -1516,14 +1517,15 @@ if unsign then Below := qword(a) < qword(b) else Below := a < b; end; -{ An arm of a match on an integer of type t, held in slot p: its labels, - each a constant or a range, none overlapping another (report section - 7.4), then its statements. } -procedure IntArm(t: PType; p: int64; var ls: TLabels; var endL: longint); -var lo, hi: TItem; L, body, i: longint; u: boolean; start: TPos; +{ An arm of a match on an integer of type t: its labels, each a + constant or a range, none overlapping another (report section 7.4), + then its statements. No code tests the labels here; Dispatch does, + after the last arm, for which each label notes where its arm starts. } +procedure IntArm(t: PType; var ls: TLabels; var endL: longint); +var lo, hi: TItem; first, i: longint; u: boolean; start: TPos; begin u := not t^.signed; - body := NoLabel; + first := ls.n; repeat start := TokPos; Expression(lo, t); @@ -1544,23 +1546,62 @@ if ls.n > High(ls.lo) then MarkAt(SpanFrom(start), 'more than ' + IntStr(High(ls.lo) + 1) + ' labels in one match'); ls.lo[ls.n] := lo.val; ls.hi[ls.n] := hi.val; inc(ls.n); - MatchRange(p, lo.val, hi.val, body); if tok <> sComma then break; Next; until false; - L := NoLabel; - Jump(L); - Fix(body); Expect(sColon); + for i := first to ls.n - 1 do ls.at[i] := pc; Statements; Jump(endL); - Fix(L); +end; + +const + MinTable = 4; { fewer labels are tested one by one } + TableDensity = 8; { a table has at most this many entries to a label } + +{ The code that picks the arm, after the last one, which the match's + start jumped to: label by label, as a chain of compares each to its + arm; or, for four or more labels not far apart, a jump table (JumpTable), + which takes the same few instructions for any of them. It is here and + not before the arms, since a table can only be made once every arm's + place is known; an arm is entered by a jump back to it. elseAt is where + the else arm starts, or NoLabel. } +procedure Dispatch(t: PType; p: int64; const ls: TLabels; elseAt: longint; var endL: longint); +var + lo, hi: int64; i, start: longint; v: int64; u: boolean; body: longint; + entry: array[0..1023] of longint; +begin + u := (t^.form = fInt) and not t^.signed; + lo := 0; hi := 0; + if ls.n > 0 then begin + lo := ls.lo[0]; hi := ls.hi[0]; + for i := 1 to ls.n - 1 do begin + if Below(ls.lo[i], lo, u) then lo := ls.lo[i]; + if Below(hi, ls.hi[i], u) then hi := ls.hi[i]; + end; + end; + if (ls.n >= MinTable) and (lo >= low(longint)) and (lo <= high(longint)) + and (qword(hi - lo) < qword(TableDensity) * ls.n) and (hi - lo <= High(entry)) then begin + start := JumpTable(p, lo, hi - lo + 1, elseAt, endL); + for v := 0 to hi - lo do + if elseAt <> NoLabel then entry[v] := elseAt else entry[v] := start; + for i := 0 to ls.n - 1 do + for v := ls.lo[i] - lo to ls.hi[i] - lo do entry[v] := ls.at[i]; + for v := 0 to hi - lo do TableEntry(start, entry[v]); + exit; + end; + for i := 0 to ls.n - 1 do begin + body := NoLabel; + MatchRange(p, ls.lo[i], ls.hi[i], body); + FixTo(body, ls.at[i]); + end; + if elseAt <> NoLabel then JumpBack(elseAt); end; procedure MatchStatement(const start: TPos; ind: longint); var - x: TItem; t: PType; c, f, o: PObj; p: int64; L, endL, n: longint; - seen: array[0..255] of boolean; hasElse, all: boolean; endAt: TPos; ls: TLabels; + x: TItem; t: PType; c, f, o: PObj; p: int64; L, endL, n, disp, elseAt: longint; + seen: array[0..255] of boolean; hasElse, all, byValue: boolean; endAt: TPos; ls: TLabels; begin Next; Expression(x, nil); @@ -1573,16 +1614,24 @@ all := true; endL := NoLabel; ls.n := 0; + { an integer or an enumeration is matched by its value, and the arms + are picked by Dispatch, after them; a variant by its tag, arm by arm } + byValue := t^.form in [fInt, fEnum]; + disp := NoLabel; + elseAt := NoLabel; + if byValue then Jump(disp); while tok = sBar do begin Next; if hasElse then Mark('else must be the last arm'); if tok = sElse then begin Next; Expect(sColon); + elseAt := pc; Statements; + if byValue then Jump(endL); hasElse := true; end else if t^.form = fInt then - IntArm(t, p, ls, endL) + IntArm(t, ls, endL) else begin if tok <> sIdent then Expected('a case'); c := t^.fields; @@ -1592,7 +1641,10 @@ if c^.val <= High(seen) then seen[c^.val] := true; Next; L := NoLabel; - MatchTag(p, c^.val, L, t^.form = fEnum); + if t^.form = fEnum then begin + ls.lo[ls.n] := c^.val; ls.hi[ls.n] := c^.val; + inc(ls.n); + end else MatchTag(p, c^.val, L); OpenScope(NewScope); if tok = sLparen then begin Next; @@ -1615,10 +1667,11 @@ Expect(sRparen); end; Expect(sColon); + if t^.form = fEnum then ls.at[ls.n - 1] := pc; Statements; CloseScope; Jump(endL); - Fix(L); + if t^.form <> fEnum then Fix(L); end; all := all and ends; end; @@ -1633,6 +1686,10 @@ if (c^.val > High(seen)) or not seen[c^.val] then MarkAt(endAt, 'no arm for ' + NameOf(c^.name)); c := c^.next; end; + end; + if byValue then begin + Fix(disp); + Dispatch(t, p, ls, elseAt, endL); end; Fix(endL); end; diff --git a/src/x64.pas b/src/x64.pas index 25e4bfe..e7efa73 100644 --- a/src/x64.pas +++ b/src/x64.pas @@ -75,6 +75,7 @@ procedure CallChunk(c: longint); procedure CallBack(target: longint); procedure CallR(r: longint); +procedure JmpR(r: longint); procedure CallM(const m: TMem); procedure Ret; procedure Leave; @@ -554,6 +555,12 @@ begin if listing then Say('call ' + RN(r)); OpR(0, false, $FF, 2, r); +end; + +procedure JmpR(r: longint); +begin + if listing then Say('jmp ' + RN(r)); + OpR(0, false, $FF, 4, r); end; procedure CallM(const m: TMem); diff --git a/test/run/MatchTable.expect b/test/run/MatchTable.expect new file mode 100644 index 0000000..8988b66 --- /dev/null +++ b/test/run/MatchTable.expect @@ -0,0 +1,4 @@ +-1 -1 -1 -1 10 20 20 -1 30 30 30 -1 40 -1 -1 +0 1 2 3 4 0 +0140 +1234567 diff --git a/test/run/MatchTable.raz b/test/run/MatchTable.raz new file mode 100644 index 0000000..a88d9e0 --- /dev/null +++ b/test/run/MatchTable.raz @@ -0,0 +1,75 @@ +module MatchTable; +import Out; + +type + Day = (mon, tue, wed, thu, fri, sat, sun); + +(* dense, with a hole and a range: a jump table *) +proc dense(n: I64): I64; +begin + match n of + | 1: return 10; + | 2, 3: return 20; + | 5..7: return 30; + | 9: return 40; + | else: return -1; + end; +end; + +(* negative labels *) +proc signed(n: I64): I64; +begin + match n of + | -2: return 1; + | -1: return 2; + | 0: return 3; + | 1: return 4; + | else: return 0; + end; +end; + +(* unsigned, at the top of the range *) +proc top(n: U64): I64; +begin + match n of + | 0FFFFFFFFFFFFFFFCH: return 1; + | 0FFFFFFFFFFFFFFFDH: return 2; + | 0FFFFFFFFFFFFFFFEH: return 3; + | 0FFFFFFFFFFFFFFFFH: return 4; + | else: return 0; + end; +end; + +proc kind(d: Day): I64; +var r: I64; +begin + r := 0; + match d of + | mon: r := 1; + | tue: r := 2; + | wed: r := 3; + | thu: r := 4; + | fri: r := 5; + | sat: r := 6; + | sun: r := 7; + end; + return r; +end; + +proc main*; +var i: I64; d: Day; +begin + for i := -3 to 11 do + Out.int(dense(i)); Out.str(" "); + end; + Out.ln; + for i := -3 to 2 do + Out.int(signed(i)); Out.str(" "); + end; + Out.ln; + Out.int(top(0FFFFFFFFFFFFFFFBH)); Out.int(top(0FFFFFFFFFFFFFFFCH)); + Out.int(top(0FFFFFFFFFFFFFFFFH)); Out.int(top(0)); Out.ln; + for d := mon to sun do Out.int(kind(d)); end; + Out.ln; +end; +end MatchTable.