Skip to content

[GPU] Demon's Souls gameplay from 7.6 to about 12 fps, and its loading crash - #49

Merged
xnetcat merged 195 commits into
mainfrom
perf/ds-30fps
Nov 19, 2026
Merged

xnetcat merged 195 commits into
mainfrom
perf/ds-30fps

Conversation

@xnetcat

@xnetcat xnetcat commented Nov 17, 2026

Copy link
Copy Markdown
Collaborator

Before submitting

Please read our contribution guidelines before opening a pull request:

➡️ CONTRIBUTING.md

Summary

Demon's Souls in gameplay (base M4, 1080p, the spawn point of the golden save) goes from 7.6–7.7 fps on main to about 12–13 fps. Nothing here is keyed to the title: the changes are in the shared GPU engine, the Metal backend, the shader translator and the Agc/kernel HLE. A loading crash that hit about one Demon's Souls boot in thirteen is fixed as well.

30 fps is not reached. With every draw dropped the frame is still 23.5 ms at 540p and GPU-bound, and at 1080p the GPU's own work is about 51 ms a frame, so the rest of the way is not in this PR.

Step (same scenario, one machine) Frame fps
main 368a616, quiet machine after a restart 130–132 ms 7.6–7.7
native Agc stubs + resolve ownership lines + read-binding memo (6d0f470) 101 ms 9.9
draws resolved ahead of the worker, read proofs, resolve memo (e6679a1) 82.2 ms 12.2
fused multiply-add on by default (80d99a4) 80.3 ms 12.4
wider half-local branch proof in wave64 compute (1d3bba6) 76.6–77.4 ms 13

What changed, by where the time was:

  • Guest side. Native stubs for the Agc calls the game makes tens of thousands of times a frame (sceAgcDcbDrawIndexIndirect, sceAgcCreatePrimState, CbSetShRegistersDirect in one reservation, scePthreadGetthreadid), and managed guest-memory accesses that no longer share a lock (per-thread stripes): import gateway calls 96.6k → 52.3k a frame.
  • Program resolution. Draws and dispatches are resolved ahead of the GPU worker on a resolver thread and taken only when nothing they read has changed since (program cache stamp, logged GPU writes, exact effects of kernel fills and copies). A content-keyed resolve memo and read proofs let a cached draw skip the resource walk. Verify modes for each exist and ran clean.
  • Metal worker. Read-only binding memo, a stage binding plan, upload prelude (a CPU-caused upload no longer ends the open render pass), label copies landed inside the open compute encoder, several stale/published runs per image so an aliased array reloads only the run that changed, pooled meshlet buffers.
  • Shaders. Legacy multiply-add fused by default (SHARPEMU_MSL_FUSE_MAD=0 restores the exact form), a wider proof for half-local EXEC branches in wave64 compute, and vertex-buffer stride and format words read through Metal function constants, with pipeline variants per layout built in the background.
  • Loading crash. A managed write (here an AMPR file read) asked whether a write-back was in flight before it took the image-cache lock; one recorded while it waited was missed and landed over the file. It now asks again after the cache has been read. New device test AManagedWriteThatReachesTheCacheBehindAWritebackBeingRecordedWaitsForIt fails without the change.
  • Diagnostics, all off unless set: fault dump by register expression, GPU and HLE write rings, frame-overlap census, gate-hoist probe, draw-floor switch, per-encoder pass profile. docs/macos/configuration.md lists the supported ones.

