Skip to content

PS2 games in the browser: static recompilation to WebAssembly with a native runtime

C++

Merge upstream main and retain KH2 VU correctness fixes

Riccardo Gioratofb18dd15c6a0
diff --cc runtime/include/ps2/system.hpp
index 0d9e8a3,75cafa1..1018867
--- a/runtime/include/ps2/system.hpp
+++ b/runtime/include/ps2/system.hpp
@@@ -19,15 -19,9 +19,16 @@@ struct Press
std::uint64_t frame;
std::uint32_t frames;
std::uint16_t buttons;
+ std::uint8_t stick = 0;
};
+struct AxisPress {
+ std::uint64_t frame;
+ std::uint32_t frames;
+ int axis;
+ std::uint8_t value;
+};
+
struct Options {
bool trace_syscalls = false;
bool trace_io = false;
diff --cc runtime/src/system.cpp
index fe99fc3,e72e84d..ec90b08
--- a/runtime/src/system.cpp
+++ b/runtime/src/system.cpp
@@@ -101,18 -101,17 +101,26 @@@ void dump_frame()
}
void apply_presses() {
- if (g_options.presses.empty()) return;
- std::uint16_t mask = 0;
- std::uint8_t stick = 0;
- for (const Press &p : g_options.presses)
- if (g_frames >= p.frame && g_frames < p.frame + p.frames) {
- mask |= p.buttons;
- stick |= p.stick;
- }
- iop::sio2::set_buttons(0, mask);
- iop::sio2::set_axis(0, 2, (stick & 4u) ? 0x00 : (stick & 8u) ? 0xFF : 0x80);
- iop::sio2::set_axis(0, 3, (stick & 1u) ? 0x00 : (stick & 2u) ? 0xFF : 0x80);
++ if (!g_options.presses.empty()) {
++ std::uint16_t mask = 0;
++ std::uint8_t stick = 0;
++ for (const Press &p : g_options.presses)
++ if (g_frames >= p.frame && g_frames < p.frame + p.frames) {
++ mask |= p.buttons;
++ stick |= p.stick;
++ }
++ iop::sio2::set_buttons(0, mask);
++ iop::sio2::set_axis(0, 2, (stick & 4u) ? 0x00 : (stick & 8u) ? 0xFF : 0x80);
++ iop::sio2::set_axis(0, 3, (stick & 1u) ? 0x00 : (stick & 2u) ? 0xFF : 0x80);
++ }
+ if (!g_options.axis_presses.empty()) {
++ // Explicit axis holds override directional presses on that axis.
+ // Outside a hold the stick rests; within one it takes the given tilt.
+ std::uint8_t axes[4] = {0x80, 0x80, 0x80, 0x80};
+ for (const AxisPress &p : g_options.axis_presses)
+ if (g_frames >= p.frame && g_frames < p.frame + p.frames) axes[p.axis] = p.value;
+ for (int a = 0; a < 4; ++a) iop::sio2::set_axis(0, a, axes[a]);
+ }
- if (g_options.presses.empty()) return;
- std::uint16_t mask = 0;
- for (const Press &p : g_options.presses)
- if (g_frames >= p.frame && g_frames < p.frame + p.frames) mask |= p.buttons;
- iop::sio2::set_buttons(0, mask);
}
void time_frames() {
diff --cc runtime/src/vu_jit.cpp
index 77264b9,89eb485..40eb46c
--- a/runtime/src/vu_jit.cpp
+++ b/runtime/src/vu_jit.cpp
@@@ -30,8 -29,8 +29,8 @@@ constexpr ImportType kImportTypes[kImpo
};
enum Local : std::uint32_t {
- kR, kMem, kPend, kPendj, kEnding, kJpc, kPcw, kUclip, kUx, kUy, kUz, kUw, kTmp, kTmp2, kMacv, kStat, kSlot, kBranchReg, kBranchValue, kNextBranchReg, kNextBranchValue, kI32Locals,
- kUv = kI32Locals, kV0, kV1, kV2, kV3, kV4, kV5, kShadow0
- kR, kMem, kPend, kPendj, kEnding, kJpc, kPcw, kExit, kUclip, kTmp, kTmp2, kMacv, kStat, kSlot, kT, kSign, kExp, kVi0, kI32Locals = kVi0 + 16,
++ kR, kMem, kPend, kPendj, kEnding, kJpc, kPcw, kExit, kUclip, kTmp, kTmp2, kMacv, kStat, kSlot, kT, kSign, kExp, kBranchReg, kBranchValue, kNextBranchReg, kNextBranchValue, kVi0, kI32Locals = kVi0 + 16,
+ kBits = kI32Locals, kUv, kV0, kV1, kV2, kV3, kV4, kV5, kShadow0
};
constexpr std::uint32_t kI32Count = kI32Locals - 2;
constexpr std::uint32_t kVecTemps = kShadow0 - kUv;
@@@ -348,7 -381,11 +381,11 @@@ private
std::map<std::uint32_t, LowerInfo> lowers_;
std::map<std::uint32_t, bool> live_in_;
std::map<int, std::uint32_t> shadow_;
- std::uint32_t case_index_ = 0;
+ std::vector<std::uint64_t> shadow_in_, shadow_out_;
+ std::map<std::uint32_t, std::uint32_t> case_of_;
+ std::uint32_t cases_ = 0, case_index_ = 0;
+ std::uint32_t vi_used_ = 0, vi_written_ = 0;
- bool any_status_ = false, any_flags_ = false;
++ bool any_status_ = false;
std::uint32_t word(std::uint32_t at) const {
std::uint32_t v;
@@@ -448,34 -534,35 +534,53 @@@
}
void vi(unsigned i) {
- c_.get(kR);
- c_.load16(vi_off(i));
+ if (!i) {
+ c_.i32c(0);
+ return;
+ }
+ vi_used_ |= 1u << i;
+ c_.get(kVi0 + i);
}
+ void branch_vi(unsigned i) {
+ if (!i) { c_.i32c(0); return; }
+ c_.get(kBranchValue);
+ vi(i);
+ c_.get(kBranchReg);
+ c_.i32c(i);
+ c_.op(kOpEq);
+ c_.op(kOpSelect);
+ }
+
+ bool delay_vi_ = false;
+
template <typename F>
void set_vi(unsigned i, F value) {
+ if (i && delay_vi_) {
+ vi(i);
+ c_.set(kNextBranchValue);
+ c_.i32c(i);
+ c_.set(kNextBranchReg);
+ }
- if (i) c_.get(kR);
value();
- if (i) c_.store16(vi_off(i));
- else c_.op(kOpDrop);
+ if (!i) {
+ c_.op(kOpDrop);
+ return;
+ }
+ vi_used_ |= 1u << i;
+ vi_written_ |= 1u << i;
+ c_.i32c(0xFFFFu);
+ c_.op(kOpAnd);
+ c_.set(kVi0 + i);
+ }
+
+ void write_back_vi() {
+ for (unsigned i = 1; i < 16; ++i) {
+ if (!(vi_written_ & (1u << i))) continue;
+ c_.get(kR);
+ c_.get(kVi0 + i);
+ c_.store16(vi_off(i));
+ }
}
template <typename F>
@@@ -1261,6 -1645,150 +1663,158 @@@ bool Translator::lower(std::uint32_t w
return true;
}
+ void Translator::instruction(std::uint32_t pc, std::uint32_t following) {
+ const std::uint32_t lo = word(pc), hi = word(pc + 4);
+ const Up u = decode_upper(hi);
- const bool flags_live = any_status_ ? true : (any_flags_ && out_live(pc));
++ const bool flags_live = any_status_ || out_live(pc);
+ const LowerInfo &li = lowers_[pc];
+
+ c_.get(kT);
+ c_.i32c(1);
+ c_.op(kOpAdd);
+ c_.set(kT);
+ if (reads_q(hi)) {
+ const QRead kind = q_read_kind(code_, kMask, pc);
+ if (kind == kQNew) flush_q();
+ else if (kind == kQDynamic) sync_q();
+ }
++ c_.i32c(0);
++ c_.set(kNextBranchReg);
++ // Flag reads bypass the VI delay seen by branch operands.
++ delay_vi_ = !branch_delay_exempt(lo);
+ upper_pre(u, flags_live);
+ if (hi & 0x80000000u) {
+ c_.get(kR);
+ c_.i32c(lo);
+ c_.store(kOffI);
+ } else if (!li.supported || !lower(lo, pc)) {
+ leave(pc);
+ }
++ c_.get(kNextBranchReg);
++ c_.set(kBranchReg);
++ c_.get(kNextBranchValue);
++ c_.set(kBranchValue);
+ upper_post(u, flags_live);
+ const int written = lower_write(pc);
+ const std::uint64_t live = shadow_out_[pc >> 3];
+ if (written >= 0 && shadow_.count(written) && ((live >> written) & 1u)) {
+ c_.get(kR);
+ c_.vload(reg_off(written));
+ vfix();
+ c_.set(shadow_.at(written));
+ }
+ const bool target_active = active(u, flags_live) && u.target > 0;
+ if (target_active && u.target != written && shadow_.count(u.target) && ((live >> u.target) & 1u)) {
+ if (!normalized(u.kind)) {
+ c_.get(kR);
+ c_.vload(reg_off(u.target));
+ vfix();
+ } else if (u.dest == 0xF) {
+ c_.get(kUv);
+ } else {
+ c_.get(kUv);
+ c_.get(shadow_.at(u.target));
+ lane_mask(u.dest);
+ c_.simd(kVBitselect);
+ }
+ c_.set(shadow_.at(u.target));
+ }
+ if (hi & 0x40000000u) {
+ c_.i32c(1);
+ c_.set(kEnding);
+ }
+
+ const std::uint32_t prev = (pc - 8u) & kMask;
+ if (in_.count(prev)) {
+ const LowerInfo &pl = lowers_[prev];
+ if (word(prev + 4) & 0x40000000u) {
+ c_.get(kEnding);
+ c_.open_if();
+ if (pl.branch || pl.jump) {
+ if (pl.branch) c_.i32c(pl.target & kMask);
+ else c_.get(kJpc);
+ c_.i32c((pc + 8u) & kMask);
+ c_.get(pl.branch ? kPend : kPendj);
+ c_.op(kOpSelect);
+ } else {
+ c_.i32c((pc + 8u) & kMask);
+ }
+ c_.set(kExit);
+ br(ret_depth());
+ c_.end();
+ }
+ if (pl.branch) {
+ c_.get(kPend);
+ c_.open_if();
+ c_.i32c(0);
+ c_.set(kPend);
+ go(pl.target);
+ c_.end();
+ }
+ if (pl.jump) {
+ c_.get(kPendj);
+ c_.open_if();
+ c_.i32c(0);
+ c_.set(kPendj);
+ c_.get(kJpc);
+ c_.set(kExit);
+ br(fallback_depth());
+ c_.end();
+ }
+ }
+ const std::uint32_t next = (pc + 8u) & kMask;
+ if (!in_.count(next)) leave(next);
+ else if (next != following) go(next);
+ }
+
+ void Translator::prologue() {
+ for (const std::uint32_t at : {kOffMacTs, kOffMacTs + 16u, kOffClipTs, kOffClipTs + 16u}) {
+ fl();
+ c_.vconst(0, 0, 0, 0);
+ c_.vstore(at);
+ }
+ const std::pair<std::uint32_t, std::uint32_t> rings[3] = {{kOffMac, kOffMacV}, {kOffStatus, kOffStatusV}, {kOffClip, kOffClipV}};
+ for (const auto &[from, to] : rings) {
+ c_.get(kR);
+ c_.load(from);
+ c_.simd(kVSplat);
+ c_.set(kV0);
+ fl();
+ c_.get(kV0);
+ c_.vstore(to);
+ fl();
+ c_.get(kV0);
+ c_.vstore(to + 16u);
+ }
+ fl();
+ c_.i32c(0);
+ c_.store(kOffMh);
+ fl();
+ c_.i32c(0);
+ c_.store(kOffCh);
+ fl();
+ c_.i32c(0);
+ c_.store8(kOffQPending);
+ c_.i32c(16);
+ c_.set(kT);
+ for (unsigned i = 1; i < 16; ++i) {
+ if (!(vi_used_ & (1u << i))) continue;
+ c_.get(kR);
+ c_.load16(vi_off(i));
+ c_.set(kVi0 + i);
+ }
+ const std::uint64_t live = shadow_in_[entry_ >> 3];
+ for (const auto &[reg, local] : shadow_) {
+ if (!((live >> reg) & 1u)) continue;
+ c_.get(kR);
+ c_.vload(reg_off(reg));
+ vfix();
+ c_.set(local);
+ }
+ c_.i32c(case_of_.at(entry_));
+ c_.set(kPcw);
+ }
+
bool Translator::run(std::vector<std::uint8_t> &out) {
pcs_ = reachable(code_, kMask, entry_);
if (pcs_.empty()) return false;
@@@ -1268,8 -1796,8 +1822,7 @@@
for (std::uint32_t pc : pcs_) {
LowerInfo l;
if (!(word(pc + 4) & 0x80000000u)) l = analyze_lower(word(pc), pc);
- any_status = any_status || l.reads_status;
+ any_status_ = any_status_ || l.reads_status;
- any_flags_ = any_flags_ || l.reads_flags;
lowers_[pc] = l;
}
for (std::uint32_t pc : pcs_) live_in_[pc] = false;
diff --cc scripts/test_vu_codegen.py
index b877705,0000000..da2a0fd
mode 100644,000000..100644
--- a/scripts/test_vu_codegen.py
+++ b/scripts/test_vu_codegen.py
@@@ -1,135 -1,0 +1,133 @@@
+#!/usr/bin/env python3
+"""Exercise native and Wasm VU code generation without a game disc.
+
+Requires a C++20 compiler with std::format and Node with Wasm SIMD/tail calls.
+Run from any directory: python3 scripts/test_vu_codegen.py [c++ compiler]
+"""
+import pathlib
+import subprocess
+import sys
+import tempfile
+
+ROOT = pathlib.Path(__file__).resolve().parents[1]
+CXX = sys.argv[1] if len(sys.argv) > 1 else 'clang++'
+
+GENERATOR = r'''
+#define main vurecomp_main
+#include "recomp/vurecomp.cpp"
+#undef main
+#include "runtime/src/vu_jit.hpp"
+#include <cstddef>
+
+int main(int argc, char **argv) {
+ const fs::path out = argv[1];
+ std::ofstream native(out / "native.cpp");
+ native << "#include <stdexcept>\n#include <cstdio>\n#include \"ps2/vu_ops.hpp\"\n"
+ "namespace ps2::vu { void interpret(int, std::uint32_t) { throw std::runtime_error(\"unexpected fallback\"); } }\n"
+ "using namespace ps2; using namespace ps2::vuops;\n";
+ constexpr std::uint32_t nop = 0x8000033C, unop = 0x000002FF, end = 0x40000000;
+ const auto addi = [](unsigned it, unsigned is, unsigned imm) { return (8u << 25) | (it << 16) | (is << 11) | imm; };
+ const auto branch = [](unsigned op, unsigned is, unsigned it, unsigned from, unsigned to) {
+ return (op << 25) | (is << 11) | (it << 16) | (((to - from - 8u) / 8u) & 0x7FFu);
+ };
+ for (int test = 0; test < 8; ++test) {
+ Program p{static_cast<std::uint64_t>(test), 0, std::vector<std::uint8_t>(16384)};
+ const auto put = [&](unsigned pc, std::uint32_t lo, std::uint32_t hi = unop) {
+ std::memcpy(p.code.data() + pc, &lo, 4);
+ std::memcpy(p.code.data() + pc + 4, &hi, 4);
+ };
+ for (unsigned pc = 0; pc < 128; pc += 8) put(pc, nop);
+ if (test < 3 || test == 5) {
+ // A preceding VI write delays a comparison, but FCAND does not.
+ put(0, test == 2 ? (0x12u << 25) | 1u : addi(1, 0, 1));
+ put(8, branch(test == 5 ? 0x2C : test == 2 ? 0x29 : 0x28, test == 1 ? 0 : 1, test == 0 ? 3 : 0, 8, 40));
+ put(24, addi(2, 0, 1), unop | end);
+ put(40, addi(2, 0, 2), unop | end);
+ } else if (test == 3) {
+ // The instruction executed before PC 40 is a taken branch's
+ // delay slot at PC 8, rather than the instruction at PC 32.
+ put(0, branch(0x20, 0, 0, 0, 40));
+ put(8, addi(1, 0, 1));
+ put(32, addi(1, 0, 3));
+ put(40, branch(0x28, 1, 3, 40, 72));
+ put(56, addi(2, 0, 1), unop | end);
+ put(72, addi(2, 0, 2), unop | end);
+ } else if (test >= 6) {
+ // JR/JALR use the saved operand; JALR may also overwrite it.
+ put(0, addi(1, 0, 1));
+ put(8, ((test == 6 ? 0x24u : 0x25u) << 25) | (1u << 11) | (1u << 16), unop | end);
+ } else {
+ // Flags remain observable after exit even with no local reader.
+ put(0, nop, (0xFu << 21) | (2u << 16) | (1u << 11) | (3u << 6) | 0x28u | end);
+ }
+ std::string name;
+ native << generate(p, name);
+ std::vector<std::uint8_t> wasm;
- if (!ps2::vu::jit::translate(p.code.data(), 0, {0x1000, 0x2000}, wasm)) return 1;
++ if (!ps2::vu::jit::translate(p.code.data(), 0, {0x1000}, wasm)) return 1;
+ std::ofstream(out / std::format("{}.wasm", test), std::ios::binary).write(reinterpret_cast<const char *>(wasm.data()), wasm.size());
+ }
+ native << "int main() {\n";
+ for (int test = 0; test < 8; ++test) {
+ native << "{ Vu0Regs r{}; std::uint8_t mem[16384]{}; r.vi[1]=2; r.vi[3]=2; r.clip=1;"
+ "for (int i=0;i<4;++i) r.vf[1].w[i]=0xBF800000; r.vf[0].w[3]=0x3F800000;\n";
+ if (test == 5) native << "r.vi[1]=0xFFFF;\n";
+ native << std::format("vu1_{:016X}(r, mem);\n", test);
+ native << (test >= 6 ? "if (r.tpc != 16) return 1;\n" : test == 4 ? "if (r.mac != 0xF0 || r.status != 0x82) return 1;\n" : "if (r.vi[2] != 2) return 1;\n");
+ native << "}\n";
+ }
+ native << "puts(\"8 native VU regressions passed\"); }\n";
+ std::ofstream offsets(out / "offsets.json");
+ offsets << std::format("{{\"vi\":{},\"vf\":{},\"clip\":{},\"mac\":{},\"status\":{},\"tpc\":{}}}", offsetof(ps2::Vu0Regs, vi), offsetof(ps2::Vu0Regs, vf), offsetof(ps2::Vu0Regs, clip), offsetof(ps2::Vu0Regs, mac), offsetof(ps2::Vu0Regs, status), offsetof(ps2::Vu0Regs, tpc));
+}
+'''
+
+WASM_TEST = r'''
+const fs = require('node:fs');
+const path = require('node:path');
+const dir = process.argv[2];
+const off = JSON.parse(fs.readFileSync(path.join(dir, 'offsets.json')));
+for (let test = 0; test < 8; ++test) {
+ const memory = new WebAssembly.Memory({initial: 1, maximum: 65536, shared: true});
+ const view = new DataView(memory.buffer);
+ const r = 0x3000;
+ view.setUint16(r + off.vi + 2, test === 5 ? 0xFFFF : 2, true);
+ view.setUint16(r + off.vi + 6, 2, true);
+ view.setUint32(r + off.clip, 1, true);
+ view.setUint32(r + off.vf + 12, 0x3F800000, true);
+ for (let i = 0; i < 4; ++i) view.setUint32(r + off.vf + 16 + 4*i, 0xBF800000, true);
+ const mod = new WebAssembly.Module(fs.readFileSync(path.join(dir, `${test}.wasm`)));
+ const env = {memory};
+ for (const imp of WebAssembly.Module.imports(mod)) {
+ if (imp.kind !== 'function') continue;
+ env[imp.name] = () => { throw Error(`Unexpected import: ${imp.name}`); };
+ }
- // These fixtures need only start, clip reads and flushing an idle Q pipe.
- env.start = () => {};
++ // The JIT initializes its pipelines inline; only FCAND needs an import.
+ env.clip = () => 1;
- env.flush_q = () => {};
+ new WebAssembly.Instance(mod, {env}).exports.run(r, 0x4000);
+ if (test >= 6) {
+ if (view.getUint32(r + off.tpc, true) !== 16) throw Error(`Register jump regression ${test}`);
+ } else if (test === 4) {
+ if (view.getUint32(r + off.mac, true) !== 0xF0 || view.getUint32(r + off.status, true) !== 0x82)
+ throw Error('Exit flags were dropped');
+ } else if (view.getUint16(r + off.vi + 4, true) !== 2) {
+ throw Error(`Branch VI regression ${test}`);
+ }
+}
+console.log('8 Wasm VU regressions passed');
+'''
+
+
+def run(*args):
+ subprocess.run(args, check=True, cwd=ROOT)
+
+
+with tempfile.TemporaryDirectory(prefix='vu-codegen-') as tmp:
+ tmp = pathlib.Path(tmp)
+ (tmp / 'generator.cpp').write_text(GENERATOR)
+ run(CXX, '-std=c++20', '-O2', '-I.', '-Iruntime/include',
+ str(tmp / 'generator.cpp'), 'runtime/src/vu_jit.cpp', '-o', str(tmp / 'generator'))
+ run(str(tmp / 'generator'), str(tmp))
+ run(CXX, '-std=c++20', '-O2', '-Iruntime/include', str(tmp / 'native.cpp'), '-o', str(tmp / 'native'))
+ run(str(tmp / 'native'))
+ (tmp / 'wasm.cjs').write_text(WASM_TEST)
+ run('node', str(tmp / 'wasm.cjs'), str(tmp))