# The SH-4 for the 2D core: what the ten games use beyond an SH-3 Written 2026-11-23, for the next step of the 2D core: a CPU. The one open SH core, HS3 (`architecture.md`), is an SH-3 (SH7709S) without FPU or MMU. The profile counts every instruction executed, per mnemonic (`../work/awprof/per-game/*.summary.json`, the interpreter run of 5,400 vblanks per game). Here is what the ten 2D games execute that an SH-3 does not have (`../work/sh4/fpucost.py`): | Game | FPU register moves | Cache and store queues | FPU arithmetic | FTRV, FIPR, FSCA, FSRRA | SH-4-only in all | |---|---|---|---|---|---| | KOF XI | 7.29% | 1.32% | 0.24% | 0.002% | 8.85% | | Victory Furlong | 6.79% | 1.27% | 0.02% | 0 | 8.07% | | Samurai Shodown VI | 6.13% | 1.14% | 0.28% | 0.000% | 7.56% | | KOF NeoWave | 3.63% | 0.64% | 0.07% | 0.000% | 4.34% | | Metal Slug 6 | 1.94% | 0.31% | 0.19% | 0.003% | 2.44% | | Sushi Bar | 0.37% | 0.04% | 0.14% | 0.001% | 0.54% | | Guilty Gear Isuka | 0.26% | 0.07% | 0.10% | 0.000% | 0.43% | | WaiWai Drive | 0.16% | 0.03% | 0.04% | 0.001% | 0.23% | | Animal Basket | 0.10% | 0.01% | 0.04% | 0.001% | 0.15% | | Salaryman Kintaro | 0.07% | 0.02% | 0.03% | 0 | 0.11% | Shares of all instructions executed. The kinds: - **Moves:** FMOV, FMOV.S, FSCHG, FRCHG, FLDI0/1, FLDS/FSTS, FNEG, FABS. These are mostly block copies: FSCHG selects 64-bit moves, and FMOV.S pairs then copy 8 bytes an instruction. - **Cache:** MOVCA.L, OCBI, OCBP, OCBWB, PREF. PREF to the store-queue area is how the games send polygons to the tile accelerator. - **Arithmetic:** FADD, FSUB, FMUL, FMAC, FDIV, FSQRT, FCMP, FLOAT, FTRC. ## What it means for the core - **The FPU's registers and moves must be fast**: one a clock, 64-bit pairs included. They are up to 7% of the instructions. - **The FPU's arithmetic can be slow.** If every arithmetic instruction took 8 clocks instead of 1, the games would need at most 2.0% more CPU time (Samurai Shodown VI; KOF XI 1.7%, Metal Slug 6 1.4%). At 16 clocks, at most 4.2%. An iterative unit that works a few bits a clock (add, multiply, divide and square root sharing one datapath) is enough. That is well under the 3,000 ALMs the budget has for a "slow shared FPU". FTRV and FIPR can be microcoded out of the same unit: a few thousand a second at most. - **The cache instructions must exist and be exact.** The games manage DMA buffers with OCBI and OCBWB and write whole lines with MOVCA.L. The SH-4's caches differ from the SH-3's (separate 8 KB instruction and 16 KB operand caches, copy-back, CCR 0x0105 in every game), so HS3's cache becomes the SH-4's. - **Store queues and PREF**: two 32-byte queues, flushed by PREF to the tile accelerator and to memory. Eleven games turn on the MMU only to map them (`workload.md`); one UTLB lookup on this path is all the MMU they need. - **Double precision**: none of the ten use it. The 3D games are different: FPU arithmetic is 8–21% of their instructions and FTRV runs up to 20,000 times a vblank (`workload.md`). The lean 3D core in `other_games.md` therefore needs a pipelined FPU, and its estimate assumes one. ## The FPU's mode The ten games were run once more with the profiler counting FPSCR at every FPU arithmetic instruction (`../work/awprof/tool`, interpreter, 2,400 vblanks each). Every one of them, at every such instruction: **0x00040000**. That is single precision (PR = 0), round to nearest (RM = 0), denormals as zero (DN = 1), no exceptions enabled. FSCHG switches SZ for the 64-bit moves around the arithmetic, but the arithmetic itself always sees the same mode. ## A first block: `rtl/sh4_fpu.sv` The FPU's arithmetic for exactly that mode, iterative: FADD, FSUB, FMUL, FDIV, FSQRT, FMAC (rounded once), FLOAT, FTRC, FCMP/EQ, FCMP/GT. One normaliser and rounder serves them all; division and square root take a bit a clock. - **Checked** (`sim/sh4/run_fpu.sh`) against the PC's own SSE arithmetic in the same mode: round to nearest, DAZ, FTZ. FMAC is checked against a multiply-add in 128-bit floats, rounded once. Operands are mostly ordinary numbers near each other, with zeros, infinities, NaNs, denormals, the largest and smallest numbers, and values a few ulps apart mixed in. 2.5 million tests per operation over five seeds: 0 differ. - **Clocks per instruction:** compares and FTRC 2, FMUL and FLOAT 5, FADD and FSUB 7, FMAC 8, FDIV 33, FSQRT 32. At these (with FTRV and FIPR as runs of products and sums), the ten games would spend 0.15–1.42% more time than with a one-clock FPU: Samurai Shodown VI 1.42%, KOF XI 1.39%, Metal Slug 6 1.14%, Sushi Bar 1.01%, the others under 0.6%. - **Size and clock**, alone in the device (`sim/sh4/ooc/`): 1,215 ALMs, 2 DSP blocks, Fmax 90.3 MHz at the slower corner. The 2D core's budget had 3,000 ALMs for the FPU. - **Cancel** (added for HS3's long-operation contract, below): drops the operation in progress, or one starting in the same clock; no done follows and the unit takes a start the next clock. The bench throws away one operation in eight at a random clock before the checked one: 3.1 million cancels over the five seeds, none wrong, and every checked result still exact. Refitted with it: 1,214 ALMs, 2 DSP blocks, 95.4 MHz (fits vary by a few MHz). - **Not in it yet:** FIPR, FTRV, FSCA and FSRRA (a few thousand a second in these games: microcode over this unit will do), double precision (none of the ten use it), the register file and the moves (they belong in the CPU's pipeline, since they must take one clock). Open: whether the real SH-4 rounds FMAC once or twice. This block rounds once. The difference shows only in the last bit of rare cases. ## From HS3 to an SH-4: the work list HS3 (ika-musume/HS3, BSD-2-Clause; read at commit d34f725, 2026-10-03, in WSL's `~/hs3ref`) is an SH7709S: the integer pipeline (`src/cpu_core/int_pipe.sv`, 3,842 lines), a 16 KB 4-way unified cache (`cache.sv`), the exception handler, and the SH7709S's peripherals (`src/peri/`: BSC, DMAC, INTC, TMU, RTC, CPG). What the ten games need on top, in the order it can be built and tested: 1. **FPU registers and moves, in the pipeline.** FR0–15 and XF0–15, FPUL, FPSCR (PR, SZ, FR); FMOV between registers and with @Rm, @Rm+, @-Rn and @(R0,Rm), 32-bit and, with SZ = 1, 64-bit pairs; FLDS, FSTS, FLDI0, FLDI1, FNEG, FABS; LDS/STS(.L) to and from FPUL and FPSCR; FSCHG, FRCHG. One clock each, as the integer moves: they are up to 7% of the instructions. 2. **FPU arithmetic: `sh4_fpu.sv`** behind the pipeline's existing long-operation contract: start, done, commit and cancel, as HS3's multiplier unit has them. The pipeline waits on done. FIPR and FTRV as a short microcode loop over the unit. 3. **The cache instructions.** MOVCA.L, OCBI, OCBP and OCBWB on top of HS3's cache. PREF exists already (`MEM_PREF`). The SH-4's split 8 KB / 16 KB caches can come later: what the games need from the caches is these instructions' effects on lines and copy-back, not their geometry. MOVCA.L must allocate its line without reading it from memory: five of the ten games use it for block copies, KOF XI, Samurai Shodown VI and Victory Furlong about 25,000 times a vblank (115–139 million in the 5,400-vblank runs), and each fill would be a wasted 16-byte read. HS3's lines are 16 bytes, the SH-4's 32, and the games step through their buffers 32 bytes at a time: until the lines are 32 bytes, each of these instructions (and PREF) must act on both 16-byte lines of its 32-byte block, or half of every DMA buffer is left stale or unwritten. 4. **Store queues.** Two 32-byte queues at 0xE0000000. PREF to that area writes a queue out as one burst, to the address QACR0/1 give, or through one UTLB entry where the game turns the MMU on. All ten use them: five through QACR, five with the MMU on, which write their entries through the UTLB array at boot and never execute LDTLB (`system.md`). 5. **The SH7091's peripherals in place of the SH7709S's**, at the SH-4's register addresses. Measured in `system.md`: the games use TMU channel 0 as a counter they read (no timer interrupt), DMAC channel 2 for the tile accelerator, and only two interrupts, Holly's IRL levels 6 and 4. BSC, INTC priorities and the serial ports are written at boot and need only to hold what was written. 6. **Exceptions and the rest of the SH-4's programming model**: the P4 area, the exception codes, SR's FD bit. No exception at all was taken in the ten games' runs, so the codes matter for correctness only at the edges. ### Where the steps go in HS3 A read of HS3's sources (commit d34f725; nothing changed or run), file and line references in `../work/sh4/hs3_study.md`: - **Pipeline:** five stages (IF, ID, EX, MA, WB), each boundary a packet register with a valid bit. IF predecodes register routing and hazards; ID decodes in one case statement, and the whole 0xF group (the FPU's opcodes) falls to "illegal". A new instruction class is a field in the package and the three packets, a decode arm and matching predecode rows; simulation assertions compare the two decodes. - **Clock:** HS3's own notes give 78–82 MHz on this FPGA family for the full SoC, with its operand paths duplicated by hand to get there. The 2D core runs at 81 MHz, so every input added to ID's operand multiplexers costs margin. - **Registers:** two reads and two writes (result, address update) from four M10Ks, banks as physical register numbers. The FPU's 32 registers fit the same structure; better as even and odd halves of 16, so a 64-bit pair is one access per port. FSCHG, FRCHG and LDS to FPSCR must hold younger instructions as LDC to SR does, since SZ, PR and FR change how the next ones decode. - **Long operations:** the MAC unit's contract (operands captured in MA, start, wait for done, commit at WB, cancelled with the pipeline's redirect) takes a variable-latency unit, so `sh4_fpu.sv` hangs off it. It blocks the pipeline while it works: FDIV and FSQRT would stop everything for up to 33 clocks (0.15–1.42% of CPU time, above). The cancel input this needs is now in `sh4_fpu.sv`. - **Memory path:** 32 bits wide from pipeline to cache to bus, one access a slot; post-increment and pre-decrement already update the address register in the same slot. **A 64-bit FMOV becomes two 32-bit micro-operations** (2 clocks): a 64-bit path would mean a wider bus, split data RAMs and new miss handling. Interrupts must wait between the halves. - **Cache:** 16 KB, 4-way, 16-byte lines; write-back or write-through per area. PREF exists (fills on a miss, never faults). OCBI, OCBP and OCBWB go beside it, reusing the purge flow of the memory-mapped tag array; MOVCA.L can start as a store that allocates. The bus does one 4-beat burst at a time; the store queues now go out as eight single longword writes (step 4, below), and the system's arbiter can learn an 8-beat burst later. - **SH-3 parts in the way:** the exception and cache registers sit at SH-3 addresses; SR's mask drops bit 15 (FD); 0xF0/0xF1 are a unified cache's arrays where the SH-4 has its instruction cache's (its operand cache is at 0xF4/0xF5, 32-byte lines); no MMU registers; the SH7709S peripheral map. Estimated edits, in order: FPU fields and predecode (~200 lines), FD and the FPU-disabled exception (~30), FPU register file with FPUL, FPSCR and forwarding (~400), decode of the 0xF group (~300), FMOV datapath with the 64-bit split (~250), FPU arithmetic on the MAC contract (~200), the cache instructions (~200), store queues (~250), SH-4 register addresses (~100, plus ~300 for 32-byte lines). About 2,000 lines into a 3,842-line pipeline. How to check each step: the way the AICA's ARM was checked (`aica.md`). The profiler records a stretch of a game's CPU execution under Flycast (a memory snapshot, then each instruction's registers and every load and store), and a bench runs the RTL from the same state, answering loads from the record and comparing everything else, instruction by instruction. For the ARM that took one trace hook and a 210-line bench, and found nothing the core did differently in 14 million instructions; the SH-4 version needs the same hook on Flycast's SH-4 interpreter. ### HS3's own testbench, as the baseline Before any change, HS3's core-only testbench (`sim/cpu_core_tb.sv`, 7,466 lines) should pass here as it does for its author; every step above is then checked against it as well. The bench was read first: no file access, no `$system`, no DPI (`../work/sh4/hs3_audit.sh`). Where it stands (`../work/sh4/hs3_sim.sh`): - **Verilator 5.053** (oss-cad-suite) elaborates HS3 once the two packages come first on the command line, and with a default timescale (`--timescale 1ns/1ps`). HS3's `run_sim.sh` sorts the files by name, and this Verilator then stops on a type used before its package is read (47 errors). - **It builds with g++ 10:** the bench is written with delays and `@(posedge clk)` inside tasks, so it needs Verilator's timing mode, which compiles with C++20 coroutines; WSL's own g++ 9.4 has none. With `g++-10` (installed by the owner, 2026-11-23) and `-MAKEFLAGS "CXX=g++-10 LINK=g++-10" -CFLAGS "-std=gnu++20 -fcoroutines"` it builds. - **It passes, apart from one sim-only check.** As shipped, the run stops at test 104 (a random program against random interrupts and NMIs) on HS3's own check that the timing-optimised GPR read-address selects equal the shared mux they replace (`int_pipe.sv:2623`, inside `translate_off`). With that check printing instead of stopping, on a copy of the sources (`../work/sh4/hs3_sim_nf.sh`), the whole suite passes: "cpu_core_tb: PASS (122 tests)", groups 0 to 13 with test 104's end-state oracle. The check fired twice, and both times printed equal values: Verilator evaluated it between two updates of its inputs, a transient, not a wrong read. This is the baseline for the SH-4 changes. - **Icarus Verilog** (`../work/sh4/hs3_iv.sh`) is no way around it: it reads all of HS3 but stops on 36 uses of a signal before its declaration, which Verilator accepts. ### In the repository HS3's CPU core is now the SH-4 port's base: `rtl/sh4/` holds its `src/cpu_core` (commit d34f725, BSD-2-Clause, `rtl/sh4/LICENSE.HS3`), and `sim/sh4/hs3/` its core testbench and Verilator waivers. Changes so far, each marked "SH-4 port" in the source: - the retire trace reports write lane one (the address update of @Rm+ and @-Rn) on its own port too (`o_RETIRE_GPR1_*`, `dbg_o_RETIRE_GPR1_*`), for the trace bench; - the late-select self-check (`int_pipe.sv`, sim-only) is sampled at the clock edge and reports instead of stopping. Sampled there it still differs once in HS3's bench (group 12b, random interrupts and NMIs: r0=03, ref=04) where the bench's own end-state check passes. Whether that read is ever used is open. `sim/sh4/run_hs3tb.sh` runs HS3's bench on these sources: "cpu_core_tb: PASS (122 tests)", one late-select note. ## The trace bench `sim/sh4/tb_trace.cpp` (`run_trace.sh`) checks the core against the SH-4 as Flycast's interpreter runs a game, the way the AICA's ARM was checked. The profiler's `AWPROF_SH4_TRACE=,` (`../work/awprof/tool`) records, from the n-th instruction on: the RAM and the BIOS, every register, and then for each instruction the registers before it, its loads and stores, the interrupts taken and the DMA blocks written into RAM. The bench: - starts the core on a stub at 0xA0E00000 that loads the trace's first state (SR, the banks, GBR, VBR, SSR, SPC, MACH, MACL, PR, R0-R15; since then the FPU, the UTLB, MMUCR, QACR0/1 and the store queues) and jumps to the trace's first instruction; - runs the game's code from the RAM image; loads outside RAM and the BIOS (registers, sound RAM, the cartridge) are answered from the trace's records in order, stores there are checked against them; - compares every instruction the core retires: its address and opcode, then R0-R15, the other bank, SR, GBR, SSR, SPC, VBR, MACH, MACL and PR after it; - writes the trace's DMA blocks into the RAM image after the instruction they followed. - delivers the trace's interrupts after the same instruction: HS3 accepts one only at a boundary with no data access granted beyond the retiring instruction, and an ungranted request can still be dropped, so from the instruction before until the acknowledge the bench grants only the data accesses the trace has for that instruction, and raises the request (level from the IRL code) when it retires. For now the caches are off (every access reaches the bus). Little endian, as the Atomiswave runs it (HS3 has the parameter). First result, HS3 unchanged, Metal Slug 6 from instruction 10,259,754,160 (just after vblank 3000 starts; 2M instructions recorded, `../work/sh4/sh4_trace.sh`): **582,718 instructions retired and matched**, at 4.7 clocks an instruction with every fetch on the bus. Most of them are the game's idle loop waiting for the vblank interrupt. The core takes that interrupt after the same instruction as the trace, and the handler's register saves match until `STS.L FPUL,@-R15` (0x4F52 at 0x8C035298), the first SH-4-only instruction: illegal on an SH-3, as expected. ## Steps 1 to 3 in the pipeline (2026-11-23) What is in `rtl/sh4/` now, each part marked "SH-4 port" in the source (about 450 lines into `int_pipe.sv` and `int_pipe_pkg.sv`): - **FPU registers:** FR0-15 of both banks, FPUL and FPSCR (reset 0x00040001), flip-flops for now. They are written only at WB, either with the packet's result word (a load's data, LDS Rm, an arithmetic result) or by a register move done there from the opcode: FMOV FRm,FRn and register pairs (SZ = 1, DR and XD), FLDS, FSTS, FNEG, FABS, FLDI0, FLDI1, FSCHG, FRCHG. - **No forwarding: two interlocks in ID**, predecoded with the other hazard classes. An instruction that reads an FPU value in ID (an FPU store, STS FPUL/FPSCR, the arithmetic) waits for every older FPU write; an FMOV memory form waits only for older FPSCR writes, since SZ sets its width. Loads into the FPU, register moves and FSCHG flow back to back. - **Memory moves on the integer path:** FMOV.S with @Rm, @Rm+, @(R0,Rm), @Rn, @-Rn, @(R0,Rn); LDS.L/STS.L and LDS/STS with FPUL and FPSCR. The store data word comes from the FPU registers on its own input of the store-data mux. - **Register-pair moves (SZ = 1)** run as two 32-bit micro-ops from one IF/ID packet: the first issue leaves the instruction in IF/ID, the second consumes it. @Rm is @Rm then @(4,Rm); @Rm+ two post-increments; @-Rn two pre-decrements (FR(2n+1) first); the lower address holds FR(2n), as Flycast moves them. No interrupt is accepted between the halves (the delayed-branch defer). A pair can be a delay slot: its branch clears IF/ID at the very edge the first half issues, so on that edge IF/ID is kept for the second half, an early-fetched branch target waits until the second half has issued, and the second half carries the slot marking. Not yet: the pair forms with @(R0,Rm). - **FSCA (exact):** two longword loads from the SH-4's measured sine table, sin(FPUL) to FR(n) and sin(FPUL + 0x4000) = cos to FR(n+1), as a micro-op pair like the register-pair moves, so it works in a delay slot too (`RTS` with `FSCA` in its slot is how Samurai Shodown VI returns from its sine function). The address rides the immediate as a PC-relative load's does: physical 0x18000000 + 4 x index, area 6, which the Atomiswave does not use; the system will map it to the table in DDR3. The table is Flycast's (`core/hw/sh4/fsca-table.h`, measured on an SH-4; GPL), so it is built from a local Flycast checkout and never committed: `tools/sh4_fsca/mkfsca.py` writes the whole period, 0x10000 little-endian floats (256 KB), the second half negated as Flycast does. - **Arithmetic (step 2):** `sh4_fpu.sv` hangs off MA. An arithmetic packet holds MA while the unit works, reading its operands straight from the FPU registers, which is exact because it left ID only with no older FPU write in flight; the result leaves MA with the packet and commits at WB. A redirect or WB fault cancels the unit. FCMP's T comes out of MA, so FCMP holds younger instructions as an LDC to SR does, and the running T resyncs from the committed SR. Single precision only (PR = 1 is illegal for now). Not yet: FIPR, FTRV, FSCA, FSRRA. - **Cache instructions (step 3), cache-off form:** OCBI, OCBP and OCBWB do nothing and MOVCA.L is a plain store, which is exact while the caches are off. With the caches on they need the real line operations (done in step 5). - **For the bench only:** the retire port marks a pair's first half; the FPU registers come out on debug ports; a sim-only input holds the pipeline's data requests off the cache (tied off in the core). **Checked:** - **The trace bench, Metal Slug 6, all 2,000,000 instructions match** (from instruction 10,259,754,160, vblank 3000), with the FPU registers, FPUL and FPSCR compared after every instruction as well: four interrupts taken after the same instruction as Flycast, 128 register-pair moves, the FPU arithmetic (FLOAT and the rest), cache instructions. 4.7 clocks an instruction with every fetch on the bus (no caches). - **Two orderings Flycast does differently, allowed in the bench:** JSR, BSR and BSRF write PR at the branch in the core and after the delay slot in Flycast; RTE restores SR at the RTE (its slot runs with it) in the core and after the slot in Flycast. They differ only if the slot reads PR or SR. The bench checks PR and SR after the slot instead. - **How interrupts line up:** HS3's cache accepts a data request at once even with the caches off, and from then on the access cannot be dropped. So from two instructions before the trace's interrupt until the core acknowledges, the bench holds the pipeline's data requests off the cache unless the trace has the access for one of those instructions, and raises the request when the instruction before the interrupt retires. - **King of Fighters XI, all 1,999,998 instructions match** (from about vblank 2950; the trace began in a delay slot, so the bench starts one instruction later): 12 interrupts, 424 register-pair moves, 2,496 register reads and 30 register writes answered or checked, 5,195 DMA blocks into RAM applied. - **Samurai Shodown VI, all 1,999,999 instructions match** (from about vblank 2950): 6 interrupts, 248 register-pair moves and 12 FSCAs (some in an RTS's delay slot), 2,423 register reads. - **HS3's own bench: PASS (122 tests)** on these sources. Its illegal-instruction tests used 0xF000, which is FADD on the SH-4; they now use 0xFFFF, undefined on both. **Seen and not done:** - **Why FSCA reads a table in DDR3.** Flycast's table (32,768 sine values over half a period) is within 2^-23 of the true sine but not symmetric about the quarter period (1,457 of 16,383 mirrored pairs differ, `../work/sh4/fsca_sym.py`), so an exact FSCA needs all of it: 1 Mbit, about a fifth of the FPGA's block RAM for an instruction the ten games run a few thousand times a second at most. A computed sine would be off by a bit now and then, and from there the trace bench could not follow the game. The owner chose the exact table (2026-11-23). - **Not yet:** FTRV, FIPR, FSRRA (none met in the three traces), double precision, the pair forms with @(R0,Rm). ## Step 4: the store queues (2026-11-23) First written into HS3's `cache.sv` beside its CCR, since on the SH-4 they belong to the cache; since step 5 they live in `rtl/sh4/sh4_cache.sv`, unchanged: - **SQ0 and SQ1**, 8 longwords each. Stores to 0xE0000000-0xE3FFFFFF write them (address bit 5 picks the queue, bits 4:2 the longword) at the cache's accept edge, as its CCR writes do; loads there read them back. Nothing reaches the bus. - **PREF in that area** is acknowledged at once, as a non-cacheable PREF always was, and the cache then writes the queue out: eight single longword writes on HS3's bus, to {QACRn[4:2], Rn[25:5]}. The cache serialises them like any external run, so a queue cannot change under its transfer and later accesses follow in program order. The cost is that the cache accepts nothing else for those clocks; filling one queue while the other goes out, as the chip allows, would need a copy of the queue. - **QACR0/1, MMUCR and the UTLB arrays** as the cache's own registers. Five games (KOF NeoWave, KOF XI, Metal Slug 6, Samurai Shodown VI, Victory Furlong) set MMUCR.AT only to map the store queues: they write 25 UTLB entries through the arrays at boot, mapping the queue area in 1 MB pages, and make no P0/U0 access with translation on. The core keeps the 64 entries in two small RAMs (they read back as written, V and D shared). On every array write it files the entry in a table by megabyte of the queue area, Flycast's `sq_remap`, by Flycast's rule (`fastmmu.cpp`): any entry whose VPN lies in 0xE0-0xE3, valid or not, its PPN masked to the page size. With AT set, a transfer goes to that page plus Rn[19:5]. An array write costs two clocks, a transfer's lookup one. MMUCR.TI clears every V. Not modelled: associative array writes and data array 2 (the games use neither), user-mode access to the queues (SQMD), and translation of anything else. **The trace format** has two new records (`../work/awprof/tool`): - 'U', after the first state: the UTLB as its arrays read, then Flycast's `sq_remap`; - 'Q', for each transfer: the address Flycast sent it to. The bench now: - has its stub write the UTLB through the arrays, then MMUCR, QACR0/1 and both queues; - replays the trace's stores to the queues into a reference copy; - turns every PREF in the queue area into the 8 longwords the core must write, at the 'Q' address (QACR's in a trace without 'Q'), and checks them as they come; - passes MMUCR and the arrays to the core, which answers their loads. A fix on the way: writes to area-0 registers above the 2 MB BIOS (Holly's, among others) had been dropped as BIOS writes; they are now matched against the trace like the others. The three traces were made again with the new records, from the same instruction counts (`../work/sh4/retrace_q.sh`, tag `q`; `trace_cmp.py` and `trace_hdiff.py` compare two): - KOF XI and Samurai Shodown VI: the same runs except for one RAM word each at the start, clock-derived it seems. - Metal Slug 6: started from its earlier run's save files, it differs in 107 RAM words and starts at 0x8C05B3AA instead of 0x8C05B3D2. **Checked:** - **All three traces still match in full, store-queue transfers included**, every longword at Flycast's address: - Metal Slug 6: 1,999,999 instructions, 2 transfers, both to RAM. - KOF XI: 1,999,998 instructions, 4,872 transfers: 4,871 to RAM, 1 to the tile accelerator. - Samurai Shodown VI: 1,999,999 instructions, 5,249 transfers: 4,833 to RAM, 416 to the tile accelerator. In all three the 25 mapped megabytes give exactly Flycast's `sq_remap`. In these stretches the games use the queues mostly to write blocks into RAM, not to feed the tile accelerator directly. - **HS3's own bench: PASS (122 tests).** - **Not checked here:** the QACR path against a real QACR game. The five games that set QACR have no trace yet, so that path is checked only against the bench's own reading of QACR (KOF XI and Samurai Shodown VI, before the UTLB was in). ## Step 5: the caches (2026-11-23) All ten games set CCR to 0x0105: both caches on, copy-back for P1 and for P0/U0/P3, no OC-RAM, no index-mode change (`workload_tables.md`). In the three traces the games run, every 2M instructions, about 18,500 MOVCA.L, 4,600-5,600 OCBI, up to 92 OCBWB, 180-500 PREFs to RAM and 2 TAS.B; none touches the cache arrays or CCR outside boot (`../work/sh4/trace_p4.py`). HS3's cache is the SH7709S's: unified, 4-way, 16-byte lines, with its CCR and arrays at SH-3 addresses, and its own bench tests exactly that. So the SH-4's is a new module, `rtl/sh4/sh4_cache.sv` (from HS3's, BSD-2-Clause), and `cpu_core` picks one with `SH4` (default 1, which also puts the exception registers at their SH-4 addresses; HS3's bench sets 0 and keeps HS3's `cache.sv`, unchanged): - **Geometry:** an 8 KB instruction cache (256 lines; 32 KB since the speed work below) and a 16 KB operand cache (512 lines), direct-mapped, 32-byte lines, tags of physical bits 28:10, in RAM from `sh4_cache_mem.sv` (one 1R1W module with a new-data bypass for every array). Fills are 8 longwords from the missed one, wrapping, answered at the first. - **HS3's protocol with the pipeline is kept:** one access a cycle, accepted at one edge, resolved against the RAMs the next; a hit answers in that cycle, anything slower goes to the FSM, which owns the bus. - **A dirty line is written back before its replacement is filled** (copied to the write-back buffer, its 8 longwords drained, then the fill), never in the background. So no line can sit in a buffer while a later uncached store, the one that starts a DMA, overtakes it. A dirty miss pays its 8 writes up front. - **Only an accepted store commits.** HS3 commits a resolving store hit whether or not the cache accepted it, which is harmless only if the request comes again; one the trace bench holds back for an interrupt is withdrawn instead. - **The cache instructions:** the pipeline sends OCBI, OCBP and OCBWB as PREF-like requests with a 2-bit sideband, and marks MOVCA.L's store (`int_pipe.sv`, `o_D_CBOP`, `o_D_MOVCA`). OCBI drops a hit, OCBP writes back a dirty hit and drops it, OCBWB writes back a dirty hit and keeps it clean. MOVCA.L on a copy-back miss claims the line without reading it (the line's other words keep whatever the array held, as on the chip). PREF fills on a miss. - **TAS.B** purges a hit (written back if dirty, then dropped), then makes its locked read and write on the bus. - **CCR** at 0xFF00001C: OCI and ICI empty a cache by walking its lines (512 clocks; the games do it at boot), with no write-back, as on the chip. ORA, OIX and IIX read back but do nothing; a simulation note says so if one is set. - **The arrays** at 0xF0/0xF1 (instruction cache) and 0xF4/0xF5 (operand cache): reads, and writes as Flycast's `sh4_cache.h` does them. A non-associative address-array write writes a dirty line back first; an associative one changes V and U on a tag match, writing back a dirty line if the new U or V is set. - **The store queues and UTLB of step 4** moved here unchanged. HS3's transaction-port package (`o_MON_*`) is not carried over: it serves HS3's own chip. **The trace bench** now turns the caches on with the trace's CCR (every line empty at the start: Flycast has no cache model outside its strict build, so its memory is the truth there). Two additions: - **Interrupt alignment.** The bench used to let a data request through near an interrupt if the trace had an access to that word, at any instruction up to the interrupt. With the caches the pipeline runs far enough ahead that, at Samurai Shodown VI's first interrupt, a load two instructions past it read the very word the store before it wrote, was let through and accepted, and the interrupt came one instruction late. Now each trace access admits one request: the core's accepted data requests (a new sim-only port) mark it used. - **Write-backs checked against DMA.** The trace has a new record, 'E': what a channel-2 DMA (display lists to the tile accelerator) read out of RAM, written after the instruction that started it. The bench's RAM image holds only what the core put on the bus, so at that point it must already hold those bytes: every dirty line the game meant the DMA to see must have been written back. `../work/awprof/tool/apply_patches.py` gains an optional kind of edit to update an older hook in a patched checkout. The traces were made again with it, tag `e` (`../work/sh4/retrace_q.sh e`): the same runs as the `q` ones plus the reads. `sim/sh4/tb_cache.cpp` (`run_cachetb.sh`) checks the paths the traces do not reach: a hand-assembled program on the same top, every RAM transaction logged and checked step by step. It covers OCBWB after a copy-back store miss, OCBI over a dirty line, OCBP, MOVCA.L without a fill, the operand cache's address array (clean, dirty, a write of 0 writing back first), CCR.OCI dropping a dirty line, TAS.B on a dirty line, write-through hits and misses, and the instruction cache staying stale after its code is rewritten until CCR.ICI. **Checked:** - **All three traces match in full with the caches on**, at 1.74 (Metal Slug 6), 1.83 (KOF XI) and 2.29 (Samurai Shodown VI) clocks an instruction, against 4.7-4.9 with every access on the bus. Interrupts (4, 12, 6), register pairs, FSCA and the store-queue transfers are all as before. - **Every DMA read matches:** KOF XI 5 channel-2 reads (7,808 bytes), Samurai Shodown VI 2 (6,976 bytes); Metal Slug 6 starts none in its stretch. - **`tb_cache`: PASS, 21 of 21 checks.** - **HS3's own bench: PASS (122 tests)**, with its own cache. - **Not checked:** the clock rate (nothing of the SH-4 core has been through Quartus yet; the operand cache's index takes address bits 13:12 from the full adder rather than HS3's 12-bit index twin), associative array writes against real code, and the arrays' behaviour against the chip rather than Flycast's model. ## Step 6: the SH7091's peripherals (2026-11-23) What the games use of them was measured before (`system.md`); this is that, and no more. **In the core.** The exception registers move to the SH-4's addresses: TEA 0xFF00000C, TRA 0xFF000020, EXPEVT 0xFF000024, INTEVT 0xFF000028 (`exc_handler.sv`, parameter `SH4`, which `cpu_core` passes on with its own). INTEVT is read in every interrupt handler of the games; the trace bench now leaves it to the core, so each handler's read checks the code the core latched when it took the interrupt. It also matters that HS3's addresses are gone: one game writes 0xFFFFFFC4-0xFFFFFFE0 at boot, where the SH7709S kept them. **Beside it, `rtl/sh4/sh4_periph.sv`**, on the cache's bus behind a router (`sh4_cpu.sv`: `cpu_core` plus the peripherals; P4 addresses go to them, everything else out on the bus): - **BSC:** storage with Flycast's masks and the chip's reset values. RFCR reads 17, as Flycast holds it to help the boards boot. PDTRA reads the board's serial ID chip from outside (Flycast's board ID read), and what is written goes out. - **DMAC:** the four channels' registers and DMAOR. Channel 2's go out to the system's DMA engine, which reports a finished transfer: SAR2 advances by its length, as on the chip (Flycast leaves it, and the games rewrite it before every transfer and never read it), DMATCR2 = 0, CHCR2.TE = 1. - **INTC:** ICR and IPRA-C stored. The interrupt to the core is the highest of Holly's IRL (level 15 - IRL, INTEVT 0x200 + 0x20 x IRL) and the timer underflows (TUNI0-2, levels from IPRA), IRL first on a tie. - **TMU:** all three channels count down at Pphi/4 to /1024 by TCR.TPSC while TSTR runs them, reload TCOR below zero and set UNF, which software clears by writing 0. Pphi is a tick from the system (50 MHz on the board), so the games' busy-wait loops on TCNT0 take their real time whatever the CPU's clock. - **SCI and SCIF:** the status always says "transmit empty", and every SCFTDR2 write comes out as a character (the four games that print debug text poll for it). - **Anything else** in P4 reads 0 and ignores writes. The trace bench keeps answering the peripherals from the trace (`trace_top.sv` is still `cpu_core` alone): the games branch on TCNT0 in their busy-wait loops, so a timer of the core's own would make them run differently from the trace. The peripherals are checked by `tb_cache.cpp` instead, now on the whole CPU (`cpu_top.sv`, `run_cachetb.sh`): an IRL interrupt through the INTC into a handler that reads INTEVT, the timer counting, the BSC's reset values, SCIF's status and characters, and channel 2 before and after a finished transfer. **Checked:** - **`tb_cache`: PASS, 26 of 26:** the 21 cache checks, and: IRL 9 taken once with INTEVT 0x320; TCNT0 counting at Pphi/4; WCR1 at 0x77777777 after reset; SCIF printing "OK" with SCFSR2 0x0060; after a finished 0x200-byte transfer SAR2 0x0C123600, DMATCR2 0, CHCR2 with TE. - **The three traces still match in full**, the 22 handlers' INTEVT reads now answered by the core. - **HS3's own bench: PASS (122 tests)**, at the SH7709S's addresses. - **Not done:** the system's channel-2 engine (RAM to the tile accelerator, with Holly's CH2 registers), Holly's interrupt controller that makes IRL, and the serial ID chip on PDTRA: they belong to the system around the CPU. ## Step 7: FIPR, FTRV and FSRRA (2026-11-23) Four of the ten games use them in their 5,400-vblank profile runs: Metal Slug 6 (FIPR 425K, FTRV 142K, FSRRA 4), KOF XI (FIPR 173K, FTRV 97), Guilty Gear Isuka (FTRV 22K) and Sushi Bar (FTRV 3K, FSRRA 2); none in the three trace stretches. The chip computes FIPR and FTRV with its own reduced internal precision, so the reference is what Flycast computes (`sh4_fpu.cpp`), and that is what `sh4_fpu.sv` now does: - **FIPR FVm,FVn:** the four products exact in double precision (a 24 x 24-bit product fits a double's 53 bits), each of the three additions rounded to double (nearest even), the sum rounded to single at the end through the unit's normaliser and rounder (denormals as zero, as the games' FPSCR 0x00040000 has it). The result goes to FR(n+3). - **FTRV XMTRX,FVn:** four such sums, row r = XF[r] FR(n) + XF[r+4] FR(n+1) + XF[r+8] FR(n+2) + XF[r+12] FR(n+3), out on a 128-bit port; the pipeline writes FR(n)..FR(n+3) at WB from it (`fpu_dst` 11_00nn). Every FPU reader waits in ID for it, so nothing restarts the unit before that commit. - **FSRRA FRn:** the square root rounded, then 1.0 divided by it, rounded: Flycast's `1.f / sqrtf(x)`, the unit's own two operations in a row. - The double-precision step is iterative (a term every few clocks): at most 23 clocks for FIPR, 89 for FTRV, 64 for FSRRA (34, 133 and 65 since the clock-rate work below). **That is slow for Metal Slug 6's busiest frames:** vblank 2161 runs 4,359 FIPR and 1,452 FTRV, about 340,000 clocks now, 28% of a 60 Hz frame at 73 MHz, where the profile's estimate (one clock each) has 5,800. The game needs 65 MHz of that estimate at p99 (`workload.md`), so frames like this one may not fit. A pipelined multiply-add (a term a clock) would bring them to about 25,000 clocks; it is the first speed item for the CPU, once the core's clock and its clocks per instruction on busy code are measured. **Checked:** - **`tb_fpu`: all 13 operations against the PC's arithmetic, 200,000 random cases each, 0 differ**, FSRRA, FIPR and FTRV against Flycast's own code run in the games' mode; 324,045 operations cancelled midway, none wrong. Writing this found a bench bug: its result check treated every operation numbered 8 or above as a compare (T only), which would have passed the new three unchecked. - **`tb_cache` step 12, through the whole pipeline:** both banks loaded, then FIPR, FTRV and FSRRA, each result stored the very next instruction: all six values equal to Flycast's. PASS, 27 of 27. - **A fourth trace, Metal Slug 6 from vblank 2161** (instruction 8,076,282,113, where its run has the most FTRV and FIPR; `../work/sh4/trace_ms6_fpu.sh`): **all 1,999,999 instructions match, 2,112 FIPR and 702 FTRV among them** (`trace_fpuops.py`), with every FPU register compared after each; also 5,007 register-pair moves and 177 store-queue transfers, at 1.99 clocks an instruction with the caches on. It joins the regression set (`bench_sq.sh`). - **The three traces still match in full; HS3's own bench: PASS (122 tests).** HS3's bench builds with width warnings as errors, which caught two index expressions in the new code. ## Speed, measured (2026-11-23) The bench now counts clocks per instruction address (`tb_trace -pcstat`): an instruction is charged the clocks since the one before it retired. With the caches on and memory answering the clock after a request (faster than any real memory), over the four traces: - **The idle loops** (the game waiting for its vblank; Metal Slug 6's is 13 instructions, retired 110,000-148,000 times a trace): 1.67-1.74 clocks an instruction. In Metal Slug 6's: a load costs 2 clocks (3 when the next instruction uses it), a taken branch 2, the rest 1. - **Busy code**, everything the hot loop is not (in KOF XI and Samurai Shodown VI it still holds some idle code: the profile counts 87% and 86% of their stretches idle, the rule 45%): | Clocks an instruction | Metal Slug 6, vblank 2161 | KOF XI | Samurai Shodown VI | |---|---|---|---| | all busy code | 2.73 | 1.95 | 2.74 | | loads | 2.39 | 2.47 | 3.92 | | stores | 2.65 | 1.74 | 3.08 | | branches | 2.26 | 1.88 | 2.03 | | FPU loads and stores | 2.78 | 1.92 | 2.30 | | FPU arithmetic | 9.50 | 4.81 | 4.54 | | the rest (ALU, moves) | 1.87 | 1.54 | 1.98 | **What it means.** The profile sized the games for a single-issue SH-4 at one instruction a clock plus 20 clocks a cache miss (`workload.md`: Metal Slug 6 65 MHz at p99, Samurai Shodown VI 91). This core takes 2-3 clocks for an instruction of busy code even before real memory latency. Metal Slug 6's vblank 2161 has 848,418 busy instructions: at 2.73 that is 2.3 million clocks, 23 ms at 100 MHz, more than a 60 Hz frame. So the CPU as it stands is about two to three times too slow for the heavier frames. Where the clocks go, in order: 1. **Loads and stores:** HS3 shares one bus between instruction fetch and data, so every access takes a fetch slot, and a load used by the next instruction stalls it. The SH-4's caches are split now; the pipeline still is not. 2. **Cache misses** stop the cache until the whole 8-longword line is in (and a dirty line written back first), even though the missed word goes to the pipeline at the first beat. 3. **FPU arithmetic:** iterative, with no forwarding; FIPR and FTRV take 23 and 89 clocks. 4. **Taken branches:** 2 clocks. These are the next work on the CPU, in that order, each measured with the same counts. (Done for the first three below, under "Speed work", whose measurements separate the causes more finely.) ## Size and clock, measured (2026-11-23) The whole CPU (`sh4_cpu.sv`: HS3's pipeline, the SH-4 caches, the FPU, the peripherals) compiled out of context in Quartus 17.0.2 Lite on the DE10-Nano's 5CSEBA6U23I7 (`sim/sh4/ooc/sh4_cpu_ooc.*`, `../work/sh4/cpufit.sh`; every input from a shift register and every output into one; `cpucheck.sh` runs Quartus's analysis alone in a minute): | | | |---|---| | Logic | 11,689 ALMs (28% of the device) | | Registers | about 8,900 | | Block RAM | 34 M10K (221,632 bits) | | DSP blocks | 8 | | Clock (static timing) | 73.0 MHz at the slow 100 C corner, 74.8 MHz at -40 C | For comparison, HS3 alone: 5,319 ALMs for its CPU core, 74-82 MHz in static timing, about 103 MHz on its boards. Getting there, each step checked with the traces, `tb_cache` and `tb_fpu` before compiling: 1. **The first fit did not fit** (107,946 combinational nodes): `sh4_ram_wt` was not inferred as block RAM, so the caches' 24 KB were flip-flops. It now uses HS3's forms (`cache_mem.sv`): inferred M10K with `no_rw_check` for whole-entry arrays, `altsyncram` with byte enables and mixed-port OLD_DATA for the operand cache's words. Two constructs Verilator takes and Quartus 17 does not had to go first (`for (genvar ...)` and uses before declarations). 2. **67.8 MHz**, limited by the new double-precision FIPR/FTRV steps: the operand choice now has its own clock, and the alignment its compare and its shift on two (FIPR 23 -> 34 clocks, FTRV 89 -> 133). 3. **66.8 MHz**, the cache's dispatch off the live address: P4 accesses (the arrays, the local registers, the SQ PREF's transfer, the peripherals) are now handled in the resolve cycle from the latched address; CCR, MMUCR and UTLB writes hold the next access a clock, so no access can see their effect late. 4. **69.6 MHz**, the resolve cycle's dispatch registered: the hit compare feeds a few flops, and the state changes a clock later (that clock accepts nothing). 5. **About 70 MHz**, the FPU's operands latched at the start: its first step had followed the 32-to-1 choice of register (every FPU operation one clock longer). 6. **74.7 MHz**, uncached fetches served in the resolve cycle: the fetch buffer's compare against the live address had decided the response register in the accept cycle. Only boot code runs uncached. 7. **73.0 / 74.8 MHz**, the load data without the hit: the operand cache is direct-mapped, so its word is the answer whatever the compare says, and the hit reaches the pipeline's aligner separately (HS3's rsp_hit_d). The slowest paths are now HS3's own: from the tag RAMs through the hit into the pipeline's stall logic and its register file's read select, and its operand forwarding. The cost of the steps above in clocks: Samurai Shodown VI's trace 2.29 -> 2.33 clocks an instruction, KOF XI's 1.83 -> 1.84, Metal Slug 6's 1.74 unchanged. ## Speed work: the fetch port, line bursts, the instruction cache, the FPU (2026-11-23) **Measuring first.** The trace bench gained three views (`sim/sh4/tb_trace.cpp`): - `-stall`: every clock charged to the instruction in IF/ID, or with IF/ID empty to the last one retired: it issues, or why not (IF/ID empty, with or without the cache busy; a hazard, by kind; EX or MA unable to move, by cause), split between the idle loop and busy code. With it, the FPU instructions in busy code by class, the busy addresses with the most clocks of two of the classes, and how often the cache's FSM left S_IDLE for each state. - `-cyc K N`: N clocks from instruction K, one line each: both buses, the responses, IF/ID, the stage valids, issue, hazard, completion, the cache's state, the retirement. - `-memlat L -memgap G`: the memory model (`sim/sh4/busmodel.h`, shared with `tb_cache`): a single access answers L clocks after it is accepted; a line's beats come every G clocks. L = G = 1 is HS3's bench, the default. - `-dacc FILE`: every data access the cache accepts, for cache-geometry studies offline. The scripts are in `../work/sh4/`: `stall_all.sh` runs the four traces, `stall_show.sh`, `fsm_all.sh`, `fpu_show.sh` and `other_show.sh` print the parts, `lat_all.sh L G` runs them at a memory latency, `cyc.sh` dumps clocks, `icache_sim.py`, `ocache_sim.py` and `fpu_overlap.py` model alternatives from a trace. **Where the busy code's clocks went, before** (percent of busy clocks; memory answering the clock after; this first count put hazards ahead of EX and MA stalls, the later one the other way round): | | Metal Slug 6, vblank 2161 | KOF XI | Samurai Shodown VI | |---|---|---|---| | an instruction issues | 33.0 | 48.6 | 34.8 | | IF/ID empty: the cache busy (misses) | 7.2 | 9.0 | 21.2 | | IF/ID empty: the fetch (data accesses take its slots, a held response stops the next) | 10.0 | 20.4 | 17.3 | | a load used by the next instruction | 8.9 | 6.0 | 10.8 | | the FPU (a value not yet written, MA held by an operation) | 22.5 | 4.1 | 1.2 | | EX waits for the bus | 6.1 | 1.8 | 7.8 | Four changes, each checked with the four traces, `tb_cache`, `tb_fpu` and HS3's bench before the next: 1. **Fetches get their own port.** HS3 sends fetches and data accesses down one L bus, a request a clock, data first, and its AGU makes both addresses. Now the pipe has two (`int_pipe.sv`, `L_BUS` for data, `L_IBUS` for fetches) and the cache two ports, both accepted in the same clock (`sh4_cache.sv`): the operand cache's RAMs read with the data port's address, the instruction cache's with the fetch port's. A fetch goes out at `fetch_pc` (plus the half-word lag after an early branch target) whatever the data side does; only an early branch target, which comes off the AGU, waits while a data access has it. When both resolve into the FSM in the same clock, the data access goes first and the fetch waits in `i_pend`; while anything dispatches, neither port accepts. An uncached data access now dispatches in its resolve cycle, not at its accept, so that a fetch accepted beside it is not lost (two clocks more for such an access). HS3's own cache keeps one bus: `lbus_merge.sv` rebuilds it from the two exactly (data first, the AGU's address), and HS3's bench, its probes moved to the merged bus, passes. 2. **A line moves as a burst.** A fill is one read request at the missed longword, answered by 8 beats in wrapping order (the first answers the pipe); a write-back or a store-queue transfer is 8 write beats, each with its own address, answered once after the eighth (`I_BUS.req_burst`). HS3 sent each longword as a request and waited for its answer, 3 clocks a longword on the bench's memory. A fault on a beat leaves the line invalid and the burst runs out. `tb_cache` logs RAM traffic per beat, so its counts (8 reads a fill) still hold. 3. **The instruction cache is 32 KB, and follows the CPU's stores.** The chip's is 8 KB direct-mapped. Run through the traces' fetch streams (`icache_sim.py`), its misses are mostly conflicts: | Instruction-cache misses, 2M instructions | 8 KB, 1 way (the chip) | 8 KB, 2 ways | 16 KB, 2 ways | 32 KB, 1 way | |---|---|---|---|---| | Samurai Shodown VI | 36,217 | 8,970 | 1,842 | 1,808 | | Metal Slug 6, vblank 2161 | 9,320 | 1,227 | 1,179 | 1,158 | | KOF XI | 2,314 | 1,947 | 1,693 | 1,644 | | Metal Slug 6 | 1,351 | 1,232 | 1,148 | 1,119 | 32 KB direct-mapped does as well as two ways and keeps the fetch path without a way select, which HS3's timing cannot spare. A bigger cache could hold stale code longer than the chip's, so it now drops a line when the CPU stores into it (a copy of the tag and V arrays, read with the data port's address); Flycast, which every game runs on, has no instruction cache at all, so no game can depend on stale code. DMA writes are not followed. The arrays at 0xF0/0xF1 keep the chip's 256 entries: entry e is the four lines {0..3, e}, an address-array write goes to all four (only the one the tag's own index bits name can ever hit), an associative one to that one, reads and the data array to {0, e}; the games never touch them at run time (`system.md`). ICI walks 1024 lines. `tb_cache` step 9 now expects the rewritten routine to return its new value at once (5, 7, 7, three fills). The operand cache stays the chip's: the same study of its accesses (`ocache_sim.py`) finds 10-40% fewer misses at 32 KB or two ways, mostly data read once. 4. **The FPU, faster where Metal Slug 6 spends.** Letting the pipeline run past an FPU operation would win little: in the traces most arithmetic instructions have 0-2 instructions after them before one needs the result or the unit, 78% of them in KOF XI and 90% in Metal Slug 6's vblank 2161 (`fpu_overlap.py`). So the operations themselves (`sh4_fpu.sv`): FIPR's and FTRV's products come from a pipeline of their own that runs ahead of the additions and holds up to four terms, so no addition waits for its product; division takes two quotient bits a clock. And arithmetic, which reads its operands in MA, no longer waits in ID for an older FPU write already in WB (it has committed by the time the reader gets to MA); FPU stores and STS, which read in ID, still do (`pd_route.fpu_rd_ma`). Clocks from start to done: FIPR 35 -> 26, FTRV 134 -> 89, FDIV 34 -> 20, FSRRA 65 -> 51 (`tb_fpu`: 200,000 cases each, 0 differ). **Clocks an instruction**, the whole trace (busy code in brackets): | | Metal Slug 6 | KOF XI | Samurai Shodown VI | Metal Slug 6, vblank 2161 | |---|---|---|---|---| | before | 1.74 (2.95) | 1.84 (1.98) | 2.33 (2.80) | 2.03 (2.86) | | 1. fetch port | 1.59 (2.82) | 1.64 (1.69) | 2.11 (2.49) | 1.87 (2.70) | | 2. bursts | 1.57 | 1.54 | 1.73 | 1.78 | | 3. 32 KB instruction cache | 1.56 (2.21) | 1.53 (1.55) | 1.51 (1.51) | 1.74 (2.23) | | 4. FPU | 1.56 (2.17) | 1.53 (1.54) | 1.51 (1.51) | 1.69 (2.05) | | 4, memory latency 6, a beat a clock | 1.57 (2.38) | 1.57 (1.60) | 1.56 (1.58) | 1.70 (2.09) | | 4, latency 8, a beat every 2 clocks | 1.58 (2.73) | 1.64 (1.69) | 1.64 (1.69) | 1.72 (2.17) | Metal Slug 6's busy code in its first trace is only 70,515 instructions at the idle loop's edge, so its figure moves with little. The latency rows matter more now: before step 3, Samurai Shodown VI's busy code went from 1.73 (latency 1) to 2.12 (6) and 2.52 (8, every 2); its instruction misses had made it sensitive to memory. **Where the busy code's clocks go now** (percent; memory answering the clock after): | | Metal Slug 6, vblank 2161 | KOF XI | Samurai Shodown VI | |---|---|---|---| | an instruction issues | 45.0 | 62.3 | 63.5 | | the FPU (a value not yet written, MA held by an operation) | 24.4 | 4.9 | 2.2 | | a load used by the next instruction | 7.6 | 8.0 | 8.0 | | IF/ID empty, the fetch side (mostly after taken branches) | 4.3 | 6.1 | 6.4 | | a taken BT/BF dropping the next instruction | 9.7 | 5.2 | 5.6 | | the cache busy (misses, write-backs, store-queue transfers) | 4.3 | 6.8 | 8.2 | | SR, RTE and control-register serialisation (an RTS after LDS.L @R15+,PR, mostly) | 1.1 | 4.5 | 3.7 | **Size and clock** (Quartus, as in "Size and clock, measured"): | | ALMs | M10K | Clock, 100 C / -40 C | |---|---|---|---| | before | 11,689 | 34 | 73.0 / 74.8 MHz | | 1. fetch port | 11,662 | 34 | 73.3 / 73.1 MHz | | 3. 32 KB instruction cache (with 2) | 11,702 | 63 | 71.4 / 72.1 MHz | | 4. FPU | 11,748 | 63 | 68.9 / 70.2 MHz | | 4. FPU, fitter seed 2 | 11,800 | 63 | 76.4 / 76.0 MHz | | 4. FPU, fitter seed 3 | 11,867 | 63 | 73.8 / 74.1 MHz | The slowest path is HS3's still, and the same chain in every fit: from the forwarding select through the address adder, the alignment check, the data request's valid and the issue decision into the register file's read select; the FPU's own slowest (rounding into FSRRA's second step) is at 74 MHz. The fitter's seed alone moves the result from 69 to 76 MHz (`../work/sh4/cpufit_seed.sh`), so the steps above cost no clock rate that a seed does not recover. One way to shorten that chain, not taken: let a misaligned access reach the cache and cancel it there (no game takes an address error), which takes the alignment check out of the issue decision; HS3's exception tests would need the cache to drop such a store. What is left is mostly the five-stage pipeline itself: a load's use one clock later, a taken branch's bubble, the serialisation on SR and PR. Metal Slug 6's FPU-heavy frames still lose a quarter of their busy clocks to the iterative unit (FADD 8 clocks, FMUL 6, FTRV 89); a pipelined unit is the remaining lever there, and the budget (`renderer2d.md`: 1,214 ALMs for the FPU's arithmetic) is the constraint. ## Speed work: the multiplier no longer holds the pipeline (2026-11-28) **Measured first.** Demo-fight recordings of Guilty Gear Isuka (field 5010) and Guilty Gear X 1.5 (field 4100), 4 million instructions each, through the trace bench with the multiplier's stalls listed by address (`tb_trace.cpp`, `-stall`). In Isuka's busy code 11% of the clocks went to the multiplier (7.5% with the multiply holding MA, 3.7% with an STS waiting for MACL), and nearly all of it to one routine of Sammy's library, a fixed-point scale it runs about 33,000 times in the recording (8C12BAB6 in Isuka, 8C0D58C6 in Guilty Gear X 1.5): MUL.L R5,R0 MOV #-7,R3 SHLD R3,R2 STS MACL,R0 MUL.L R5,R2 SHLD R3,R0 STS MACL,R2 The multiply sat in MA until its product was done (a clock to capture the operands, two for a 32x32 product), so the MOV and SHLD behind it, which do not touch MACH/MACL, waited too; STS then waited for the multiply to leave WB. 9 stall clocks a pass. **The change** (`rtl/sh4/int_pipe.sv`, `mac_dsp`): a multiply leaves MA as its operands and its command are captured (MAC.L and MAC.W on their second read), launches the next clock and retires in WB that same clock. The multiplier writes MACH/MACL itself when the product is done; a multiply that has retired is not dropped by an interrupt that redirects the pipeline meanwhile. An instruction that uses MACH/MACL waits in ID while a multiply is in flight (`mac_armed`, `mac_dsp_busy`), except that in the clock a 32x32 product without accumulation is written, STS takes it from the product register (`mach_id`, `macl_id`): MUL.L and an STS of its MACL now issue four clocks apart, as the SH-4's (software manual: MUL.L latency 4 to MACL). The trace bench checks MACH/MACL at the next instruction when a multiply is still in flight at its retirement. **Result** (busy code's clocks; memory answering the clock after / the machine's memory model, `-sys`): | | Isuka | Guilty Gear X 1.5 | |---|---|---| | before | 2,685,098 / 3,080,787 | 2,576,883 / 2,856,349 | | the multiply leaves MA | 2,551,567 / 2,947,213 (-5.0% / -4.3%) | 2,499,825 / 2,779,319 (-3.0% / -2.7%) | | and STS takes the product | 2,485,026 / 2,880,672 (-7.5% / -6.5%) | 2,461,422 / 2,740,918 (-4.5% / -4.0%) | The routine's remaining wait is 3 clocks a pass (STS behind the second multiply). HS3's testbench passes (122 tests, its random-interrupt oracle among them, with multiplies in flight at the interrupts), and the 23 recordings still on disk (KOF XI, KOF NeoWave, Samurai Shodown VI, Metal Slug 6, Sushi Bar, Isuka, The Rumble Fish 2, the attract loop's title and rankings) replay without a difference at both memory timings: 20 to their end, two older ones up to where they lack store-queue records, and one of Metal Slug 6's up to an interrupt the bench does not raise (5,006,190 instructions, the same with the core before). The fit (seed 2) has the CPU's clock 0.18 ns short of 73.6 MHz, on the instruction cache's tags to the branch target (`arm_tgt`), a path the change does not touch; without the STS bypass the same seed had 0.15 ns to spare. **What would come next for the busy code** (the machine's memory model scaled to 115.7 MHz: a second-level hit 14 clocks, a miss 66): with main RAM in SDRAM and a miss at 20 clocks, Isuka's busy code would take 11.3% fewer clocks (3,098,751 -> 2,747,561) and Guilty Gear X 1.5's 7.4% (2,917,041 -> 2,702,451). Tried, and measured on the board it is the other way round: the model's DDR3 was too slow (`system.md`, "Main RAM in SDRAM, tried"). ## The CPU's clock above what timing analysis signs off (2026-11-29) The OSD's CPU clock reaches 115.7 MHz, but the analysis signs the CPU off at the PLL's compiled 73.6 MHz only, so which builds run at 115.7 is a matter of placement: build `x` restarted KOF XI in its attract at 115.7 (and played it at 101), `t`, `v`, `y` and `z` play it; `y` was 0.14 ns short at 73.6 and `x` had 0.25 ns to spare, so the slack at 73.6 does not tell. A release is now first run on the seven games the owner keeps at 115.7 (`core.md`). Asking the fitter for more (an extra 3.7 ns of setup uncertainty on the CPU's clock, `../work/exp/seedsOC.sh`, so that it works towards 101 MHz) made it worse: the CPU's paths 0.43 ns longer than without, and the system clock missed. What limits the CPU (build `z`, `../work/exp/rptz.tcl`): its 400 worst paths are all within 0.2 ns of each other and share one trunk, the operand cache's tag RAM -> its hit -> the memory stage's advance (`exma_allow`) -> decode's (`idex_allow`) -> whether the fetch response is taken (`i_rsp_ready`) -> a fetch firing (`i_req_fire`, fanout 99) -> the registers it loads (the prediction state `bq_tgt`, `arm_tgt`, the pair slot): 11.5 ns of a 13.6 ns period at the slow corner, half of it routing. Shortening one end does not help while the trunk is shared; what would is cutting it, for example a fetch that fires on a registered "room in a small instruction buffer" instead of on decode taking the response in the same clock. **Late enables as late selects** (`int_pipe.sv`): the trunk ends at the fetch firing (`i_req_fire`) and the pair capture, which were the load enables of the prediction state and the pair slot (`bq_tgt`, `bq_strong`, `arm_tgt`, `pair_pc`, `pair_inst`, `pair_pd`, `pair_ptgt`, `pair_pstrong`, `fetch_pending_pc`: about 200 flip-flops spread over the CPU). Each now loads a candidate and a hold copy every clock and keeps the enable in one flip-flop, its value the select between the two: the same register, one clock later in the same state, with the late signal reaching a few flip-flops instead of 200. Seven of Flycast's recordings (`../work/r3d/trall.sh`: KOF XI, Metal Slug 6, Samurai Shodown VI, Guilty Gear Isuka and X 1.5, KOF NeoWave, The Rumble Fish 2, a million instructions each) retire and match in exactly the clocks they took before. ## FIPR and FTRV as the chip computes them (2026-11-29) The 3D games run FTRV (a 4 x 4 matrix times a vector) 3,000 to 17,000 times a vblank at their busiest (`workload.md`: Knights of Valour 17,100, Demolish Fist 15,700, Dolphin Blue 13,600, Block Pong-Pong 6,800, The Rumble Fish 3,500). The unit did each as sixteen products summed one at a time in double precision, Flycast's way: 89 clocks, so at 115.7 MHz FTRV alone could take 65-80% of a 60 Hz frame in the first three. The owner found exactly those games' 3D scenes slow, and 115.7 MHz did little for them. How the chip does it is now known to the bit: skmp (Stefanos Kornilios Mitsis Poiitidis) measured FIPR, FTRV, FSCA and FSRRA on a Dreamcast and published a C model of them (`../ref/skmp_fpu/sh4_fpu_approx.h`, MIT; his blog post "SH4 FPU" and the gist it links), with 0 mismatches over tens of millions of cases. One block serves all four: four truncated Booth radix-4 multipliers, an aligner per product, a four-input adder and one rounding. A product keeps 28 bits (the array's rows cut below column 16, a negative row without its hot one, two small corrections, 2^19 added and 20 bits dropped); the four are aligned to the largest exponent by truncation, added exactly and rounded once. That is far simpler to make fast than Flycast's three rounded double additions, and it is what the games' authors ran: Flycast's FIPR differs from the chip's in 7.8% of random cases, nearly always by one unit. **`sh4_fvec.sv`**: that block, pipelined, a row a clock. Per lane the exact 24 x 24 product comes from a DSP block and what the cut rows lose is added beside it (the rows' bits below column 16, a one for each negative row: a sum of nine numbers of 16 bits; `../work/sh4/fvcmp.cpp` checked that decomposition against the model's array on 2 million pairs). Nine stages: operands taken apart, products, the loss summed, the 28-bit products, aligned, added, the magnitude and its leading one, cut to 24 bits, rounded with the specials. FIPR takes 11 clocks from start to done (26 before), FTRV 14 (89). `sh4_fpu.sv` hands both to it and loses its double-precision path. Denormal operands are zeros (FPSCR.DN = 1, as the games run) and FPSCR's cause and flag fields are not written, as before. Checks: `tb_fpu` now holds FIPR and FTRV to skmp's model, bit for bit (1,000,000 FIPRs and 400,000 FTRVs with zeros, infinities, NaNs, denormals and cancellation among the operands, operations cancelled midway: 0 differ); every other operation as before. The trace bench (`tb_trace`) checks each FIPR and FTRV the core retires against the model, from the trace's registers before it, and then writes Flycast's values into the core's registers where they differ (`int_pipe.sv`'s FPU registers are `public_flat_rw` for Verilator), so the recording goes on in step. Two 3D traces recorded for this (Flycast, 2,000,000 instructions each, from the games' busy 3D code: Dolphin Blue frame 1426, Knights of Valour frame 1999) pass the trace bench: 22,204 and 16,037 FIPRs and FTRVs, every one equal to the chip's. Up to where the old bench stopped (a NaN, below; 256,860 and 1,053,475 instructions) the new unit takes 14% and 13% fewer clocks for the whole code (1,204,199 → 1,038,867 and 2,323,215 → 2,014,137); in Knights of Valour's FTRVs alone 414,165 → 105,111. What the bench had to learn on the way: - **NaNs.** The SH-4 writes the quiet NaN it makes as 0x7FBFFFFF (the hardware manual: "Single-precision qNaN: H'7FBFFFFF"); Flycast keeps whatever the PC's FPU made (0xFFFFFFFF, a payload carried on). The core is right; the bench takes a NaN for a NaN and puts the trace's in (1,518 and 4,851 times in these traces: the games compute NaNs routinely). - **A line written back where a store-queue transfer is due.** Dolphin Blue writes its vertices to RAM through the store queues and drops the stale operand-cache line there first (OCBI, no write-back). The core had written that line back a little earlier, as the chip may (it was dirty and evicted), and the bench took the write-back for the transfer. It now tells them apart by the first longword; a transfer that never comes is still reported. - `tb_trace -list ` prints the trace's instructions (PC, opcode, R0-R15, FPUL, FPSCR) and its store-queue transfers; `-sqwatch ` prints the core's two store queues after each of those instructions (`sq` in `sh4_cache.sv` is `public_flat_rd` for it).