Opt-in and unchanged by default: SHARPEMU_TITLE_SCENE_RESOLUTION (540p scene gives about 15–18 fps in Demon's Souls, but changes the picture), SHARPEMU_FLIP_AHEAD, SHARPEMU_RESOLVE_SHARDS (two shards gave no frame-time gain).

Testing

All on a base M4 at 1080p, frames checked at full size.

  • Demon's Souls (PPSA01342) – boots, loads the save and reaches gameplay; frame times are in the table above (quiet machine, same scenario, measured as each step landed). The commits after ac81c83 were run in the game (gameplay reached, no fatal, their counters and verify modes clean) but their frame time is not measured: the machine was under memory pressure for those runs.
  • Demon's Souls loading crash – one capture shows the store returning while the write-back's submission was not complete and the texels landing during the read. With the fix: 14 boots, 0 crashes. That count is too small to prove the rate changed (about 1 crash was expected); the device test is the evidence that the interleaving is closed.
  • Dreaming Sarah (title menu), Quake (main menu), void tRrLM(); //Void Terrarium (in game), The Oregon Trail (menu), Superliminal (first room) – 60 fps, alive at the end of the run, final frame matches the earlier checked runs (mean difference at most 2.1 of 255 over the game area).
  • Poppy Playtime Chapter 1 (PPSA18454) – title menu and the first lobby render as before; 190 consecutive presented frames in the lobby differ only by noise. The title menu shows a whole-black game image in some window captures, on main as well (5 of 80 captures on main, 8 of 80 here), so it is not from this branch and is being looked at separately.
  • dotnet test SharpEmu.slnx -c Release: every assembly passes (Libs 10639, Gpu.Metal 2073, ShaderCompiler.Metal 4833, ShaderCompiler 2550).
  • SHARPEMU_TEST_REQUIRE_DEVICE=1 on SharpEmu.Gpu.Metal.Tests: 2069 pass, 4 fail, 7 skipped. Three are the MetalClearFoldingTests that fail on main too; the fourth, MetalImageBudgetTests.TheHostReadingIsLive, reads the host's memory footprint and has failed before on this machine under load.
  • uvx reuse lint clean; Python build-tool tests pass.

Not covered

  • 30 fps in Demon's Souls. Not reached; see the summary.
  • GTA V and Silent Hill: The Short Message at this head. Both were compared with main at 1d3bba6 (scenes reached, picture the same). They were not run again after the buffer-word variants and the later resolver commits, because the machine did not have the memory for them.
  • Frame time of the commits after ac81c83 (buffer-word variants loaded from their own archive files, dispatches answered off the shared resolve lock, exact effects of kernel fills and copies). Baking the same buffer words measured GPU 58.2 → 50.9 ms a frame; the variant path itself has no clean measurement yet.
  • The device suites are not part of CI.

Checklist

  • I have read and followed CONTRIBUTING.md.
  • I tested my changes or marked the testing section as N/A.
  • I wrote this pull request description myself and did not paste AI-generated explanations.
  • I listed the game(s) I tested (or marked the testing section as N/A).

xnetcat and others added 30 commits November 15, 2026 01:42
…direct

DrawIndexIndirect writes its five dwords and the cursor in one TryEmitCommandDwords
round instead of an allocation plus four writes. The modifier's user-SGPR slot decode
moves into AgcExports.IndexIndirectRegisterLocations (shared by DrawIndirect,
DrawIndexIndirect and DrawIndexIndirectMulti) and the packet stub encodes the same
slots through a new ModifierSgprSlots word kind; DrawInitiator now ORs in its constant.
The randomized stub-vs-export test covers both builders with modifiers built to hit
stages 3/5 against the others and bits 0, 1, 2, 8 and 32.

Co-Authored-By: Claude <noreply@anthropic.com>
…al once per resolution and per re-check

On the resolving thread a word in a page that is not clean ran ConcurrentOwner twice, for the page and
for the word, each able to take the image-cache lock, send for the completed serial and take the
overlay locks; the worker's re-check of a resolution sent for the serial once per answer. Demon's Souls
keeps a pending GPU write in its descriptor page, so each of the ~45 words a stage reads paid both tests.

- A page found owned is remembered for the rest of the resolution (a ring beside the clean pages), and
  in it the 256-byte line of a read is tested before the read: a clean line is recorded once, like a
  clean page, and its words are read from it; only the words of an owned line are tested one by one.
  Every test is an overlap test, so a clean line is clean for every range inside it, and its answer is
  checked again at the take like any other. SHARPEMU_CONCURRENT_OWNED_LINES=0 restores the per-word
  page and word tests.
- A resolution and a worker re-check each read the completed serial once, at their first test that
  needs it, as the worker's scoped serial (4e2e63f64) did for compute materializations. A serial only
  grows, so an older one reports more writes pending, never fewer: no answer becomes clean that would
  not be clean with a newer serial. SHARPEMU_CONCURRENT_SCOPED_SERIAL=0 sends at every test again.
- The PERF prefetch section gains owner_tests=(page,line,word,recheck,image_locks,serial_reads,
  overlay_calls), counted per resolution or re-check and added to the host's totals once at its end.

Bench (MetalClearFoldingTests.ConcurrentResolveCostOverAnOwnedDescriptorPage, SHARPEMU_BENCH_WORD_READS=
20000; 45 words over 4 lines of a page with one pending write, 250 live records; load 6.0):
both off 11.22 us/resolve, 5.52 us/re-check; owned lines only 1.11 / 0.54; scoped serial only
10.97 / 5.07; both on 0.99 / 0.46.

Co-Authored-By: Claude <noreply@anthropic.com>
…adAddress

sceAgcCbSetShRegisterRangeDirect with a null source reserves the payload for the
caller, which then asks sceAgcGetDataPacketPayloadAddress for it and fills it: the
pattern Demon's Souls runs ~6,400 times a frame. The range stub now handles a null
source as the export does (no overlap check, no copy, any count up to the packet's
0x3FFF limit) instead of declining, and the payload-address query gets its own stub
(type 0: header count all ones -> 0, else packet+4; any other type: packet+8). It
declines for low/non-user pointers and page-crossing accesses and needs the export
behind its trampoline. Tests run both stubs against the exports.

Co-Authored-By: Claude <noreply@anthropic.com>
CreatePrimState made about 15 guest reads and 10 writes per call. Its success path
now reads each shader header (0x28..0x5A) and specials block (0x00..0x2F) once and
writes the cx and uc register blocks with one TryWritePair; anything that path could
answer differently (a failing read, a wrong shader type, a null specials pointer, a
destination overlapping what is read, a failed write) falls back to the field-by-field
code, which keeps every partial write and MEMORY_FAULT/INVALID_ARGUMENT answer.
SHARPEMU_AGC_PRIMSTATE_FAST=0 keeps the old path. The export reads registers only and
never blocks or calls back, so it joins the trivial leaves. CreateInterpolantMapping
reads each shader's two header fields in one read (the separate reads still answer
when it fails).

