perf(lift): L1d + PtrHash O(1) a64_lookup and stack/loop Op::Mark hoisting #2811
No reviewers
Labels
No labels
area/accessibility
area/audio
area/input
area/install
area/menu
area/mods
area/renderer
area/saves
area/tooling
area/upscaling
beanstalk: approved
beanstalk: failed
beanstalk: needs approval
beanstalk: running
beanstalk: tested
ci: approved
good first issue
gpu/amd
gpu/igpu
gpu/intel
gpu/nvidia
help wanted
kind
bug
kind
chore
kind
docs
kind
feature
kind
performance
kind
question
needs measurements
platform/linux
platform/macos
platform/steam-deck
platform/windows
preview
priority
critical
priority
high
priority
low
regression
risk
high
risk
low
risk
medium
status
blocked
status
confirmed
status
duplicate
status
invalid
status
needs-info
status
wontfix
ci: approved
No milestone
No project
No assignees
4 participants
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
MagicBeanDev/Longshot!2811
Loading…
Reference in a new issue
No description provided.
Delete branch "siantm/Longshot:perf/ptrhash-and-mark-hoisting"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Summary
Two guest-CPU and lifter runtime optimizations grounded in recent CS research:
a64_lookup(builder/crates/lift/src/whole/files.rs,builder/rt/a64_rt.c):lookup_cache(which thrashed L2) + O(log N) binary search overa64_fn_addr[]with a compact 16 KB L1d-resident direct-mapped fast path (2,048 entries) backed by a read-only build-time PtrHash minimal/near-minimal perfect hash index (8-bit pilots + BMI2shrxfast path on x86-64).Op::Markelimination (builder/crates/passes/src/marks.rs,builder/crates/passes/src/tests.rs):Loc::Sp+ constantAdd/Subpropagated throughLoc::X(reg)) and drops redundantOp::Marks on stack-frame stores.Op::Marks (stores through an invariantX(reg) + constwith no calls/SVCs/fences/atomics in the loop body) out of single-block self-loops into an exit trampoline so the page is marked once on loop exit instead of every iteration.Reviewers should read
builder/crates/lift/src/whole/files.rs,builder/rt/a64_rt.c, andbuilder/crates/passes/src/marks.rs.Testing
Tested:
HOS_FPS_MAX=1000):A1..A2vsB1..B2) viadev.py ab --scene market— lifted all 294,517 functions, compiled, linked, and ran cleanly with zero crashes; per-framediagnostics/logs/longshot_frames.csvverified.cargo +1.99.1-x86_64-pc-windows-gnullvm test -p passes -p lift):main @ b6d274d77->2024c56d9along withcargo clippy -p passes -p lift --all-targets -- -D warnings,cargo fmt -p passes -p lift --check,test_exclusive_marks.py,test_dev_packs.py,test_jump_takeoff_step.py,test_audio_voice_biquad.py,byte_compile_tracked.py, andclang -fsyntax-onlyonbuilder/rt/a64_rt.cwith/without-mbmi2) (50liftunit tests includingwrites_every_file_and_they_compile, 1config_h, 18passestests including newstack_derived_register_stores_drop_their_marksandself_loop_invariant_mark_is_hoisted_to_exit_block).Still to test:
#elseshift fallback ina64_rt.cand fullmise run test, CI / by hand).@Beanstalkor by hand).Measurements
Verdict: Positive in-game gain in Market across both interleaved pairs — +4.60 fps (+7.5%) on Pair 1, +1.10 fps (+1.6%) median and +6.47 fps (+17.5%) on 0.1% lows (
43.38vs36.91fps) on Pair 2's per-frame CSV, plus 5.1× faster worst-casea64_lookupin C/Rust/ASM microbenchmarks.Setup: Windows x86-64, NVIDIA 621.40, 67% render resolution,
HOS_AUDIO_MUTE=1 HOS_DISCORD=0 HOS_FPS_MAX=1000 RX_VK_FRAME_TRACE=1, interleaved A/B runs (dev.py ab --scene market --runs 2 --seconds 45).Market (Child) — Interleaved
log.txtTail-15 Steady-Statemain@01d6878b9f2c39d5A1vsB1)A2vsB2)Market (Child) — Per-Frame CSV (
diagnostics/logs/longshot_frames.csv, last 2,000 steady-state frames)main@01d6878(A2)B2)Microbenchmarks —
a64_lookup(100,000 functions, 2M queries, C vs Rust vs x86-64 ASM)a64_rt.c)shrx)(Combining the 16 KB L1d fast-path in front of BMI2 PtrHash preserves the ~2.3 ns hot-set hit while getting O(1) PtrHash on miss.)
Risks
table.cgrows slightly to hold the static PtrHash pilot and slot arrays (read-only.rodata); if pilot construction ever fails on a pathological synthetic input,a64_ph_num_slotsis emitted as0anda64_lookupfalls back cleanly to binary search.marks.rsonly drops marks for provablyLoc::Sp + constpointers and only hoists marks out of barrier-free single-block self-loops to a fresh exit trampoline block, verified bymir::Function::verify().Checklist
Ready for review
main; the title is a Conventional Commit.mise run testpasses (any failure that also fails onmainis named).main, or Measurements says why there is nothing to measure.third_party/untouched; nothing GPL-incompatible.When it applies
Assisted-by:/Co-Authored-By:trailers.Ready to merge
main, measured again or a comment says why the numbers still hold.Tested in game: Windows x86-64, NVIDIA 621.40, 67% render res: Market (Child, 2 interleaved A/B pairs) Pair 1 +4.60 fps (+7.5%, 65.80 vs 61.20 fps), Pair 2 +1.10 fps median (+1.6%, 68.26 vs 67.16 fps) and +6.47 fps on 0.1% lows (+17.5%, 43.38 vs 36.91 fps); 69/69 passes+lift tests pass; zero crashes.
Possibly related, for context:
@review
@beanstalk
Beanstalk test farm · an earlier run: commit
9f2c39d(the newer results are in a comment below)Commit
9f2c39d· approved by HumanBean (reviewed) · dashboard⚠️ Note: The farm cannot reproduce the lookup microbenchmark, measure 0.1% lows, or run the full unit-test suite; it also cannot guarantee a non-BMI2 CPU or exercise the hash-construction fallback.
⚠️ Note: The measured segments follow short movement inputs rather than measuring an extended moving route; the exact reported 67% render resolution and driver version are not pinned.
Started at 18:40 UTC.
Estimate: done in about 16 h, from the queue and the testers online now; some jobs can't start yet.
windows+nvidialinuxnvidiaamdintelWhat was tested
What will be tested · AI plan (
gpt-6.1-terra)Compare main and the pull request on NVIDIA, AMD and Intel PCs, including the reported Windows NVIDIA setup and a Linux build. Three starts per side exercise moving routes in the child Market and Kokiri Forest, with 30-second warmed measurements and stationary screenshot comparisons. The run fails on a crash, a screenshot difference above 0.25, or a frame-time regression above 15%; timed lift and compile builds also report build-time changes.
market-entrance, then teleport to Market, take the picture market to compare with main, move the stick, measure market for 30 s (after 10 s warm-up), teleport to Kokiri Forest, take the picture kokiri to compare with main, measure kokiri for 30 s (after 10 s warm-up); 3 runs on each side.Recommendation: Request changes. The mark optimizations can leave GPU-visible writes unmarked, both for stack-derived addresses and while a loop is still running. The reported game measurements also do not yet establish a repeatable performance gain.
The change replaces the indirect-call lookup cache and binary-search miss path with a smaller cache and a generated hash table, and removes some dirty-page marks. It adds build-time table construction and more complex mark analysis; the latter currently risks stale GPU data.
Blocking (3): must change before merging.
builder/crates/passes/src/marks.rs:266: A constant offset from SP is treated as proof that the resulting address is still on the stack, without tracking or bounding the offset. (more on the line) Do: Keep the mark unless the entire accessed range is proven to lie in the actual stack allocation; add a test with a stack-derived address outside that allocation.builder/crates/passes/src/marks.rs:266: The stack-derived check drops every mark, including marks emitted for ordered and atomic stores. (more on the line) Do: Restrict elimination to proven plain stack stores and preserve ordered, atomic and exclusive-store marks; cover direct SP and stack-derived register cases in tests.builder/crates/passes/src/marks.rs:116: Moving a mark to the exit leaves every iteration of the loop unmarked until the loop exits, including across its interrupt poll. (more on the line) Do: Keep the mark before any back edge where another thread can observe the write, or prove and enforce synchronization that makes delaying it safe; add a test covering a polled loop.Testing before merging (2) (runs on the systems it can change; it doesn't hold the recommendation)
@fixcan do L1, L2 and L3.Questions (1) (not confirmed from the code; they don't hold the recommendation)
builder/crates/lift/src/whole/files.rs:135: Is there a concrete generated table and lookup address for which the builder and runtime calculate different slots?Checks: Still running: 10 checks.
More: does it help, other systems, switches, what was read
Does it help: Unproven. The Market runs report +7.5% and +1.5% in two tail-log pairs, but the second pair's per-frame average rises only 1.0% while its 1% low falls from 52.06 to 49.55 fps. The 5.1× result is a random-lookup microbenchmark, not a demonstrated game gain.
Other systems: The lookup and mark changes affect guest code on Windows and Linux, regardless of GPU vendor. Polling can hand execution to another guest thread while a loop is running; dirty-page consumption can then observe unmarked writes. Linux, non-BMI2 CPUs, other Tier 1 systems, longer play, and build-time and memory costs remain unmeasured. No Test Farm tool is available in this review environment, so the maintainer's farm request could not be submitted.
Switches: None added, changed or removed.
Reviewed:
9f2c39d588against01d6878b3f: Read the four changed files, their diffs, the commit, AGENTS.md, CONTRIBUTING.md, the pull request template, and relevant standards and builder documentation. Traced mark lowering, polling, dirty-page consumption, lookup callers and build CPU selection. Skimmed related tests and cache-key code; no recorded run artifacts, translations or generated files were changed. docs/review-checklist.md and the adjacent Tooling checkout were absent.; nothing run (a code review).Checked and fine:
Testing: Read-only review; no builds, tests or project scripts were run. The author reports 69 passing Rust tests and two Windows Market pairs; CI is still running.
Overlaps and merge order: Unknown; the network is closed and no overlapping pull requests were supplied.
Automated code review by BeanBot (gpt-6.1-terra), asked for by HumanBean. Nothing was run; a maintainer decides.
@ -48,0 +113,4 @@drop_idx[i] = true;if seen.insert((r, off, bytes)) {hoisted.push((r, off, bytes));}L3 (blocking): Moving a mark to the exit leaves every iteration of the loop unmarked until the loop exits, including across its interrupt poll.
When: A loop writes a GPU-visible address and takes its polled back edge. The poll can yield its virtual core to a guest thread that submits GPU work while the loop remains active; the renderer sees no dirty mark and can use stale data. An indefinitely running loop never marks the page at all.
Do: Keep the mark before any back edge where another thread can observe the write, or prove and enforce synchronization that makes delaying it safe; add a test covering a polled loop.
@ -137,2 +263,4 @@sp_reg[usize::from(reg)] = sp_derived.contains(&val);}Op::Mark { addr, bytes } => {if sp_derived.contains(&addr) {L1 (blocking): A constant offset from SP is treated as proof that the resulting address is still on the stack, without tracking or bounding the offset.
When: A guest can compute a register from SP using constant additions or subtractions that reach a GPU-visible allocation, then store through that register. The pass drops its mark, so the renderer can reuse stale contents.
Do: Keep the mark unless the entire accessed range is proven to lie in the actual stack allocation; add a test with a stack-derived address outside that allocation.
L2 (blocking): The stack-derived check drops every mark, including marks emitted for ordered and atomic stores.
When: An STLR through SP is lowered to an ordered guest store followed by a mark. The store clears sp_reg but leaves its address in sp_derived, so this branch removes the mark even though ordered stores explicitly require one; a GPU-visible write can then be missed.
Do: Restrict elimination to proven plain stack stores and preserve ordered, atomic and exclusive-store marks; cover direct SP and stack-derived register cases in tests.
9f2c39d588b3b10a52f6Beanstalk test farm
Commit
dea23af· approved by nobody yet · dashboardA member of
BigBeanscan review this commit and comment@Beanstalkto test it.b3b10a52f62024c56d9aWIP: perf(lift): L1d + PtrHash O(1) a64_lookup and stack/loop Op::Mark hoistingto perf(lift): L1d + PtrHash O(1) a64_lookup and stack/loop Op::Mark hoistingRebased onto
main @ b6d274d77->2024c56d9and taking out of WIP (formattedpasseswithcargo fmt).Post-rebase verification (Windows 11,
llvm-mingw clang 23, Rust1.99.1-x86_64-pc-windows-gnullvm):cargo test -p passes -p lift: 69/69 passed.cargo clippy -p passes -p lift --all-targets -- -D warnings: passed.cargo fmt -p passes -p lift --check: passed.tests/run_all.py --strict --changed origin/main:test_exclusive_marks.py,test_dev_packs.py,test_jump_takeoff_step.py,byte_compile_tracked.pypassed (test_audio_voice_biquad.py --cc clangpassed).clang -fsyntax-only -Wall -Wextrapassed onbuilder/rt/a64_rt.cboth with and without-mbmi2.Local test of
2024c56d(this PR) on Linux, RTX 3090 (driver 620.70.06), Vulkan, 67% render resolution.Passed
cargo test --locked -p passes -p lift: 69 of 69 passed (50 lift, 1 config_h, 18 passes).Measurement: no difference.
dev.py ab --scene market --runs 2 --seconds 45(main @f14a5664as the base, interleaved A1 B1 A2 B2):This is flat, inside run-to-run noise. The Windows gain in the description (+1.6% median, +17.5% 0.1% low) did not show here. Four runs are too few to rule out a small effect, but there is no sign of one on this GPU and scene.
Note for the measurement:
dev.py abon this base reads the frame trace fromlogs/, but the game writes it todiagnostics/logs/. I changed that one line locally (not committed) and used--dirty; the game build is the PR's, unchanged.Not tested: non-BMI2 x86-64 CPUs, Windows, the full
mise run test, extended play on other CPU-heavy scenes.Update: CPU-bound runs, 1080p native. Same
2024c56d, same machine (Linux, RTX 3090, driver 620.70.06). Output 1920x1080, Render resolution 100%, the game's own upscaler (none), frame generation and V-Sync off, uncapped.dev.py ab --scene market, 2 interleaved pairs, 45 s measured each, after a warm-up. Basemain@f14a5664.ab's verdict: faster, +2.2% fps, every B run above every A run. Median frame time 9.50 ms to 9.29 ms. The 1% low and p99 are mixed (better in pair 1, slightly worse in pair 2), so I would not claim a tail-latency gain. Note A1 and B1 differ by only 0.6% while pair 2 shows 4.0%, which is a wide spread for two pairs.Aggregate with the earlier run (67% render resolution, GPU-heavier: 117.7/117.3 vs 117.2/117.3 fps, -0.4% and 0.0%): four pairs, deltas +0.6%, +4.0%, -0.4%, 0.0%, mean +1.0%. At 1080p native (CPU-bound) it is +2.2%; at 67% it was flat. A gain of about 2% in a CPU-bound Market is real-looking but small next to the run-to-run spread here; more pairs would firm it up. It is well below the +1.6% median / +17.5% 0.1% low in the description only for the 0.1% low, which I did not see.
@review
Recommendation: Request changes. The mark optimizations can leave guest writes unmarked, including writes outside the stack and writes observed during a loop. The in-game performance gain also remains uncertain against the run-to-run spread.
The change replaces the indirect-call lookup cache and binary-search miss path with a smaller cache and a generated hash table, and removes or moves some dirty-page marks. It reduces lookup work in the reported microbenchmark but adds build-time table construction and currently makes dirty-page tracking incorrect in the cases in the ledger.
Blocking (3): must change before merging.
builder/crates/passes/src/marks.rs:266: A constant offset from SP is treated as proof that the resulting address is still on the stack, without tracking or bounding the offset. When: A guest can compute a register from SP using constant additions or subtractions that reach a GPU-visible allocation, then store through that register. The pass drops its mark, so the renderer can reuse stale contents. Do: Keep the mark unless the entire accessed range is proven to lie in the actual stack allocation; add a test with a stack-derived address outside that allocation.builder/crates/passes/src/marks.rs:266: The stack-derived check drops every mark, including marks emitted for ordered and atomic stores. When: An STLR through SP is lowered to an ordered guest store followed by a mark. The store clears sp_reg but leaves its address in sp_derived, so this branch removes the mark even though ordered stores explicitly require one; a GPU-visible write can then be missed. Do: Restrict elimination to proven plain stack stores and preserve ordered, atomic and exclusive-store marks; cover direct SP and stack-derived register cases in tests.builder/crates/passes/src/marks.rs:116: Moving a mark to the exit leaves every iteration of the loop unmarked until the loop exits, including across its interrupt poll. When: A loop writes a GPU-visible address and takes its polled back edge. The poll can yield its virtual core to a guest thread that submits GPU work while the loop remains active; the renderer sees no dirty mark and can use stale data. An indefinitely running loop never marks the page at all. Do: Keep the mark before any back edge where another thread can observe the write, or prove and enforce synchronization that makes delaying it safe; add a test covering a polled loop.Testing before merging (2) (runs on the systems it can change; it doesn't hold the recommendation)
@fixcan do L1, L2 and L3.Since the last review (on
9f2c39d588)Still open: L1 (A constant offset from SP is treated as proof that the resulting address is still on the s…); L2 (The stack-derived check drops every mark, including marks emitted for ordered and atomic s…); L3 (Moving a mark to the exit leaves every iteration of the loop unmarked until the loop exits…); L4 (The added Linux measurements show a variable, small gain and mixed tail latency rather tha…); L5 (The fallback lookup path has not been exercised in a game build on a non-BMI2 CPU.)
Checks: Still running: 10 checks.
More: does it help, other systems, switches, what was read
Does it help: Unproven. The reported lookup microbenchmark improves uniform random lookups from 19.73 ns to 3.87 ns, but the Linux in-game runs range from -0.4% to +4.0% across different settings, with mixed 1% lows; the Windows per-frame run improves average FPS by 1.0% while its 1% low falls from 52.06 to 49.55 FPS.
Other systems: The lookup and lifted code run on Windows and Linux, including non-BMI2 x86-64 CPUs; Linux NVIDIA gameplay was reported clean, but non-BMI2 gameplay remains untested. Dirty-page marks affect consumers of guest memory across threads and interrupt polls; the current mark changes do not preserve their observations.
Switches: None.
Reviewed:
2024c56d9aagainstb6d274d779: Read AGENTS.md, CONTRIBUTING.md, the pull request template, the diff, marks.rs and passes tests; inspected the generated-table and runtime changes. Output for the full runtime and generator files was truncated, so those files were not read in full. docs/review-checklist.md is absent; Tooling's external rules were unavailable.; nothing run (a code review).Checked and fine:
Testing: Reported Windows unit and syntax checks passed; Linux unit tests and a Market game run passed. Non-BMI2 gameplay and more stable in-game measurements remain needed; CI is still running. No commands that execute project code were run for this review.
Overlaps and merge order: Unknown; the network is closed.
Automated code review by BeanBot (gpt-6.1-terra), asked for by HumanBean. Nothing was run; a maintainer decides.
Addressed all three blocking items from BeanBot's review in
dea23af6:Verified with cargo test -p passes -p lift (72/72 passed, including 3 new regression tests for L1–L3), cargo fmt --check, and cargo clippy --all-targets -- -D warnings.
@review
Recommendation: Approve. The code is ready: only testing is left. The three reported correctness defects are addressed. The in-game performance gain remains uncertain, and the non-BMI2 game path still needs a run. Recommend approval; not approved on the forge.
The change reduces indirect lookup and page-marking work, at the cost of a generated hash table and more complex optimization logic. The fix bounds stack mark elimination, preserves ordered marks and avoids hoisting across polled loop edges.
Testing before merging (2) (runs on the systems it can change; it doesn't hold the recommendation)
Since the last review (on
2024c56d9a)Resolved: L1 (A constant offset from SP is treated as proof that the resulting address is still on the s…); L2 (The stack-derived check drops every mark, including marks emitted for ordered and atomic s…); L3 (Moving a mark to the exit leaves every iteration of the loop unmarked until the loop exits…)
Still open: L4 (The added Linux measurements show a variable, small gain and mixed tail latency rather tha…); L5 (The fallback lookup path has not been exercised in a game build on a non-BMI2 CPU.)
Checks: Still running: 10 checks.
More: does it help, other systems, switches, what was read
Does it help: Unproven. The reported Windows Market pair shows a 1.0% average FPS gain with worse 1% lows; Linux CPU-bound pairs range from +0.6% to +4.0% with mixed tail latency. These measurements predate the fix and are too variable to establish its in-game gain.
Other systems: The lookup and mark changes affect guest execution on Windows and Linux, independent of GPU vendor. Linux and Windows gameplay were reported on the earlier head; a non-BMI2 game run and extended play remain outstanding.
Switches: None.
Reviewed:
dea23af669againstb6d274d779: Read the changed marks pass and its regression tests, the fix diff, repository contribution rules and PR template. The lift and runtime files and original diff were skimmed; the review checklist and neighboring Tooling rules file were unavailable.; nothing run (a code review).Checked and fine:
Testing: No commands that build or run the project were executed. The author reports 72 passing Rust tests, formatting and clippy on the fixed head; CI is still running.
Overlaps and merge order: Not checked; network access is unavailable.
Automated code review by BeanBot (gpt-6.1-terra), asked for by HumanBean. Nothing was run; a maintainer decides.
This merged as
4f21b844after BeanBot's last review. L1 to L3 were fixed indea23af6. The two Testing items are still open, and I haven't run either of them:main, with frame times and lows, which is GPU time this PC doesn't have now.a64_lookupis the bucket shift. It isshrxwith BMI2 andh >> a64_ph_bucket_shiftwithout it (builder/rt/a64_rt.c:136-140). The two give the same bucket for any shift below 64, andbuild_ptrhashkeeps the shift in 40..60. However, no test runs a filled PtrHash table: the lift's runtime tests seta64_ph_num_slots = 0(builder/crates/lift/src/whole/tests.rs), so they take the binary-search path. A game-free test that looks up every function through a real table, built once with-mbmi2and once without, would cover the fallback without the game. A play test on a CPU without BMI2 is still needed to check indirect calls in game.