diff --git a/dm/games/0400486024DEC000/README.md b/dm/games/0400486024DEC000/README.md index c231e3429d..2cf070ebe5 100644 --- a/dm/games/0400486024DEC000/README.md +++ b/dm/games/0400486024DEC000/README.md @@ -105,6 +105,7 @@ From an empty save: at about 45 s `A` (title), `A` (New Game), then the movie. F - [Freeing a memory pool during a texture ID walk](../../../docs/reference/nvn-objects.md#freeing-a-memory-pool-during-a-texture-id-walk): the `-[NvPkg buffer]: unrecognized selector` crash after a save or a scene change. - [HMMA chains keep their matrices in the SIMD-group](../../../docs/reference/shaders.md#hmma-chains-keep-their-matrices-in-the-simd-group): the NDVE movie networks behind the title and the opening, 14.8 → 11.4 ms of compute a frame on this M6. - [Raw global memory lookups that start from their last entry](../../../docs/reference/shaders.md#raw-global-memory-lookups-that-start-from-their-last-entry): the foliage, vertex and compute shaders read structures word by word through loaded addresses; about 2 ms less GPU a frame at the spawn point. +- [Raw global memory loads through one pointer that resolve its pool once](../../../docs/reference/shaders.md#raw-global-memory-loads-through-one-pointer-that-resolve-its-pool-once): the 11 colour-pass mesh shaders read each vertex's attributes word by word through 5 pointers, 253 to 506 lookups a thread; the pass that draws them was 5.8 ms of geometry and 0.2 ms of pixels at 683x384 (M3 Max). - [The GPU idles with the next command buffer already committed](../../../docs/reference/frame-rate.md#the-gpu-idles-with-the-next-command-buffer-already-committed): the 25-40 ms frames. - [The 30 Hz display link in fullscreen on a fixed-rate screen](../../../docs/reference/frame-rate.md#the-30-hz-display-link-in-fullscreen-on-a-fixed-rate-screen): 66.7 ms frames at a 30 fps cap in fullscreen on a MacBook Air M4, with the frame-delta change that applies the cap. - [Pool tables and readback buffers made anew each frame](../../../docs/reference/memory.md#pool-tables-and-readback-buffers-made-anew-each-frame): about 1,500 residency changes per 300 frames. diff --git a/dm/gfx/nvn/dmsh_chain.h b/dm/gfx/nvn/dmsh_chain.h index ac55b8992b..2a7a4baf2c 100644 --- a/dm/gfx/nvn/dmsh_chain.h +++ b/dm/gfx/nvn/dmsh_chain.h @@ -1,3 +1,3 @@ // Generated file (dm/gfx/tools/dmsh_chain.py --header): the B shader library translation chain version this source tree expects (default options), one for every game; // the host loads only /b-/. Run dmsh_chain.py --header after changing the chain's tools and commit this file with the change -#define DMSH_CHAIN "094f939bfef9" +#define DMSH_CHAIN "723dc3a3e17d" diff --git a/dm/gfx/tests/test_dmsh_raw_run.py b/dm/gfx/tests/test_dmsh_raw_run.py new file mode 100644 index 0000000000..65f3c324ee --- /dev/null +++ b/dm/gfx/tests/test_dmsh_raw_run.py @@ -0,0 +1,119 @@ +#!/usr/bin/env python3 +"""Raw global memory loads through one pointer at constant offsets resolve its pool once (GlobalToStorage.ResolveRawRuns): through the offline translator (dmsh_xlate, arch sm86), a compute +shader's three loads at +0, +4 and +12 through an address it cannot trace (the thread index, as Ocarina of Time's colour-pass mesh shaders read a structure through a pointer they loaded) +call the range helper once, before the loads, for [base, base + 16) (it tries the entry it chose last first), and each load calls the resolved helper with that entry and its delta instead of the per-access lookup; and on this +Mac's GPU the two translated helpers read what the pool table names: a run inside a pool takes its entry (also above 4 GiB, through the hint), a run across two adjacent pools, one that +leaves a pool for a gap, one in a gap and one at address 0 take entry 0 and still read each word through the full lookup. +Needs DMSH_TEST_XLATE (the translator) like the other translator tests.""" +import os +from pathlib import Path +import re +import shutil +import subprocess +import sys +import tempfile +import unittest + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from test_dmsh_ampere_mem import EXIT, Translated, inst # noqa: E402 +from test_dmsh_ampere_alu import STORE, waiting, s2r_tid # noqa: E402 +from test_dmsh_raw_last import LDG, MAC_METAL # noqa: E402 + +LDG_R5 = (LDG[0], (LDG[1] & ~(0x3f << 32)) | 0x3f << 32) # LDG.E R6, [R5]: the uniform register is URZ, so the address is R5 (the thread index) alone, a 32-bit register +OFFSETS = (0, 4, 12) +RESOLVE = re.compile(r'(?m)^int (_\d+)\((?:thread const int& _\d+, ){4}const device (_\d+)& \w+, thread uint& _\d+\)\n\{\n') +RESOLVED = re.compile(r'(?m)^int (_\d+)\((?:thread const int& _\d+, ){5}const device _\d+& \w+, thread uint& _\d+\)\n\{\n') + +# The pool table as in test_dmsh_raw_last (nvn_mtl.m gmem_map, dmsh_abi.h DMSH_GMEM_MAP_*): pools A and B adjacent (entries 1 and 2), C past a gap and above 4 GiB (entry 3) with a hint +# for its 2 MiB chunk. Each lane resolves [base, base + 16) and loads +0, +4 and +12: inside A, across A's end into B, inside C, across C's end into the gap, in the gap, at address 0 +RUNNER = '''#import +#include +#include +enum { POOLS = 3, WORDS = 1024, LANES = 64, CASES = 6, OUTS = 4 }; +static const uint64_t GUEST[POOLS] = {0x10000000ull, 0x10001000ull, 0x200040000ull}; +static const int OFF[3] = {0, 4, 12}; +static uint32_t value(int p, uint64_t off) { return (uint32_t)(p + 1) << 24 | (uint32_t)(off / 4); } +static int expect(uint64_t a) { for (int p = 0; p < POOLS; p++) if (a >= GUEST[p] && a < GUEST[p] + WORDS * 4) return (int)value(p, a - GUEST[p]); return 0; } +static int entry(uint64_t s, uint64_t e) { for (int p = 0; p < POOLS; p++) if (s >= GUEST[p] && e <= GUEST[p] + WORDS * 4) return p + 1; return 0; } +int main(int ac, char **av) { @autoreleasepool { + id d = MTLCreateSystemDefaultDevice(); NSError *e = nil; + id l = [d newLibraryWithURL:[NSURL fileURLWithPath:@(av[1])] error:&e]; if (!l) { puts(e.description.UTF8String); return 2; } + id ps = [d newComputePipelineStateWithFunction:[l newFunctionWithName:@"k"] error:&e]; if (!ps) { puts(e.description.UTF8String); return 2; } + id pool[POOLS], map = [d newBufferWithLength:8192 * 32 options:MTLResourceStorageModeShared]; + uint32_t *t = map.contents; memset(t, 0, 8192 * 32); for (int k = 1; k < 8192; k++) memset(t + k * 8, 0xff, 8); + for (int p = 0; p < POOLS; p++) { + pool[p] = [d newBufferWithLength:WORDS * 4 options:MTLResourceStorageModeShared]; uint32_t *w = pool[p].contents; for (int i = 0; i < WORDS; i++) w[i] = value(p, i * 4); + uint64_t s = GUEST[p], end = s + WORDS * 4, delta = pool[p].gpuAddress - s, *ent = (uint64_t *)(t + (p + 1) * 8); ent[0] = s; ent[1] = end; ent[2] = delta; + } + uint32_t chunk = (uint32_t)(GUEST[2] >> 32) << 11 | (uint32_t)GUEST[2] >> 21; t[(chunk & 8191) * 8 + 6] = 3 | chunk << 13; // C's chunk: entry 3 + id base = [d newBufferWithLength:LANES * CASES * 8 options:MTLResourceStorageModeShared], out = [d newBufferWithLength:LANES * CASES * OUTS * 4 options:MTLResourceStorageModeShared]; + uint64_t *b = base.contents; int want[LANES * CASES * OUTS]; + for (int lane = 0; lane < LANES; lane++) { + uint64_t in = (uint64_t)(lane * 8) % (WORDS * 4 - 64); + uint64_t cs[CASES] = {GUEST[0] + in, GUEST[1] - 8, GUEST[2] + in, GUEST[2] + WORDS * 4 - 8, 0x10002000ull + in, 0}; + for (int c = 0; c < CASES; c++) { + int i = lane * CASES + c; b[i] = cs[c]; want[i * OUTS] = entry(cs[c], cs[c] + 16); + for (int k = 0; k < 3; k++) want[i * OUTS + 1 + k] = expect(cs[c] + OFF[k]); + } + } + id q = [d newCommandQueue]; id c = [q commandBuffer]; id ce = [c computeCommandEncoder]; + [ce setComputePipelineState:ps]; [ce setBuffer:map offset:0 atIndex:0]; [ce setBuffer:base offset:0 atIndex:1]; [ce setBuffer:out offset:0 atIndex:2]; + for (int p = 0; p < POOLS; p++) [ce useResource:pool[p] usage:MTLResourceUsageRead]; + [ce dispatchThreads:MTLSizeMake(LANES, 1, 1) threadsPerThreadgroup:MTLSizeMake(32, 1, 1)]; [ce endEncoding]; [c commit]; [c waitUntilCompleted]; + const int *got = out.contents; int bad = 0; + for (int i = 0; i < LANES * CASES * OUTS; i++) if (got[i] != want[i]) { if (bad++ < 8) printf("lane %d case %d out %d: base 0x%llx got 0x%x, want 0x%x\\n", i / OUTS / CASES, i / OUTS % CASES, i % OUTS, b[i / OUTS], got[i], want[i]); } + printf("bad %d of %d\\n", bad, LANES * CASES * OUTS); return 0; +} } +''' + + +@unittest.skipUnless(os.environ.get('DMSH_TEST_XLATE'), 'set DMSH_TEST_XLATE to the offline translator') +class RawRun(Translated): + def msl(self): + code = (s2r_tid(9), s2r_tid(5)) + sum((((LDG_R5[0], LDG_R5[1] | o << 40), STORE) for o in OFFSETS), ()) # each load kept by a store to shared memory + return self.translate(b''.join(inst(*waiting(i)) for i in code) + inst(*EXIT), shared=0x1000) + + def test_one_resolve_before_the_runs_loads(self): + msl = self.msl() + r, h = RESOLVE.search(msl), RESOLVED.search(msl) + self.assertTrue(r and h, msl[:4000]) + main = msl[msl.index('kernel void main0'):] + calls = re.findall(r'(?m)^ *int (_\d+) = ' + r.group(1) + r'\(([^;]*)\);$', main) + self.assertEqual(len(calls), 1, main[:3000]) + entry = calls[0][0] + loads = [m.start() for m in re.finditer(h.group(1) + r'\(', main)] + self.assertEqual(len(loads), len(OFFSETS), main[:3000]) + self.assertLess(main.index(r.group(1) + '('), loads[0]) # the resolve comes before the first load + self.assertEqual(len(re.findall(r'(?m)^int _\d+\(thread const int& _\d+, thread const int& _\d+, const device', msl)), 0) # no per-access helper is left + names = [entry] + re.findall(r'(?m)^ *int (_\d+) = ' + entry + ';$', main) # the entry, or a copy of it + self.assertEqual(len(re.findall(r'(?m)^ *int _\d+ = (?:' + '|'.join(names) + r') \* 8;$', main)), 1, main[:2000]) # the entry's delta, read once + + @unittest.skipUnless(shutil.which('xcrun') and sys.platform == 'darwin', 'needs Metal') + def test_reads_on_gpu(self): + msl = self.msl() + r, h = RESOLVE.search(msl), RESOLVED.search(msl) + n = 6 + body = ''.join(f' {{ uint a = b.x + {o}u; int alo = int(a), ahi = hi + (a < b.x ? 1 : 0); out[(i * {n} + s) * 4 + {k + 1}] = {h.group(1)}(alo, ahi, e, dlo, dhi, map, last); }}\n' + for k, o in enumerate(OFFSETS)) + kernel = (msl[:msl.index('kernel void main0')] + + f'kernel void k(const device {r.group(2)}& map [[buffer(0)]], const device uint2* base [[buffer(1)]], device int* out [[buffer(2)]], uint i [[thread_position_in_grid]])\n' + '{\n uint last = 0u, chosen = 0u;\n' + f' for (int s = 0; s < {n}; s++)\n {{\n uint2 b = base[i * {n} + s]; int lo = int(b.x), hi = int(b.y);\n' + ' uint en = b.x + 16u; int elo = int(en), ehi = hi + (en < b.x ? 1 : 0);\n' + f' int e = {r.group(1)}(lo, hi, elo, ehi, map, chosen);\n' + ' int dlo = int(map._m0[e * 8 + 4]), dhi = int(map._m0[e * 8 + 5]);\n' + f' out[(i * {n} + s) * 4] = e;\n' + body + ' }\n}\n') + with tempfile.TemporaryDirectory() as w: + w = Path(w) + (w / 'k.metal').write_text(kernel) + c = subprocess.run(MAC_METAL + [str(w / 'k.metal'), '-o', str(w / 'k.air')], capture_output=True, text=True) + self.assertEqual(c.returncode, 0, c.stderr[-3000:]) + subprocess.run(['xcrun', '-sdk', 'macosx', 'metallib', str(w / 'k.air'), '-o', str(w / 'k.metallib')], check=True) + (w / 'r.m').write_text(RUNNER) + subprocess.run(['clang', '-fobjc-arc', '-framework', 'Metal', '-framework', 'Foundation', str(w / 'r.m'), '-o', str(w / 'r')], check=True, capture_output=True) + out = subprocess.run([str(w / 'r'), str(w / 'k.metallib')], capture_output=True, text=True) + self.assertIn('bad 0 of 1536', out.stdout, out.stdout + out.stderr) + + +if __name__ == '__main__': + unittest.main() diff --git a/dm/gfx/tools/dmsh_chain.lock b/dm/gfx/tools/dmsh_chain.lock index 03b17ca200..c3a7d298d2 100644 --- a/dm/gfx/tools/dmsh_chain.lock +++ b/dm/gfx/tools/dmsh_chain.lock @@ -1,7 +1,7 @@ # Translation chain tool fingerprints (written by tool_lock.py --update-lock; regenerate after changing tools and commit it) -dmsh_xlate.dll 0c4a312520b5aa7f -Ryujinx.Graphics.Shader.dll 63adda80b4b3bd6e -Ryujinx.Common.dll eea41bd3312d4f2a +dmsh_xlate.dll 645696007366c5c4 +Ryujinx.Graphics.Shader.dll 7eafb3b31c8ddae4 +Ryujinx.Common.dll b258ba4054871372 xlate_source 0bd66426675438a9 spirv-cross e37945d8e441d34d metal_macosx Apple metal version 32023.922 (metalfe-32023.922.4) diff --git a/dm/gfx/tools/dmsh_xlate_bin/Ryujinx.Common.dll b/dm/gfx/tools/dmsh_xlate_bin/Ryujinx.Common.dll index 52c0d4095d..dee0c910b6 100644 Binary files a/dm/gfx/tools/dmsh_xlate_bin/Ryujinx.Common.dll and b/dm/gfx/tools/dmsh_xlate_bin/Ryujinx.Common.dll differ diff --git a/dm/gfx/tools/dmsh_xlate_bin/Ryujinx.Graphics.Shader.dll b/dm/gfx/tools/dmsh_xlate_bin/Ryujinx.Graphics.Shader.dll index 95bca2ee08..204aa87508 100644 Binary files a/dm/gfx/tools/dmsh_xlate_bin/Ryujinx.Graphics.Shader.dll and b/dm/gfx/tools/dmsh_xlate_bin/Ryujinx.Graphics.Shader.dll differ diff --git a/dm/gfx/tools/dmsh_xlate_bin/Spv.Generator.dll b/dm/gfx/tools/dmsh_xlate_bin/Spv.Generator.dll index a39ea231d2..decf302bc7 100644 Binary files a/dm/gfx/tools/dmsh_xlate_bin/Spv.Generator.dll and b/dm/gfx/tools/dmsh_xlate_bin/Spv.Generator.dll differ diff --git a/dm/gfx/tools/dmsh_xlate_bin/dmsh_xlate.dll b/dm/gfx/tools/dmsh_xlate_bin/dmsh_xlate.dll index 1917c7ade4..2aa30b5477 100644 Binary files a/dm/gfx/tools/dmsh_xlate_bin/dmsh_xlate.dll and b/dm/gfx/tools/dmsh_xlate_bin/dmsh_xlate.dll differ diff --git a/dm/gfx/tools/dmsh_xlate_bin/dmsh_xlate.pdb b/dm/gfx/tools/dmsh_xlate_bin/dmsh_xlate.pdb index e5704526de..08a7dcda54 100644 Binary files a/dm/gfx/tools/dmsh_xlate_bin/dmsh_xlate.pdb and b/dm/gfx/tools/dmsh_xlate_bin/dmsh_xlate.pdb differ diff --git a/dm/third_party/ryujinx/src/Ryujinx.Graphics.Shader/Translation/Optimizations/GlobalToStorage.cs b/dm/third_party/ryujinx/src/Ryujinx.Graphics.Shader/Translation/Optimizations/GlobalToStorage.cs index 887753680e..878db73152 100644 --- a/dm/third_party/ryujinx/src/Ryujinx.Graphics.Shader/Translation/Optimizations/GlobalToStorage.cs +++ b/dm/third_party/ryujinx/src/Ryujinx.Graphics.Shader/Translation/Optimizations/GlobalToStorage.cs @@ -75,6 +75,17 @@ public bool Equals(LsKey other) private readonly Dictionary> _sharedEntries; private readonly HelperFunctionManager _hfm; + // nxnative: the raw global memory load helpers (TryGenerateRawStorageOp) by function id, their variants that take a pool resolved once for a run of loads + // (ResolveRawRuns), and the helper that resolves a run's range + public readonly Dictionary RawLoadFunctions = new(); + public readonly Dictionary ResolvedLoadFunctions = new(); + public int ResolveRangeFunction = -1; + + public int AddHelper(Function function) + { + return _hfm.AddFunction(function); + } + public GtsContext(HelperFunctionManager hfm) { _entries = []; @@ -277,6 +288,8 @@ public static void RunPass( } } } + + ResolveRawRuns(gtsContext, resourceManager, gpuAccessor, blocks); } private static bool IsGlobalMemory(StorageKind storageKind) @@ -801,7 +814,8 @@ private static bool TryGenerateRawStorageOp( ResourceManager resourceManager, IGpuAccessor gpuAccessor, Operation operation, - out int functionId) + out int functionId, + bool resolved = false) { functionId = 0; @@ -839,6 +853,11 @@ private static bool TryGenerateRawStorageOp( inArgumentsCount = 3; } + if (resolved) + { + inArgumentsCount = 5; // the address, then the run's entry (0: none holds the whole run) and its delta (ResolveRawRuns) + } + EmitterContext context = new(); Operand addrLow = Argument(0); @@ -863,6 +882,15 @@ Operand Below(Operand high, Operand low) // the address is below {low, high} context.BitwiseAnd(context.ICompareEqual(addrHigh, high), context.ICompareLessUnsigned(addrLow, low))); } + // A load of a run whose pool was resolved once (ResolveRawRuns) moves by that pool's delta; a run no single entry holds takes the lookup below + if (resolved) + { + Operand lblLookup = Label(); + context.BranchIfFalse(lblLookup, context.ICompareNotEqual(Argument(2), Const(0))); + EmitAccess(Argument(3), Argument(4)); + context.MarkLabel(lblLookup); + } + Operand selected = Local(); Operand lblFound = Label(); Operand lblChosen = Label(); @@ -889,14 +917,7 @@ Operand Below(Operand high, Operand low) // the address is below {low, high} context.BranchIfTrue(lblFound, hintFits); // The last entry whose start is at or below the address (entry 0 starts at 0, so there always is one) - Operand index = Const(0); - - for (int step = 1 << (GmemMapLog2 - 1); step != 0; step >>= 1) - { - Operand candidate = context.IAdd(index, Const(step)); - Operand entry = context.IMultiply(candidate, Const(GmemMapEntryWords)); - index = context.ConditionalSelect(AtOrBelow(MapWord(entry, 1), MapWord(entry, 0)), candidate, index); - } + Operand index = EmitTableSearch(context, entry => AtOrBelow(MapWord(entry, 1), MapWord(entry, 0))); context.Copy(selected, index); context.MarkLabel(lblFound); @@ -920,93 +941,621 @@ Operand Below(Operand high, Operand low) // the address is below {low, high} context.MarkLabel(lblLogged); } - // A small integer is read or written in its 32-bit word - Operand wordLow = isSmall ? context.BitwiseAnd(addrLow, Const(~3)) : addrLow; - Operand hostLow = context.IAdd(wordLow, MapWord(found, 4)); - Operand carry = context.ConditionalSelect(context.ICompareLessUnsigned(hostLow, wordLow), Const(1), Const(0)); - Operand hostHigh = context.IAdd(context.IAdd(addrHigh, MapWord(found, 5)), carry); + EmitAccess(MapWord(found, 4), MapWord(found, 5)); + + context.MarkLabel(lblSkip); + + bool returnsValue = operation.Dest != null; + + if (returnsValue) + { + context.Return(Const(0)); + } + else + { + context.Return(); + } + + Function function = new( + ControlFlowGraph.Create(context.GetOperations()).Blocks, + GetFunctionName(operation, isMultiTarget: true, []) + (resolved ? "RawResolved" : "Raw"), + returnsValue, + inArgumentsCount, + 0); + + if (resolved) + { + functionId = gtsContext.AddHelper(function); + gtsContext.ResolvedLoadFunctions[operation.StorageKind] = functionId; + } + else + { + functionId = gtsContext.AddFunction(operation, isMultiTarget: true, [], function); + + if (operation.Inst == Instruction.Load) + { + gtsContext.RawLoadFunctions[functionId] = operation.StorageKind; + } + } + + return true; + + // The access at the address moved by a pool's delta (its Metal GPU address minus its guest address), and its return + void EmitAccess(Operand deltaLow, Operand deltaHigh) + { + // A small integer is read or written in its 32-bit word + Operand wordLow = isSmall ? context.BitwiseAnd(addrLow, Const(~3)) : addrLow; + Operand hostLow = context.IAdd(wordLow, deltaLow); + Operand carry = context.ConditionalSelect(context.ICompareLessUnsigned(hostLow, wordLow), Const(1), Const(0)); + Operand hostHigh = context.IAdd(context.IAdd(addrHigh, deltaHigh), carry); + + Operand resultValue = null; + + if (operation.Inst == Instruction.Load) + { + resultValue = context.Load(StorageKind.GlobalMemory, hostLow, hostHigh); + + if (isSmall) + { + Operand bitOffset = HelperFunctionManager.GetBitOffset(context, addrLow); + + resultValue = operation.StorageKind switch + { + StorageKind.GlobalMemoryS8 => context.BitfieldExtractS32(context.ShiftRightS32(resultValue, bitOffset), Const(0), Const(8)), + StorageKind.GlobalMemoryS16 => context.BitfieldExtractS32(context.ShiftRightS32(resultValue, bitOffset), Const(0), Const(16)), + StorageKind.GlobalMemoryU8 => context.BitwiseAnd(context.ShiftRightU32(resultValue, bitOffset), Const(byte.MaxValue)), + _ => context.BitwiseAnd(context.ShiftRightU32(resultValue, bitOffset), Const(ushort.MaxValue)), + }; + } + } + else if (operation.Inst == Instruction.Store) + { + Operand value = Argument(2); + + if (isSmall) + { + int bitSize = operation.StorageKind is StorageKind.GlobalMemoryS8 or StorageKind.GlobalMemoryU8 ? 8 : 16; + Operand bitOffset = HelperFunctionManager.GetBitOffset(context, addrLow); + + Operand lblLoopHead = Label(); + context.MarkLabel(lblLoopHead); + + Operand oldValue = context.Load(StorageKind.GlobalMemory, hostLow, hostHigh); + Operand newValue = context.BitfieldInsert(oldValue, value, bitOffset, Const(bitSize)); + Operand casResult = context.AtomicCompareAndSwap(StorageKind.GlobalMemory, hostLow, hostHigh, oldValue, newValue); + + context.BranchIfTrue(lblLoopHead, context.ICompareNotEqual(casResult, oldValue)); + } + else + { + context.Store(StorageKind.GlobalMemory, hostLow, hostHigh, value); + } + } + else if (operation.Inst == Instruction.AtomicCompareAndSwap) + { + resultValue = context.AtomicCompareAndSwap(StorageKind.GlobalMemory, hostLow, hostHigh, Argument(2), Argument(3)); + } + else + { + resultValue = context.Add(operation.Inst, StorageKind.GlobalMemory, Local(), hostLow, hostHigh, Argument(2)); + } + + if (resultValue != null) + { + context.Return(resultValue); + } + else + { + context.Return(); + } + } + } + + // nxnative: the binary search of the pool table as a loop of GmemMapLog2 steps: the last entry whose start passes startAtOrBelow (given an entry's first word). The search runs only + // when the last entry and the hint both missed, but unrolled it was 13 copies of the step at every call site once Metal inlines the helpers: Ocarina of Time's compute shaders + // 77e64b1d8200eac3 and d8abf8a34811f8c6 took 2.3 to 2.6 s each to become pipelines, and the 8 that its foliage's reaction to a sword needs froze the game for 11 s the first time + private static Operand EmitTableSearch(EmitterContext context, Func startAtOrBelow) + { + Operand index = Local(); + Operand step = Local(); + Operand lblStep = Label(); + + context.Copy(index, Const(0)); + context.Copy(step, Const(1 << (GmemMapLog2 - 1))); + context.MarkLabel(lblStep); - Operand resultValue = null; + Operand candidate = context.IAdd(index, step); + context.Copy(index, context.ConditionalSelect(startAtOrBelow(context.IMultiply(candidate, Const(GmemMapEntryWords))), candidate, index)); + context.Copy(step, context.ShiftRightU32(step, Const(1))); + context.BranchIfTrue(lblStep, context.ICompareNotEqual(step, Const(0))); - if (operation.Inst == Instruction.Load) + return index; + } + + // nxnative: loads through one untraced pointer at constant offsets resolve its pool once. A shader that reads a structure word after word through a pointer it loaded (Ocarina of Time's + // colour-pass mesh shaders, 253 to 506 raw loads each, a pointer from a fixed word of a storage buffer and offsets +0, +4, +8 ...) paid each word the last-entry check, 4 table reads, and the + // delta's 2 more: about 7 memory reads per word of data, and nearly all of the 683x384 colour pass's 5.8 ms of mesh work. Here the loads of one base {low, high} (SSA values) at + // offsets c >= 0, as the decoder builds them (low = base low + c, high = base high + the carry of that add), are a run: at the nearest block that dominates all of them, one call looks up + // the entry holding the run's whole range [base + min c, base + max c + 4) and reads its delta, and each load moves by that delta. A run no single entry holds (it spans two pools, or an + // address in none, or a guard that leaves the pointer invalid) gives entry 0, and each of its loads takes the full lookup as before. The resolve only reads the table, so running it + // where a guarded load would not run is harmless. Stores and atomics keep the per-access path: the write log is per entry + private const int RawRunMinLoads = 2; + private const int RawRunMaxOffset = 1 << 24; + + private readonly struct RawRunAccess + { + public readonly LinkedListNode Node; + public readonly BasicBlock Block; + public readonly Operand BaseLow; + public readonly Operand BaseHigh; + public readonly int Offset; + + public RawRunAccess(LinkedListNode node, BasicBlock block, Operand baseLow, Operand baseHigh, int offset) + { + Node = node; + Block = block; + BaseLow = baseLow; + BaseHigh = baseHigh; + Offset = offset; + } + } + + private static void ResolveRawRuns(GtsContext gtsContext, ResourceManager resourceManager, IGpuAccessor gpuAccessor, BasicBlock[] blocks) + { + if (gtsContext.RawLoadFunctions.Count == 0) { - resultValue = context.Load(StorageKind.GlobalMemory, hostLow, hostHigh); + return; + } + + // The runs in program order (first load first), keyed by the base's value (RawValueKey: the same SSA values, or the same pure operations of them), and where each node is + Dictionary> runs = new(); + List order = []; + Dictionary blockOf = new(); + Dictionary keys = new(); - if (isSmall) + foreach (BasicBlock block in blocks) + { + for (LinkedListNode node = block.Operations.First; node != null; node = node.Next) { - Operand bitOffset = HelperFunctionManager.GetBitOffset(context, addrLow); + blockOf[node.Value] = block; + + if (node.Value is not Operation call || + call.Inst != Instruction.Call || + call.SourcesCount != 3 || + call.Dest == null || + call.GetSource(0).Type != OperandType.Constant || + !gtsContext.RawLoadFunctions.ContainsKey(call.GetSource(0).Value)) + { + continue; + } - resultValue = operation.StorageKind switch + if (!TryGetRawBase(call.GetSource(1), call.GetSource(2), out Operand baseLow, out Operand baseHigh, out int offset)) { - StorageKind.GlobalMemoryS8 => context.BitfieldExtractS32(context.ShiftRightS32(resultValue, bitOffset), Const(0), Const(8)), - StorageKind.GlobalMemoryS16 => context.BitfieldExtractS32(context.ShiftRightS32(resultValue, bitOffset), Const(0), Const(16)), - StorageKind.GlobalMemoryU8 => context.BitwiseAnd(context.ShiftRightU32(resultValue, bitOffset), Const(byte.MaxValue)), - _ => context.BitwiseAnd(context.ShiftRightU32(resultValue, bitOffset), Const(ushort.MaxValue)), - }; + continue; + } + + string key = RawValueKey(baseLow, keys, RawKeyDepth) + "|" + RawValueKey(baseHigh, keys, RawKeyDepth); + + if (!runs.TryGetValue(key, out List run)) + { + runs.Add(key, run = []); + order.Add(key); + } + + run.Add(new RawRunAccess(node, block, baseLow, baseHigh, offset)); } } - else if (operation.Inst == Instruction.Store) + + int mapBinding = -1; + + foreach (string key in order) { - Operand value = Argument(2); + List run = runs[key]; - if (isSmall) + if (run.Count < RawRunMinLoads) { - int bitSize = operation.StorageKind is StorageKind.GlobalMemoryS8 or StorageKind.GlobalMemoryU8 ? 8 : 16; - Operand bitOffset = HelperFunctionManager.GetBitOffset(context, addrLow); + continue; + } - Operand lblLoopHead = Label(); - context.MarkLabel(lblLoopHead); + // The nearest block that dominates every load of the run + BasicBlock at = run[0].Block; + + foreach (RawRunAccess access in run) + { + at = NearestCommonDominator(at, access.Block); - Operand oldValue = context.Load(StorageKind.GlobalMemory, hostLow, hostHigh); - Operand newValue = context.BitfieldInsert(oldValue, value, bitOffset, Const(bitSize)); - Operand casResult = context.AtomicCompareAndSwap(StorageKind.GlobalMemory, hostLow, hostHigh, oldValue, newValue); + if (at == null) + { + break; + } + } - context.BranchIfTrue(lblLoopHead, context.ICompareNotEqual(casResult, oldValue)); + if (at == null) + { + continue; } - else + + if (mapBinding < 0) + { + if (!resourceManager.TryGetStorageBufferBinding(GmemMapCbSlot, 0, write: false, out mapBinding) || + !TryGetResolveRangeFunction(gtsContext, resourceManager, out _)) + { + return; + } + } + + int min = int.MaxValue, end = 0; + + foreach (RawRunAccess access in run) + { + min = Math.Min(min, access.Offset); + end = Math.Max(end, access.Offset + 4); + } + + // Before the run's first load in that block, else at its end (before its branch) + LinkedListNode before = null; + + foreach (RawRunAccess access in run) + { + if (access.Block == at) + { + before = access.Node; + break; + } + } + + // A load's base whose value is defined there: one SSA value dominates all its uses, but loads that compute the same value each on their own may not + Operand baseLow = null, baseHigh = null; + + foreach (RawRunAccess access in run) + { + if (IsAvailableAt(access.BaseLow, at, before, blockOf) && IsAvailableAt(access.BaseHigh, at, before, blockOf)) + { + (baseLow, baseHigh) = (access.BaseLow, access.BaseHigh); + break; + } + } + + if (baseLow == null) + { + continue; + } + + EmitterContext context = new(); + + (Operand minLow, Operand minHigh) = AddOffset64(context, baseLow, baseHigh, min); + (Operand endLow, Operand endHigh) = AddOffset64(context, baseLow, baseHigh, end); + Operand entry = context.Call(gtsContext.ResolveRangeFunction, true, minLow, minHigh, endLow, endHigh); + Operand entryWord = context.IMultiply(entry, Const(GmemMapEntryWords)); + Operand deltaLow = context.Load(StorageKind.StorageBuffer, mapBinding, Const(0), context.IAdd(entryWord, Const(4))); + Operand deltaHigh = context.Load(StorageKind.StorageBuffer, mapBinding, Const(0), context.IAdd(entryWord, Const(5))); + + foreach (Operation op in context.GetOperations()) + { + if (before != null) + { + at.Operations.AddBefore(before, op); + } + else + { + at.Append(op); + } + } + + foreach (RawRunAccess access in run) + { + Operation call = (Operation)access.Node.Value; + StorageKind kind = gtsContext.RawLoadFunctions[call.GetSource(0).Value]; + + if (!gtsContext.ResolvedLoadFunctions.TryGetValue(kind, out int resolvedId)) + { + Operation model = new(Instruction.Load, kind, Local(), Const(0), Const(0)); + + if (!TryGenerateRawStorageOp(gtsContext, resourceManager, gpuAccessor, model, out resolvedId, resolved: true)) + { + continue; + } + } + + call.SetSource(0, Const(resolvedId)); + call.AppendSources([entry, deltaLow, deltaHigh]); + } + } + } + + // The base and constant offset of a raw load's address, as the decoder builds an address plus an offset (InstEmitAmpereMem.AGlobalAddress, InstEmitMemory.Get40BitsAddress): + // low = base low + c, high = base high + (low < base low ? 1 : 0), or the carry alone for a base high of 0. An address that is no such sum is its own base at offset 0 + private static bool TryGetRawBase(Operand low, Operand high, out Operand baseLow, out Operand baseHigh, out int offset) + { + low = SkipCopies(low); + high = SkipCopies(high); + + if (low.AsgOp is Operation add && add.Inst == Instruction.Add && add.SourcesCount == 2) + { + for (int i = 0; i < 2; i++) { - context.Store(StorageKind.GlobalMemory, hostLow, hostHigh, value); + Operand c = add.GetSource(i), b = SkipCopies(add.GetSource(1 - i)); + + if (c.Type != OperandType.Constant || c.Value <= 0 || c.Value >= RawRunMaxOffset || b.Type != OperandType.LocalVariable) + { + continue; + } + + if (IsCarryOf(high, low, b)) // a high word of 0: the optimizer folded 0 + carry to the carry + { + baseLow = b; + baseHigh = Const(0); + offset = c.Value; + + return true; + } + + if (high.AsgOp is Operation addHigh && addHigh.Inst == Instruction.Add && addHigh.SourcesCount == 2) + { + for (int j = 0; j < 2; j++) + { + if (IsCarryOf(addHigh.GetSource(j), low, b)) + { + baseLow = b; + baseHigh = SkipCopies(addHigh.GetSource(1 - j)); + offset = c.Value; + + return baseHigh.Type is OperandType.LocalVariable or OperandType.Constant; + } + } + } } } - else if (operation.Inst == Instruction.AtomicCompareAndSwap) + + baseLow = low; + baseHigh = high; + offset = 0; + + return low.Type == OperandType.LocalVariable && high.Type is OperandType.LocalVariable or OperandType.Constant; + } + + // carry = (sum < base) ? 1 : 0 + private static bool IsCarryOf(Operand carry, Operand sum, Operand baseLow) + { + if (SkipCopies(carry).AsgOp is not Operation select || + select.Inst != Instruction.ConditionalSelect || + select.SourcesCount != 3 || + select.GetSource(1).Type != OperandType.Constant || select.GetSource(1).Value != 1 || + select.GetSource(2).Type != OperandType.Constant || select.GetSource(2).Value != 0) { - resultValue = context.AtomicCompareAndSwap(StorageKind.GlobalMemory, hostLow, hostHigh, Argument(2), Argument(3)); + return false; } - else + + return SkipCopies(select.GetSource(0)).AsgOp is Operation compare && + compare.Inst == Instruction.CompareLessU32 && + compare.SourcesCount == 2 && + SkipCopies(compare.GetSource(0)) == sum && + SkipCopies(compare.GetSource(1)) == baseLow; + } + + private const int RawKeyDepth = 6; + + // A key equal for two operands that hold the same value in an invocation: the same SSA value or constant, or the same pure integer operation of such values (a decoder computes + // a pointer plus a uniform register again for each instruction). Anything else, a memory load among them, is keyed by its own identity + private static string RawValueKey(Operand operand, Dictionary keys, int depth) + { + operand = SkipCopies(operand); + + if (operand.Type == OperandType.Constant) { - resultValue = context.Add(operation.Inst, StorageKind.GlobalMemory, Local(), hostLow, hostHigh, Argument(2)); + return "#" + operand.Value.ToString(System.Globalization.CultureInfo.InvariantCulture); } - if (resultValue != null) + if (keys.TryGetValue(operand, out string known)) { - context.Return(resultValue); + return known; + } + + string key; + + if (depth > 0 && operand.AsgOp is Operation op && op.Dest == operand && op.DestsCount == 1 && op.SourcesCount is >= 1 and <= 3 && IsPureInteger(op.Inst)) + { + string[] sources = new string[op.SourcesCount]; + + for (int i = 0; i < sources.Length; i++) + { + sources[i] = RawValueKey(op.GetSource(i), keys, depth - 1); + } + + if (op.Inst is Instruction.Add or Instruction.BitwiseAnd or Instruction.BitwiseOr or Instruction.BitwiseExclusiveOr or Instruction.CompareEqual or Instruction.CompareNotEqual) + { + Array.Sort(sources, StringComparer.Ordinal); + } + + key = op.Inst.ToString() + "(" + string.Join(",", sources) + ")"; } else { - context.Return(); + key = "v" + keys.Count.ToString(System.Globalization.CultureInfo.InvariantCulture); } - context.MarkLabel(lblSkip); + keys[operand] = key; - bool returnsValue = operation.Dest != null; + return key; + } - if (returnsValue) + private static bool IsPureInteger(Instruction inst) + { + return inst is Instruction.Add or Instruction.Subtract or Instruction.Multiply or Instruction.ConditionalSelect or + Instruction.CompareLessU32 or Instruction.CompareEqual or Instruction.CompareNotEqual or + Instruction.BitwiseAnd or Instruction.BitwiseOr or Instruction.BitwiseExclusiveOr or Instruction.BitwiseNot or + Instruction.ShiftLeft or Instruction.ShiftRightU32 or Instruction.ShiftRightS32; + } + + // The operand's value exists at the insertion point: before node in block, or at block's end when node is null + private static bool IsAvailableAt(Operand operand, BasicBlock block, LinkedListNode node, Dictionary blockOf) + { + if (operand.Type == OperandType.Constant) { - context.Return(Const(0)); + return true; } - else + + if (operand.Type != OperandType.LocalVariable || operand.AsgOp == null || !blockOf.TryGetValue(operand.AsgOp, out BasicBlock defBlock)) { - context.Return(); + return false; } - Function function = new( - ControlFlowGraph.Create(context.GetOperations()).Blocks, - GetFunctionName(operation, isMultiTarget: true, []) + "Raw", - returnsValue, - inArgumentsCount, - 0); + if (defBlock != block) + { + for (BasicBlock x = block.ImmediateDominator; x != null; x = x.ImmediateDominator == x ? null : x.ImmediateDominator) + { + if (x == defBlock) + { + return true; + } + } + + return false; + } + + if (node == null) + { + return true; + } + + for (LinkedListNode n = node.Previous; n != null; n = n.Previous) + { + if (n.Value == operand.AsgOp) + { + return true; + } + } + + return false; + } + + private static Operand SkipCopies(Operand operand) + { + while (operand.AsgOp is Operation copy && copy.Inst == Instruction.Copy && copy.SourcesCount == 1) + { + operand = copy.GetSource(0); + } + + return operand; + } + + private static (Operand, Operand) AddOffset64(EmitterContext context, Operand low, Operand high, int offset) + { + if (offset == 0) + { + return (low, high); + } + + Operand sum = context.IAdd(low, Const(offset)); + Operand carry = context.ConditionalSelect(context.ICompareLessUnsigned(sum, low), Const(1), Const(0)); + + return (sum, context.IAdd(high, carry)); + } + + private static BasicBlock NearestCommonDominator(BasicBlock a, BasicBlock b) + { + HashSet above = []; + + for (BasicBlock x = a; x != null; x = x.ImmediateDominator == x ? null : x.ImmediateDominator) + { + above.Add(x); + } + + for (BasicBlock y = b; y != null; y = y.ImmediateDominator == y ? null : y.ImmediateDominator) + { + if (above.Contains(y)) + { + return y; + } + } + + return null; + } + + // The entry of the pool table that holds a whole range [min, end): the entry this helper chose last in this invocation, else the hint of min's 2 MiB chunk, else the last entry + // starting at or below min, if that entry also reaches end; else 0. A shader that loads its pointers again in each guarded block resolves the same pointer many times + // (Ocarina of Time's colour-pass mesh shaders: 122 runs through 5 pointers), and all but the first take the remembered entry + private static bool TryGetResolveRangeFunction(GtsContext gtsContext, ResourceManager resourceManager, out int functionId) + { + functionId = gtsContext.ResolveRangeFunction; + + if (functionId >= 0) + { + return true; + } + + if (!resourceManager.TryGetStorageBufferBinding(GmemMapCbSlot, 0, write: false, out int mapBinding)) + { + return false; + } + + resourceManager.Properties.UsesPhysicalPointers = true; + + EmitterContext context = new(); + + Operand minLow = Argument(0); + Operand minHigh = Argument(1); + Operand endLow = Argument(2); + Operand endHigh = Argument(3); + + Operand MapWord(Operand entry, int word) + { + return context.Load(StorageKind.StorageBuffer, mapBinding, Const(0), context.IAdd(entry, Const(word))); + } + + Operand NotAbove(Operand aHigh, Operand aLow, Operand bHigh, Operand bLow) // {aLow, aHigh} <= {bLow, bHigh} + { + return context.BitwiseOr( + context.ICompareLessUnsigned(aHigh, bHigh), + context.BitwiseAnd(context.ICompareEqual(aHigh, bHigh), context.ICompareLessOrEqualUnsigned(aLow, bLow))); + } + + Operand Holds(Operand index) + { + Operand found = context.IMultiply(index, Const(GmemMapEntryWords)); + + return context.BitwiseAnd( + context.ICompareNotEqual(index, Const(0)), + context.BitwiseAnd( + NotAbove(MapWord(found, 1), MapWord(found, 0), minHigh, minLow), + NotAbove(endHigh, endLow, MapWord(found, 3), MapWord(found, 2)))); + } + + int lastBinding = resourceManager.AddRawLastEntryMemory(); + Operand last = context.Load(StorageKind.LocalMemory, lastBinding); + Operand lblMiss = Label(); + context.BranchIfFalse(lblMiss, Holds(last)); + context.Return(last); + context.MarkLabel(lblMiss); + + Operand selected = Local(); + Operand lblFound = Label(); + + Operand chunk = context.BitwiseOr(context.ShiftLeft(minHigh, Const(32 - GmemHintShift)), context.ShiftRightU32(minLow, Const(GmemHintShift))); + Operand indexMask = Const((1 << GmemMapLog2) - 1); + Operand hint = MapWord(context.IMultiply(context.BitwiseAnd(chunk, indexMask), Const(GmemMapEntryWords)), 6); + Operand hintIndex = context.BitwiseAnd(hint, indexMask); + Operand hintFits = context.BitwiseAnd( + context.BitwiseAnd(context.ICompareNotEqual(hintIndex, Const(0)), context.ICompareEqual(context.ShiftRightU32(hint, Const(GmemMapLog2)), chunk)), + context.ICompareLessUnsigned(minHigh, Const(1 << (GmemHintShift - GmemMapLog2)))); + context.Copy(selected, hintIndex); + context.BranchIfTrue(lblFound, hintFits); + + Operand index = EmitTableSearch(context, entry => NotAbove(MapWord(entry, 1), MapWord(entry, 0), minHigh, minLow)); + + context.Copy(selected, index); + context.MarkLabel(lblFound); + + Operand lblNone = Label(); + context.BranchIfFalse(lblNone, Holds(selected)); + context.Store(StorageKind.LocalMemory, lastBinding, selected); + context.Return(selected); + context.MarkLabel(lblNone); + context.Return(Const(0)); + + Function function = new(ControlFlowGraph.Create(context.GetOperations()).Blocks, "RawResolveRange", true, 4, 0); - functionId = gtsContext.AddFunction(operation, isMultiTarget: true, [], function); + functionId = gtsContext.ResolveRangeFunction = gtsContext.AddHelper(function); return true; } diff --git a/docs/agents/symptoms.md b/docs/agents/symptoms.md index cb1115f44f..3afa590695 100644 --- a/docs/agents/symptoms.md +++ b/docs/agents/symptoms.md @@ -950,6 +950,7 @@ One line per symptom in the [subsystem references](../reference/): what you see - a storage buffer reported with `cb_slot` 3, which had no NVN slot. → [Storage buffer addresses in the game's own uniform buffer](../reference/shaders.md#storage-buffer-addresses-in-the-games-own-uniform-buffer) - whatever a shader writes through a pointer it read from memory never happens. The build summary counted `Failed to find storage buffer for global memory operation "Store"`, and the shader's MSL had a store function with an empty body. In Donkey Kong Bananza the tunnel's walls and floor were black and only the loose rocks drew. → [Global memory at an address loaded from memory](../reference/shaders.md#global-memory-at-an-address-loaded-from-memory) - a pass whose shaders read memory through loaded addresses takes several milliseconds on the GPU for little work. `[gpuprof]` names the pass, and its shaders' build notes say `Global memory operation "Load" traced to no storage buffer`. Ocarina of Time's foliage mesh shader `73dc0b90c4082e43` (`Foliage.Product.110`, 135 such reads) took 10.9 ms of a 683x384 frame; 2,241 of the game's shaders (vertex, compute, fragment and mesh) have such a lookup, some hundreds of them. → [Raw global memory lookups that start from their last entry](../reference/shaders.md#raw-global-memory-lookups-that-start-from-their-last-entry) +- a pass of task or mesh draws takes milliseconds of GPU geometry time while its pixels are cheap: with `DM_NVN_GPUPROF_GEOM=1`, `gpuprof.py --timeline` shows nearly all of the pass before its `geometry` mark. The same draws in a depth pre-pass, whose mesh shaders read only the position, are a fraction of it. Their shaders' MSL calls the raw lookup helper hundreds of times, once per 32-bit word. → [Raw global memory loads through one pointer that resolve its pool once](../reference/shaders.md#raw-global-memory-loads-through-one-pointer-that-resolve-its-pool-once) - `no resolved slot number`, the shader does not load; the translation has a 32-entry texture-pool array (`fp_t2d_cb0_40000000`, handle type Direct). → [Bindless handles through a loop phi](../reference/shaders.md#bindless-handles-through-a-loop-phi) - none in the log: texture reads come back 0. Particle meshes collapse to a point (their scale reads 0), so effects are missing or show as dark patches. The translator's own message (`Failed to find handle source for bindless access of type "textureBuffer"`) used to be dropped, because `dmsh_xlate`'s accessor had no `Log`; its messages now go into the shader's notes, marked `translator: `, and the build summary counts them apart from unanswered queries. → [Bindless reads whose handle phi also carries other values](../reference/shaders.md#bindless-reads-whose-handle-phi-also-carries-other-values) - the shaders' bindless arrays have no slot and used not to load; the translator falls back to a 32-entry array such as `array, 32> vp_tb_cb0_40000000`. → [Texture slots picked at run time](../reference/shaders.md#texture-slots-picked-at-run-time) diff --git a/docs/reference/shaders.md b/docs/reference/shaders.md index 4ee14f11af..13a5beb1c6 100644 --- a/docs/reference/shaders.md +++ b/docs/reference/shaders.md @@ -1585,6 +1585,19 @@ Finding, keying and translating shaders (`dm/gfx/tools/shader_split.py`, `dmsh_b - **Open:** over the walk the frame time p95 went 19 → 26 ms. The runs ended in different places (the route is timed and the game moves at its frame rate), the new side's render target loads were higher (the game's dynamic resolution taking the headroom), and the Mac had 8 GB of swap in use, so this is not settled. Keeping the range itself in registers (PR #1464's form, no table reads on a hit) has not been compared on the same Mac. - **Found on:** [The Legend of Zelda: Ocarina of Time](../../dm/games/0400486024DEC000/README.md); the diagnosis, the cache and the first measurements in [PR 1464](https://github.com/seedds/nxnative/pull/1464) and [PR 1405](https://github.com/seedds/nxnative/pull/1405#issuecomment-6678379920). +### Raw global memory loads through one pointer that resolve its pool once + +- **Symptom:** a pass of task or mesh draws takes milliseconds of GPU geometry time while its pixels are cheap: with `DM_NVN_GPUPROF_GEOM=1`, `gpuprof.py --timeline` shows nearly all of the pass before its `geometry` mark. The same draws in a depth pre-pass, whose mesh shaders read only the position, are a fraction of it. Their shaders' MSL calls the raw lookup helper hundreds of times, once per 32-bit word. +- **Cause:** a shader that reads a structure through a pointer it loaded (per-vertex attributes behind a meshlet's pointer) issues one load per word at constant offsets from the pointer (`LDG.128` is four). Each found its pool on its own ([Raw global memory lookups that start from their last entry](#raw-global-memory-lookups-that-start-from-their-last-entry)): even on a hit of the last entry that is the entry's four bounds and its two delta words, about 7 memory reads per word read. Ocarina of Time's 11 colour-pass mesh shaders do 253 to 506 such loads per thread. The pass that draws them took 5.8 ms of geometry and 0.2 ms after it at 683x384 on an M3 Max, against about 0.2 ms for the same geometry in the depth pre-pass. +- **Fix:** general, in the translator (`GlobalToStorage.ResolveRawRuns`), loads only. After the pass, the raw loads whose address is a base plus a constant offset c >= 0, as the decoder builds it (low = base low + c, high = base high + the carry, or the carry alone when the high word is 0), are grouped by the base's value: the same SSA values, or the same pure integer operations of them (`RawValueKey`), since the decoder computes a pointer plus a uniform register again for each instruction. + - **The resolve:** a run of two loads or more gets one call of `RawResolveRange` at the nearest block that dominates all of them, before the run's first load there, with a base whose definition reaches that point. It returns the table entry holding the whole range [base + min c, base + max c + 4): the entry it chose last, else the 2 MiB chunk's hint, else the search; 0 when no single entry holds it. Its delta is read there once. + - **The loads:** each calls the resolved helper (`…RawResolved`). A non-zero entry moves the address by the delta and reads it, with no table read. Entry 0 (the run spans two pools, leaves a pool, or the pointer is invalid on a path where the guarded load would not run) takes the full lookup as before. The resolve only reads the table, so running it where a guarded load would not is harmless. + - **Not changed:** stores and atomics keep the per-access path (the write log is per entry). A shader that loads its pointers again inside each guarded block still gets a run per block (Ocarina's colour-pass mesh shaders: 122 resolves for 490 loads, through 5 pointers), and the resolve's own last entry makes all but the first of them a hit. +- **Check:** `dm/gfx/tests/test_dmsh_raw_run.py`: a kernel's three loads at +0, +4 and +12 through one pointer call the range helper once, before them, and the resolved helper three times; on the GPU the two helpers read what the table names for runs inside a pool (also above 4 GiB through the hint), across two adjacent pools, from a pool into a gap, in a gap and at address 0, 1,536 reads with one cache word over the cases. `test_dmsh_raw_last.py` is unchanged (its two loads have undefined, so unequal, uniform bases). The 13 colour-pass task and mesh shaders of Ocarina of Time translate and compile: 506 lookups → 122 resolves, 490 resolved loads and 16 single lookups in each of the larger mesh shaders. +- **The search is a loop:** the binary search over the table (`EmitTableSearch`, in the per-access helper and in `RawResolveRange`) is a loop of 13 steps, not 13 unrolled copies. It runs only when the last entry and the hint both miss, but Metal inlines every helper at every call site, so the unrolled search was copied hundreds of times into each such shader. The pipelines are built when a shader is first dispatched: the 8 compute pipelines that Ocarina of Time's foliage reaction to a sword first needs took 11.3 s on the submit thread, a 12 s freeze (the cut grass in the hidden Kokiri Forest area). Fresh pipeline builds on an M3 Max, `77e64b1d8200eac3` / `d8abf8a34811f8c6` / `e28c9a738fbd99fe`: 2.57 / 2.33 / 0.44 s with the unrolled search, 3.71 / 3.46 / 0.54 s with the resolves added (each resolve one more inlined search), 1.59 / 1.44 / 0.26 s with the loop (the first one's metallib 508 → 290 KB). +- **Open:** a matched in-game measurement at the same spot. Hoisting the pointer loads themselves out of their guards would give one run per pointer, but would read the pointer's buffer where the game's guard does not. Compute pipelines are still built on the submit thread at their first dispatch: a shader the prewarm list does not hold still stops the game for its build, now about 40 % shorter. +- **Found on:** [The Legend of Zelda: Ocarina of Time](../../dm/games/0400486024DEC000/README.md). + ### Bindless handles through a loop phi - **Symptom:** `no resolved slot number`, the shader does not load; the translation has a 32-entry texture-pool array (`fp_t2d_cb0_40000000`, handle type Direct).