PerfAudit 'agc' gains DcbDrawIndexIndirect and CreatePrimState benches; the tool's
fakes are brought up to the current IRenderHost/IShaderPipelineProvider so it builds.

Co-Authored-By: Claude <noreply@anthropic.com>
The per-host-thread GuestFastPath block gains the bound self handle's unique thread
id at offset 24 (free until now). KernelPthreadState.GetCurrentThreadUniqueId
publishes it whenever it answers for a bound guest thread, and only into a block
whose self handle is that very thread; every path that clears or replaces the self
handle (BindGuestThread, PublishHostSelf, Disable, UnbindCurrentThread,
ForgetPublishedSelves, ReleaseThread) clears the id first. The stub for
scePthreadGetthreadid and pthread_getthreadid_np answers the id and declines with no
block, no self handle or no id. SHARPEMU_HLE_FAST_THREADID=0 keeps the export.

Co-Authored-By: Claude <noreply@anthropic.com>
…e it while its inputs stand

For every read-only storage buffer of every draw, BindResources checked the mapping twice, flushed the
images over the range, ordered it after deferred copies and staged stores, looked for a staged copy to
share and resolved its window; ObtainBuffer ran the same chain for index and indirect buffers. A
worker-owned MetalReadBindingMemo keeps the window range a read-only binding resolved to, keyed by
(address, size, compute stage), and answers the next binding of the range while:
- the range translates to the same backing alias (read on every hit, so a remap misses; an alias over
  the whole range is what both mapping checks answered);
- the stamp holds: guest-memory submission, window partition and trap versions (holes, stale windows),
  ImageSetVersion and Epochs.GpuModified, read per lookup and on both sides of the chain an entry is
  stored from (a miss earlier in a draw can move the cuts);
- there is no deferred fill, deferred label copy or staged copy at all (checked live, which leaves the
  ordering and sharing steps nothing to do), no trap, no released single-copy chunk, and no trace.
Only answers from the in-place window path are kept, for ranges mapped whole whose flush found no
GPU-modified image (MetalImageCache.FlushGpuWrites now says whether it did). Written bindings always
take the full chain. The design's mapping-version stamp (DeviceAddressMappingVersion) is replaced by the
alias check: span registrations do not cover every remap of backed memory.

SHARPEMU_METAL_V2_READ_BINDING_MEMO=0 takes the full chain for every binding; =verify runs it behind
every hit and raises a fatal error on a different range or a found image.

The PERF line gains read_binding_memo=(hits,misses,stores,verified) and, for a later stage binding
plan, bind_shape=(binds, image_set_moves, binding_epoch_moves, snapshot_repeats per array among the
last 8 per stage kind, buffers_read_only, buffers_written, tiny_pass_dummies).

DsDrawCostBenchTests (ROUNDS=150, ABAB x3, load 5.1-5.8): draws 3.274-3.350 -> 3.271-3.305 us
(within noise), dispatches 4.35-4.41 -> 4.22-4.26 us; checksums A971C9681B3C2325 / 4FAE6605365DFE0E
equal with the memo at 0, on and verify; hits 91% of draw lookups, 98% of dispatch lookups.

Co-Authored-By: Claude <noreply@anthropic.com>
DispatchImportCore tested the address probe, the register-packet profile,
SHARPEMU_PERF_HLE, the guest-RIP sampler, the all-imports warning and the
import filter on every call. They are fixed when the session is configured,
so one precomputed _leafDiagnosticsOff skips them together. NoteHleEntry,
the session counters and the shutdown safe point still run on every call.

Co-Authored-By: Claude <noreply@anthropic.com>
A range of more than 256 bytes passed the line guard by unsigned wrap-around, so only the line it starts in was tested and a pending write further on in the range was missed.
…egistersDirect shapes

GatewayCrossingMeasurementTests (opt-in, SHARPEMU_GATEWAY_BENCH_OUTPUT names the
report) calls the real import trampoline from native code for a trivial-leaf
and a full-path import, against a native stub and DispatchImportCore alone.

SHARPEMU_PERF_HLE=1 adds two [PERF][HLE] lines: how mutex lock, trylock and
unlock arguments resolve (explicit slot, implicit slot, aliased, created from
the static initialiser or a zero slot, missing) and how many were uncontended;
and the shape of sceAgcCbSetShRegistersDirect calls that reach the export
(over the stub's 32 registers, unsorted, duplicates, runs, source overlap,
no room, failures).

Co-Authored-By: Claude <noreply@anthropic.com>
…ast preparation of the same snapshot arrays

The materializer hands draws whose descriptors evaluate the same way the same Images and Samplers arrays
(Demon's Souls: nine in ten stage bindings), and PrepareBindings looked every T# up in the texture memo and
every S# up in the sampler cache again. The stage binding plan keeps, per stage, program and pair of arrays
(two-way, 1024 sets), the memo entry each T# key maps to and the sampler for each S# and integer-view class.
Each entry's stamp is still checked per use, a stale one is resolved and memoised as on a lookup miss; a
cleared memo or sampler cache retires every plan (generations); a host movie stage takes the full path; the
sampler class is resolved again per draw. Buffers are not planned.

SHARPEMU_METAL_V2_STAGE_PLAN=0 looks everything up; =verify checks every planned answer against a fresh
lookup and raises a fatal error on a difference. stage_plan=(...) on the PERF line counts hits and misses by
cause. The bind_shape ring scans now run only under SHARPEMU_METAL_V2_BIND_SHAPE=1 or the trace switch.

DsDrawCostBench (6 runs per arm, ABBA): draws 3.297 -> 3.254 us, dispatches 4.11 -> 3.97 us, plan hit rate
97.5% / 97.4%, checksums unchanged.

Co-Authored-By: Claude <noreply@anthropic.com>
… lookups miss

Demon's Souls answered 37% of its read-only binding lookups from the memo against 91-98% in the bench, with
nearly every miss stored again. In DsDrawCostBench most draw misses were other ranges' entries in the
range's direct-mapped slot (170k of 217k misses over the run); a command buffer binds a few thousand ranges.
The memo now keeps two ways per set (2048 sets), the more recently used first, and the PERF line's
read_binding_memo field says why lookups missed (empty set, other ranges, alias or which stamp field moved,
live refusals) and how many stores evicted another range, for the next game run to read.

DsDrawCostBench (6 runs per arm, ABBA): draw memo hit rate 91.3% -> 97.9% (remaining misses: a new command
buffer's serial), draws 3.288 -> 3.272 us, dispatches 3.98 -> 3.86 us (noisy), checksums unchanged.

Co-Authored-By: Claude <noreply@anthropic.com>
…gs per encoder

EndEncoders formatted the cause as cause.ToString().ToLowerInvariant() for the pass profile and union-pass
notes on every render and compute encoder it ended, two allocations each. The lowercase names are made once.

DsDrawCostBench (6 runs per arm, ABBA; its streams end few encoders, so this is a no-change check): draws
3.286 -> 3.277 us, dispatches 4.06 -> 4.00 us, checksums unchanged.

Co-Authored-By: Claude <noreply@anthropic.com>
… each encoder is told

The dispatch extras of the host encode-cost plan are sized offline but not in the game: in DsDrawCostBench a
storage image's resolution and acquire take about 0.3 us each (two per dispatch, about 30% of a dispatch's
recording), and every compute encoder is told the submission's resident windows again (209 at the
Demon's Souls run's 120 s mark). The PERF line's bind_shape gains storage_images and the WAITS line
residency_named and compute_encoders, so the next game run says what memoising storage images or a residency
set for the windows would save before either is built.

Co-Authored-By: Claude <noreply@anthropic.com>
… threads

Each thread reads and writes its own 64 KiB of a real PhysicalVirtualMemory backing
(r8, r36, w8, pair, emit), and calls SharedBackingViews' single-view paths directly
counting refusals; the write rows rerun with HostBackingObject._managedWrites nulled to
split the write-interval ledger's cost from the alias pins'. Primitives p1-p7 (shared and
padded Interlocked, ThreadStatic, CurrentManagedThreadId, MemoryBarrier, shared RWLS read,
private-region PVM read). --qos=ui runs the workers at user-interactive QoS.
…ripes

A long[] with a 256-byte stride per stripe (a power of two of at least twice the
processor count, at most 64), indexed by the managed thread id, two lanes per stripe on
the stripe's own line. Entrants increment their stripe (a full fence) and re-check the
drainer's flag; drainers set the flag with a full fence and sum the stripes. The sum is
signed, so an exit on another thread still balances; a negative sum is fatal. No user yet.
HostBackingObject.TryEnterAliasAccess/ExitAliasAccess: the closing check, a stripe
increment, then the closing re-check (the same Dekker with Close as TryEnterAccess's
increment). ActiveAccesses, and so TryDisposeCore's drain, now include the alias stripes;
a negative stripe sum at the drain is fatal. SHARPEMU_ACCESS_STRIPES=0 sends alias
accesses through TryEnterAccess again. No caller yet; SharedBackingViews follows.
…ir stripe

An alias access (every lock-free single-view read and write) took two shared atomics on
the way in and two on the way out: SharedBackingViews._activeAccesses and the backing's
_accessState. It now increments the calling thread's stripe once and re-reads every
drainer's flag after it (copy reservation, Dispose, the backing's Close). The copy
reservation and Dispose sum the stripes (Dispose now fences its flags before it does);
the backing's drain already includes them. SHARPEMU_ACCESS_STRIPES=0 restores the two
shared counts.

Tests: a copy reservation waits for a writer paused before its bytes; ten writers never
tear a 256-byte record a reservation holds (both fail when the drains ignore the stripes);
readers racing Dispose; single-view accesses while another range is remapped.
Every ordinary managed write paid ~16 shared atomics (admission, identity, slot,
active/begun/completed counters, history) for a ledger nothing in production reads:
only TryReadMappedCopy* and ExecuteOriginalWrite observe it, and they have no
production caller. Until something captures a revision, reserves a publication or
enrolls a read watch, a writer now only increments its own stripe of a second lane,
re-reads the sticky observer flag (backing out to the full path if set) and gets a
dormant token; the byte intervals inside a dormant operation need no registration.
Observers set the flag with Interlocked.Exchange and refuse (never wait, counted in
ObservationRefusals) while the lane's sum is not zero; once one sees zero, every
dormant writer has landed and every later write takes admission, identity and history
exactly as before. The switch logs one [MEM] line per backing.
SHARPEMU_WRITE_INTERVALS_DORMANT=0 starts every ledger observed.

Tests: dormant writes touch no slot, history or counter and do not allocate; a dormant
writer paused before its bytes makes capture, read-watch enrollment and publication
reservation refuse, and after it lands they succeed and writes advance identity again
(fails when observers ignore the lane); a reserved publication always sees the bytes its
revision read while ten writers run. Ledger tests that count intervals observe first.
…rite does

GuestGpuMemory.MarkCpuWriteLanded(first, second) tested Covers, while the single-write
overload and the pre-write MarkCpuWrite test CoversWrites, so a pair write into a range
only a lazy registration covers (the PRT aperture) was announced before it landed but
never after: an upload between the two kept the old bytes and left the pages clean.
The new test (a pair must reach the stores exactly as its two writes do) failed before
the fix on arm64 and x64.
Each run of consecutive registers took a command-buffer state read, a cursor write and a
packet write: Demon's Souls calls this ~560 times a frame with 5-8 runs. When the buffer
already has room for every run's packet, they are reserved in place together and
committed with the cursor as one pair write (1 read + 1 pair per call). Without that room
the runs go one at a time exactly as before, each reaching the full callback with its
own size. SHARPEMU_AGC_COALESCE=0 always takes the run-by-run path.

Test: coalesced and run-by-run output compared byte for byte (memory, cursor, return,
callback requests, leaf decline) for the DS shape (unsorted, a duplicate, 7 runs) with
plenty of room, exactly enough, reserved dwords, one dword short (callback), room for the
first runs only, the same in a leaf, and a full buffer.
…g pays

label_land, label_batch, label_barrier, label_mix, label_force_by, label_force_range and
label_in_encoder_refused on the WAITS line. The landing cause is passed through
OrderAfterDeferredCopies and kept with _landDeferredLabels; held copies carry their kind
(command-processor write, end-of-pipe label, other). No behaviour change.
…wo dispatches

SHARPEMU_LABEL_SEPARATOR_BENCH_OUTPUT: 200 pairs of tiny dispatches separated by nothing,
an encoder split, a split with a blit, a device event, a shared event, or a word-copy
dispatch inside the open encoder. M4: 0 / 21 / 50 / 46 / 111 / 0.8 us per pair.
Step 0 of the meshlet cache plan, diagnostics only: meshlet_builds_by (new, changed,
recurring against the key's last 8 hashes, kept past removal), meshlet_hash_kb,
meshlet_build_kb, meshlet_build_split_ms (read, build, alloc), meshlet_entries and
meshlet_evictions on the PERF line; SHARPEMU_METAL_MESHLET_TRACE=1 prints the first
200 builds.
Step 1 of the meshlet cache plan: a key holds up to four built versions, each found
again only by a full-range hash equal to the current bytes, so content that cycles
through a few index patterns at one range stops rebuilding. A miss retires the least
recently used version through the existing completion-guarded release; the same-
submission skip returns the version that submission validated. PERF adds
meshlet_version_hits (hits one version per key would have rebuilt) and
meshlet_versions. SHARPEMU_METAL_MESHLET_VERSIONS=0 keeps one version per key.
… encoder

A batch of held copies with no CPU-visible copy lands as one scatter dispatch between two
memory barriers in the open compute encoder, at a forced landing or as EnsureComputeEncoder
opens one, instead of ending the encoder for an event barrier and a copy encoder. The encoder
waited on the encoder fence at its start, so the copies land after all earlier work in device
order and before all later work, as the device-only event gave. Refused (counted) without the
fence chain, with occlusion prefix sums owed, or with staged stores still to write back (they
land at the encoder end and must not overwrite a later copy). A CPU-visible copy keeps the
shared event. SHARPEMU_METAL_V2_LABELS_IN_ENCODER=0 off, =verify reads folded words back.
Step 2 of the meshlet cache plan: a buffer whose entry goes is kept, still resident,
in a free pool by capacity (quarter steps of a power of two, from 4 KiB; 32 MiB of free
buffers at most) once the submission that last used it has completed, and the next
build of that class writes into it. A rebuild then neither creates nor releases a
Metal buffer, so the shared resident list keeps its version and the next encoder
names nothing again. PERF adds meshlet_pool_hits, meshlet_pool_mb and
meshlet_resident_churn (buffers created or released). SHARPEMU_METAL_MESHLET_POOL=0
creates and releases per build as before.
The interpreter flags a WRITE_DATA (or qword run) causal when, since its queue's previous
one, a read was answered from a value not yet landed (a wait met by a recorded label or
store, its own last store, COPY_DATA of a pending value, an operand read from a pending
label, a COND_EXEC taking an owed operand as zero) or it emitted a partial flush, cache
action or acquire. The Metal host holds a causal write CPU-visible, and every later write
behind it until the held copies land; any other write is device-ordered, so a batch of
them lands inside the open compute encoder. Callers that cannot tell stay causal.
SHARPEMU_METAL_V2_CP_WRITE_DEVICE_ORDER=0 off; =verify keeps every write CPU-visible and
counts cp_write_order_suspects.
…en compute encoder

A command-processor write that is not causal, recorded while a compute encoder is open, is a
scatter dispatch between two memory barriers in that encoder at once instead of a held copy:
it lands where it was recorded, after all earlier work in device order, and the dispatch that
reads it has nothing to land. Held as before when a held copy covers its bytes (by guest
address or by destination buffer), when any command-processor write is held, when a staged
store over its bytes is still to be written back, or when it is not whole aligned words.
label_cp_in_encoder counts them. SHARPEMU_METAL_V2_CP_WRITES_IN_ENCODER=0 off.
SHARPEMU_METAL_V2_BUFFER_WORD_CONSTANTS (on with portable buffers; =0 restores
today's MSL) turns PortableBufferWord.ConstantsEnabled on in
ApplyTranslationSwitches, so the prewarm and the command stream translate alike;
the prewarm stamp names the switches, which keys the static precompile's
finished units, the only store that does not follow the source text.

Every function made from a translated library goes through
NewTranslatedFunction (the LOD statistics switch and buffer-word values, none
for the generic function), which replaces NewMipStatisticsFunction: a source
that declares the constants must be made with constant values.

A render pipeline whose programs declare buffer words keeps up to 16 variants
in a worker-only open-addressed table. Each draw hashes the words its shader
data holds at the declared dwords (CommitBindings records the stages) and
draws through the variant once it is built; the first draw of a layout draws
through the generic pipeline and queues the variant on two background
builders that compile at prewarm priority (EnterPrewarm). Specialized
functions are cached per module (at most 64), made outside the module's lock.
A variant is listed in the archive under its own pair key and in the state
table under its values. Mesh, rectangle-list and tessellation pipelines, the
pixel stage of a remapped pipeline, and compute programs stay generic; every
generic draw of a declaring program is counted on the PERF line
(buffer_words=[...]).
…nd compute its switch on use

A variant build ran on a plain thread, so a pipeline Metal refused went through
GpuFatal's process exit before the catch that keeps the draws generic; the builder
now runs its builds as work ahead of need. The switch was a static initialized from
a static of another part of the class, whose order is not defined. The corpus replay
can translate as the host does (SHARPEMU_CORPUS_PORTABLE=1): all 1,241 recorded
Demon's Souls programs translate with the constants on.
…tch's buffer words

A compute pipeline whose program declares buffer-word constants keeps up to 16
variants in the same worker-only table render pipelines use. CommitBindings(Compute)
notes the committed stage and the entry it was committed for; BindPipeline(Compute)
chooses once per dispatch (ComputeStateOf: the variant once built, else the generic
state, the reason counted, a stage committed for another entry counted unreadable);
EnsureComputePipelineState binds that choice on every path that binds the program's
state (direct, indirect, thread-unit indirect, tessellation hull dispatches). Variants
build on the same two background builders at prewarm priority under
GpuFatal.Speculatively; BuildComputePipelineState(variant: true) holds no runtime slot
and never takes the empty-kernel stand-in (the generic state runs instead). A compute
variant is stored as its own archive library file (ComputeBufferWordArchiveKey).
Counters per kind; the PERF line adds buffer_words_compute=[...] with generic_off.
SHARPEMU_METAL_V2_BUFFER_WORD_COMPUTE=0 keeps dispatches generic (no source change).

A library Metal loads from an archive library file (every warm start) holds the
function with its constants already resolved: a function specialized from it ignores
the values, so render variants built on a warm start ran the generic code. Specialized
functions now come from the module's MSL compiled again without the archive, once per
module on the builder (RetainSpecializableLibrary), or for a compute variant a past
session stored, from that variant's own file.
…ary file

A noted render pipeline is written as the library file of either stage key that has
none. A variant's functions carry one layout's strides and formats, so written under
its modules' keys (their files evicted or rejected) the next start would load that
layout as the library of every draw of the module. A variant is now listed under its
pair only.
… lane of their own

A render variant's specialized stages are written as library files of their own
(StageBufferWordArchiveKey: the module's library key, the LOD statistics switch and
every value of the stage; zero for a module without a key or a stage without buffer
words, never the module's key), and a later start loads each function from its file and
the pipeline from the segment its pair is listed in: no front end, no back end. A file
that does not load or lacks the function is counted (files_rejected) and the function
is built instead.

A module whose library this process compiled from its MSL (LibraryFromSource, kept
through the source-key dedupe) is specialized directly; only a library that came from
the archive needs its MSL compiled again, once per module (SpecializationGate keeps a
second builder from compiling it twice).

Variant builds no longer take the prewarm's slots, which the static precompile can hold
for minutes: four builders, and compiles (an archive miss only) in a lane of their own
(MetalCompileScheduler.EnterVariant, two slots, still behind the game's compiles).

The GPU worker no longer waits on a builder: segments are read and opened outside the
archive's lock; a builder never compiles or rebuilds a module, nor the LOD-statistics or
remapped pixel function a generic stage needs (the variant is counted unresident and its
draws stay generic); a capped layout no longer formats its warning on every draw.

The PERF fields add from_file / from_library / from_msl, msl_compiles,
pipelines_compiled, files_rejected, unresident, build_ms and wait_ms.
SHARPEMU_DS_SHARD_BENCH_OUTPUT captures the program takes of one worker
round of the DS-shaped stream and replays their resolution (inputs,
resolution in the host's concurrent-read scope, binding packets) on
N shards, each a ShaderPipelineCache + RenderExecutor of its own, routed
by a hash of the program pair (or of the job index). Reports jobs/s,
ms per frame, thread CPU and wall per job, and the resolve memo mix per
shard. Inert without the variable.
…E_SHARDS, default 2)

Each shard has its own queue, thread and resolve memo under its own gate; draws route by a hash of the memo-key
fields (vertex address and user data, the pixel's when active), dispatches by compute address. The shared tier
(program cache, vertex tables, translation, pipeline creation) stays under the pipeline cache's _resolveGate,
taken only on a memo miss; cached-materialization revalidation takes it too. Ordering holds across shards: the
finished count is the prefix over every shard's running or queued head, pause waits for all, caller and fallback
resolutions run on the job's own shard. 1 restores the single resolver. Per-shard counts, resolve and CPU time and
the shared-lock wait are in the prefetch counters' shards=(...) field.
…H_ENGINE=1)

Replays the captured frame through ParallelProgramPrefetch on fresh pipeline caches per arm, fingerprints the
programs every take hands out and counts program and pipeline creations; reports monitor contention, GC pauses
and frame times inside the timed part.
…emon's Souls

Same session, 1080p defaults: 80.8 ms median with one shard, 82.6 ms with two; the worker's
wait on the resolver fell by about 2 ms per frame, resolver CPU rose about 45% and 8-9 ms per
frame went to waiting on the shared lock. SHARPEMU_RESOLVE_SHARDS=2 still enables it.
SHARPEMU_METAL_V2_PROFILE_PASSES=1 sampled only render passes and the shared
compute encoder, so every transfer blit, tiler compute encoder, fill, copy,
staged store and label copy landed in the next record's gap_us. Those encoders
now open through their pass descriptors with start/end-of-encoder samples when
the profile is on (the plain calls are kept when it is off), each with a record
(k=blit, k=tiler-compute, k=host-compute) named for the transfer cause and the
label the call site reports. An encoder the sample ring has no room for is
recorded as us=? and counted. The sub line sums GPU time per kind (kind_us=),
the gaps (gaps_us=) and unsampled records.
…me floor

SHARPEMU_DIAG_SKIP_ALL_DRAWS_AFTER_S=<seconds> drops draws at translation, before they are
resolved or recorded; dispatches, labels and flips go on. Demon's Souls at the 540p scene cap:
23.5 ms per frame with it against 65-76 ms without, in the same run.
…with shards

With more than one resolve shard, a dispatch whose kept program still holds, or whose kept program only needs new
user data on a fast plan with a permutation already made, completes on its own thread (this thread's kept programs,
runtime inputs, user data memo and lookup options) without the shared tier; anything else (a replan, shader calls,
traces, a cached materialization, a new permutation, the identity recheck) still takes it. SHARPEMU_RESOLVE_UNSHARED_COMPUTE=0
sends every dispatch through the shared lock. One shard is unchanged.

The shared lock's takes and wait are split by reason in the prefetch counters (shared_by=, shared_wait_by=), with the
dispatches answered off it (unshared_compute=) and why a rebinding still took it (rebind_shared_by=); the resolvers'
sampled allocation is split by path and step (alloc_by_path=, alloc_by_step=). A retry's read log is bound to the
thread that set it, so another resolver's guest reads are never logged into it.
… pipelined worker

SHARPEMU_DS_DRAW_BENCH_DISPATCH_REBIND=1 runs each compute program over the four tables in turn, so dispatches rebind
as in Demon's Souls; SHARPEMU_DS_SHARD_BENCH_DRAIN=pipeline takes each job on a worker thread inside the timed part
with the submitter at most _WINDOW (64) jobs ahead, so the resolvers draw assumptions from the host's pool as in game.
The arm line reports the shared-lock split, allocation by path and step, and the resolvers' idle time.
…when the write covers its reads

A dispatch the recorder consumes as a kernel fill or copy (TryClearImageFromKernelFill, TryCopyWordsOnHost) on Metal
either does a storage store's bookkeeping and logs the write over its destination (NoteGuestMemoryWrite), or writes
nothing (identical elision). The dispatch take already refuses a job whose reads a write logged since its resolution
began covers (IsStillCurrentAcrossDispatches), so those two kinds no longer refuse every job resolved ahead of them.
Every other effect kind, and every effect for a draw's take, keeps the blunt refusal.

Counters: dispatch_effects=(kind=n,...) and exact_effects=(mode,refused,taken) in the prefetch line.
SHARPEMU_PREFETCH_EXACT_EFFECTS=0 restores the blunt rule. Not game-verified.
…the ownership check too

A draw's take over dispatches refused on every dispatch effect. For a kernel fill or copy the host logs as a GPU
write it now makes the same check a dispatch's take makes (IsStillCurrentAcrossDispatches), which refuses the draw
only when the write covers what its resolution read. Demon's Souls: about 9 more draws a frame taken; a verify run
(SHARPEMU_PREFETCH_DRAW_LOOKAHEAD=verify) re-resolved 7,875 such draws without a difference.

exact_effects= gains draws, draw_refused and draw_taken. SHARPEMU_PREFETCH_EXACT_EFFECTS=dispatch keeps the old
rule for draws only.
…ive fault

SHARPEMU_FAULT_DUMP=label=expr:len[,...] (expr: register, hex, [expr] qword load,
joined by + or -) prints windows the fixed register dumps cannot reach, such as a
caller's locals or a structure two pointers away. SHARPEMU_FAULT_DUMP_REPEAT_MS
dumps them again after a delay, so bytes another thread is still writing show up
as a difference. Off unless set; used to trace the Demon's Souls load SIGSEGV.
…t claimed after the release

A waiting thread read the guard as pending, the owner then released (complete written, claim dropped), and the
waiter's claim succeeded: it wrote pending over complete and returned 1, so a function-local static was
constructed a second time under the threads already using it. The guard is read again under the claim; a release
writes it complete before dropping its own, so that read sees it and the caller gets 0.

Found while tracing the Demon's Souls load crash; not shown to be its cause.
SHARPEMU_GPU_WRITE_RING=1 keeps the last 1 Mi writes of 16 bytes or more the
host makes or encodes into guest memory for the GPU: every image texel piece
EncodeTextureToGuest writes back (with the image's address, format, extent, tile
mode, levels and piece), every store, fill, copy and writeback declared through
NoteGuestMemoryWrite (with the transfer label or the draw/dispatch), and the
host-side fills and copies. The fault dump's windows are looked up locally and
handed to the GPU host through $TMPDIR/sharpemu-fault-ranges-<pid>.txt, which
prints the intersecting entries once it sees the guest process gone. Transfer
labels also carry the image's guest address. Diagnostic only, off by default;
for the Demon's Souls load crash, where 1 KiB of RGBA8 texels landed in a
freshly copied animation file.
…= byte search

SHARPEMU_HLE_WRITE_RING=1 records file reads into guest memory (AMPR, read,
pread/readv) with the file and offset, and the libc memcpy/memmove import with its
source, into the write ring the fault dump prints. SHARPEMU_FAULT_ALIASES=1 prints
the backing bytes each dumped window maps and every other guest range mapping them;
a SHARPEMU_FAULT_DUMP label starting with find searches mapped backing bytes for the
window's bytes and names every guest address holding them.
… around a read

The write ring records the backing offset an address mapped to when it was
written, so a fault's ranges are looked up by backing as well as by address in
both processes, and a recorded copy into a range adds its source to the search.
SHARPEMU_FAULT_DUMP labels starting with save write the bytes to
SHARPEMU_FAULT_SAVE_DIR; find labels add the other holders of the bytes to the
ranges. SHARPEMU_FAULT_RING_PRODUCER adds the ranges of writes whose producer
contains a text (a file name), SHARPEMU_WRITE_RING_TAIL prints the newest
records, and SHARPEMU_HLE_WRITE_RING_MIN keeps the HLE ring to large writes,
since recording every small copy hid the race it was built to find.

An AMPR read records its begin, and the 16 bytes at +0x20000 of its destination
as the fill starts and ends. In Demon's Souls that showed a render target's
texels already under the file's bytes when the read finished.

The switches are documented in docs/macos/configuration.md.
…ed the cache

A managed (HLE) write never faults, so before it lands it asks the image cache
whether a recorded writeback is still storing into its bytes, then takes the
cache lock and has every GPU-written image under it written back first. A
writeback another store had the worker record between the two was neither: not
fenced yet when the write asked, and no longer a GPU-written image once the
write held the lock. The write returned without waiting and the writeback
landed over it.

Demon's Souls crashed in about one boot in thirteen this way (SIGSEGV in
hkRootLevelContainer::findObjectByType with a null container). It reads
c0000_a2x.anibnd into memory a 2048x2048 render target still claims while
another guest store into that target has its writeback being recorded; the
read's notification returned with the writeback's submission not yet
committed, the target's small mips landed over the first 1 MiB of the file
during the read, and Havok's in-place load of the animation data failed.

The write now asks about fenced writebacks again once the cache has been read.
A writeback is fenced inside the hold of the lock that records it and before
its image leaves the page owners, so the second question sees it on either
exit. A faulting store needs none: the fence keeps its page watched and the
retried store asks again.

With SHARPEMU_GPU_WRITE_RING=1 the cache also records what a managed write
found: the bytes at +0x20000 of it as it enters and returns, the completed
submission, and the submission it waited for.
Copilot AI balanced review requested due to automatic review settings November 17, 2026 12:51

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

An organization owner can choose the repository organization as the billing source for reviews requested by members with a paid Copilot license. Learn about Copilot code review billing.

Ten workers that entered and backed out in a tight loop after the flag was set left
a three-core CI runner no instant at which every cell read zero, and the drainer timed
out (run 44087141754). The backing's admission checks the flag before it counts, so
the test now does the same; an entrant that raced the flag still backs out.
@github-actions

Copy link
Copy Markdown

📦 Build artifacts — 1114a71

Platform Download
macOS (osx-x64) sharpemu-osx-x64-2e5b8ca
macOS app bundle (osx-x64) sharpemu-osx-x64-app-2e5b8ca

From build run #450. Downloads require a GitHub login and expire after 90 days.

@xnetcat
xnetcat merged commit c868e46 into main Nov 19, 2026
8 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants