mirror of
https://github.com/seedds/nxnative.git
synced 2026-11-23 11:39:42 -10:00
A read of a game uniform slot past the size the game bound gives 0, as Maxwell's constant buffers do: Metal has no bounds of its own, so Paper Mario: The Thousand-Year Door's forward shader read its light count past a 16-byte binding and the GPU hung in Peach's invisibility-potion scene (chain 3510ea767778, issue #1860)
- Translator (TranslationFlags.MetalUniformBounds, Metal only): every read of c[3] to c[16] compares its word index with the slot's size in words from a table in bank 25 and gives 0 past it (TryGenerateBoundedUniformLoad). A fixed-offset read keeps its constant address; a computed-offset read also falls back to row 0, so no read reaches memory past the binding. c0, c2, c1, NVN2 push constants and compute's uniform pointers are not bounded
- ABI: DMSH_CBSIZE_BANK 25, DMSH_CBSIZE_SLOTS 14, binding kind cbsize; the host fills the table from the current bindings at each argument-buffer encode (NVN_RB_CBSIZE, 0 for an unbound slot, at most 64 KiB)
- cb_extent.tsv gives a slot it cannot bound its highest fixed-offset read (f<reg>:<bytes>); the host logs the first shaders bound shorter than that with a running count (ub_short)
- dmsh_fetch.unguard: the build's analyses that look for a uniform word (frag_pos proofs, raster_facts, int_outputs) read the guarded form bare; the host takes such a word only from inside its binding (ubo_float)
- Translator dlls built here from these sources; lock and dmsh_chain.h regenerated
- Tests: test_dmsh_abi (the translator's bank and slots are the header's), test_dmsh_fetch UniformBounds (unguard, a computed offset left alone, the guarded pixel-position proof, Mac and iPhone compiles)
- docs/reference/shaders.md: Reads past a uniform binding's size; the TTYD note; symptom index regenerated
On f1e0f08cc43e21e3 the count reads (576u < size words) ? c14[144].x : 0, so a 16-byte binding skips the loop; reflection and cb_extent row match the chain without the guard. Regression (quick, against 79741184): NieR:Automata and Return of the Obra Dinn, no shader newly failing, no interface or RED change, same frames reached, screenshots within run noise. Cost on NieR's opening flight (bench.py, M6, 2 runs each): GPU p50 6.43 -> 6.53 ms, p95 9.12 -> 9.70 ms, 60 fps either way. Not yet run through the potion scene: the reporter's checkpoint retest is open.
Co-authored-by: Oz Rinkliff <[email protected]>
This commit is contained in:
1 parent
79741184af
commit
26062f9ec0
28 files changed
+254
-20
No files matched your search
@@ -59,6 +59,7 @@ Update 1.0.1 (v65536), SDK 15.3.2. Intelligent Systems' engine on NintendoWare (
|
||||
- **Resolved: `nvnCommandBufferClearColori` / `ClearColorui`**: an integer target is cleared once Mario stands on Rogueport's docks, about frame 12,300 of a new file.
|
||||
- **Resolved: a format-converting copy into a packaged texture** (a 128x128 RGBA8 render target into an RG8 texture, mirrored in Y, as the boat arrives in Rogueport, about frame 10,950): `copy_t2t_draw` declined a destination made without render-target use.
|
||||
- **Resolved: an unbound uniform slot** (`stage 0 cb5 has no uniform buffer bound`, at the title): the argument buffer kept a null pointer there.
|
||||
- **Resolved in the chain, retest open: a GPU hang in Peach's invisibility-potion scene** ([GitHub issue #1860](https://github.com/seedds/nxnative/issues/1860), Mac and iPad, MetalFX and Standard). `forward.bfsha` variant `f1e0f08cc43e21e3` reads its light count at byte 0x900 of uniform slot 11 and loops over that many lights; the game binds 16 bytes to that slot for some materials, relying on Maxwell's 0 past a binding, and Metal read whatever lay there. Reads past a binding now give 0 for every game ([Reads past a uniform binding's size](../../../docs/reference/shaders.md#reads-past-a-uniform-bindings-size)). The fix was not run through the scene here (no save there); the reporter's checkpoint run on both devices is open.
|
||||
- Conditional rendering: the engine calls `SetRenderEnableConditional`; drawn unconditionally (the profile has no `render_cond`), no screen played looked wrong.
|
||||
- The 4 domain shaders of `shaders/tessellation.bfsha` have no Metal stage; nothing seen so far draws with them.
|
||||
|
||||
@@ -89,6 +90,7 @@ General host changes first needed here; each applies to every game:
|
||||
- **Zstd by magic** in `shader_split.py`, **`tex_dyn_slots` for combined handles** (`tex_fit_elem`), **handle arrays in a uniform buffer** (`NVN_RB_TEXU` / `SAMPU` with `n`, array length from the MSL type), **integer clears** converted at replay, **render-target use for a copy destination** (`tex_upgrade`) and **an unbound uniform slot reading the all-zero bank**: [Zstd files recognised by their magic](../../../docs/reference/shaders.md#zstd-files-recognised-by-their-magic), [Texture slots picked at run time](../../../docs/reference/shaders.md#texture-slots-picked-at-run-time), [An array of handles in a uniform buffer](../../../docs/reference/shaders.md#an-array-of-handles-in-a-uniform-buffer), [Integer colour clears](../../../docs/reference/rendering.md#integer-colour-clears), [Render-target use added on demand](../../../docs/reference/rendering.md#render-target-use-added-on-demand), [An unbound uniform slot reads the zero bank](../../../docs/reference/rendering.md#an-unbound-uniform-slot-reads-the-zero-bank).
|
||||
- **`nn::settings::GetAvailableLanguageCodes`** (`hle_sdk16.c`): [Available language codes and their count](../../../docs/reference/services.md#available-language-codes-and-their-count).
|
||||
- **`nn::fs::Unmount` of a mount in the SDK's own table** (`hle_fs.c`): [A mount in the SDK's own table stays until the SDK releases it](../../../docs/reference/services.md#a-mount-in-the-sdks-own-table-stays-until-the-sdk-releases-it).
|
||||
- **Uniform reads past the bound size give 0** (the translator's `MetalUniformBounds`, the size table `DMSH_CBSIZE_BANK`): [Reads past a uniform binding's size](../../../docs/reference/shaders.md#reads-past-a-uniform-bindings-size).
|
||||
- **The host's StandardAllocator cap** (`hle_svc.c`, the `stdalloc_cap` key): [StandardAllocators over 12 to 62 GB of address space](../../../docs/reference/memory.md#standardallocators-over-12-to-62-gb-of-address-space).
|
||||
|
||||
## Open
|
||||
|
||||
@@ -40,6 +40,11 @@
|
||||
// compute's c0 push region there); one block for the graphics stages, one for compute
|
||||
#define DMSH_PUSH_BANK 24
|
||||
#define DMSH_PUSH_SIZE 0x100 // bytes of a block
|
||||
|
||||
// Uniform bounds: a read of a game uniform slot (c[3 + reg]) past the size the game bound gives 0, as Maxwell's constant buffers do. The translator reads each slot's bound size from
|
||||
// a table in a bank of its own (TranslationFlags.MetalUniformBounds, Ryujinx Constants.NxUniformSizesBank), which the host fills from the current bindings
|
||||
#define DMSH_CBSIZE_BANK 25
|
||||
#define DMSH_CBSIZE_SLOTS 14 // a u32 for each of uniform slots 0 to 13, as four uint4: 64 bytes
|
||||
#define DMSH_C0_POINT_SIZE 0x610 // graphics stages: the largest point size, to which GLSLC clamps a shader-written gl_PointSize (Super Mario Odyssey's point sprites)
|
||||
#define DMSH_C0_SAMPLE_TABLE 0x620 // pixel stage: GLSLC's sample position table, one byte per (pixel of the location grid, sample): x and y in 1/16 pixel, low and high nibble
|
||||
#define DMSH_C0_SAMPLE_BYTES 16 // bytes of that table
|
||||
@@ -50,6 +55,7 @@
|
||||
#define DMSH_KIND_CBUF "cbuf" // uniform buffer slot reg (c[3 + reg])
|
||||
#define DMSH_KIND_C1 "c1" // the shader's own constant segment c[1] (its bytes are the json's c1)
|
||||
#define DMSH_KIND_DRVCB "drvcb" // a driver segment, c[bank] (bank 0 or 2): NVN_RB_DRV0 / NVN_RB_DRV2
|
||||
#define DMSH_KIND_CBSIZE "cbsize" // the uniform slots' bound sizes, c[DMSH_CBSIZE_BANK]: NVN_RB_CBSIZE
|
||||
#define DMSH_KIND_SUPPORT "support" // the translator's support buffer
|
||||
#define DMSH_KIND_GEOMETRY "geometry" // one of the geometry lowering's helper buffers, reg = its index (dmsh_geometry.py HELPERS)
|
||||
#define DMSH_KIND_SBUF "sbuf" // storage buffer slot reg, its address in the stage's c0 table; rw = the shader writes it
|
||||
|
||||
@@ -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 <library dir>/b-<V>/. Run dmsh_chain.py --header after changing the chain's tools and commit this file with the change
|
||||
#define DMSH_CHAIN "dedc9391c30b"
|
||||
#define DMSH_CHAIN "3510ea767778"
|
||||
+19
-3
@@ -5429,7 +5429,7 @@ static void shmap_read(void) {
|
||||
}
|
||||
|
||||
@interface NvShader : NSObject { @public id<MTLFunction> fn, tf_fn, discard_fn, fn_u, fn_m, fn_d, geo_fn; uint8_t mask_m; // fn_u: the integer-output entry point (dmsh_build.py fs_uint), for pipelines whose colour attachments are all unsigned integer (pso_desc); fn_m: the mixed one, its outputs in mask_m unsigned integer; fn_d: the dual-source one (dmsh_build.py fs_dual)
|
||||
uint16_t tf_stride[4]; uint32_t cb_ext[16], sb_ro; nvn_refl rf; id<MTLArgumentEncoder> ae; NSUInteger arg_len; int stage, range_ro, layer_out; const char *builtin; uint64_t logged; char key[24]; id<MTLBuffer> c1buf; uint64_t c1_gpu; size_t c1off;
|
||||
uint16_t tf_stride[4]; uint32_t cb_ext[16], cb_fix[16], sb_ro; nvn_refl rf; id<MTLArgumentEncoder> ae; NSUInteger arg_len; int stage, range_ro, layer_out; const char *builtin; uint64_t logged; char key[24]; id<MTLBuffer> c1buf; uint64_t c1_gpu; size_t c1off;
|
||||
uint32_t geo_vertices, geo_invocations, geo_output, geo_stride, geo_index_stride;
|
||||
uint8_t mesh_kind, mesh_notask; uint16_t mesh_threads, mesh_payload; // an NVN2 task (1) or mesh (2) shader, a mesh shader with no task, its workgroup's threads, its payload's bytes (dmsh_meshstage.py)
|
||||
id<MTLFunction> mesh_obj; // a mesh shader with no task: the object function that launches its workgroups in blocks of DMSH_MESH_GRID (dmsh_meshstage.py main0_o)
|
||||
@@ -5765,11 +5765,22 @@ static NvShader *shader_load(NSString *pc, int stage, int layer) {
|
||||
NSString *ext = g_cb_ext[[pc hasSuffix:@"_b"] ? [pc substringToIndex:pc.length - 2] : pc]; // bytes each uniform slot can read (cb_len), storage slots never written (sb_ro)
|
||||
for (NSString *f in [ext componentsSeparatedByString:@" "]) { int r = 0, n = 0;
|
||||
if (sscanf(f.UTF8String, "%d:%d", &r, &n) == 2 && r >= 0 && r < 16 && n > 0) o->cb_ext[r] = (uint32_t)n;
|
||||
else if (sscanf(f.UTF8String, "f%d:%d", &r, &n) == 2 && r >= 0 && r < 16 && n > 0) o->cb_fix[r] = (uint32_t)n;
|
||||
else if (sscanf(f.UTF8String, "s%d", &r) == 1 && r >= 0 && r < 32) o->sb_ro |= 1u << r; }
|
||||
return o;
|
||||
}
|
||||
// The part of uniform slot reg's binding the shader can read: its first cb_ext bytes when cb_extent.tsv bounds them, else the whole binding
|
||||
static inline uint64_t cb_len(NvShader *sh, int reg, uint64_t size) { uint32_t e = sh && reg >= 0 && reg < 16 ? sh->cb_ext[reg] : 0; return e && e < size ? e : size; }
|
||||
// Encodes where a uniform slot is bound shorter than the shader reads it at a fixed offset (cb_extent.tsv: the slot's proven extent, else its highest fixed-offset read, f<reg>:<bytes>).
|
||||
// Maxwell gives 0 past a constant buffer's size and the translator's reads do the same (DMSH_CBSIZE_BANK), so this is not wrong: it counts what used to read the guest memory past the
|
||||
// binding. Paper Mario: The Thousand-Year Door binds 16 bytes to a slot read up to byte 0x930, and the GPU hung on the light count it read at 0x900 (GitHub issue #1860)
|
||||
static uint64_t g_ub_short;
|
||||
static void ub_short(NvShader *sh, int st, int reg, uint64_t size) {
|
||||
uint32_t need = sh->cb_ext[reg] ? sh->cb_ext[reg] : sh->cb_fix[reg];
|
||||
if (!need || size >= need) return;
|
||||
uint64_t n = ++g_ub_short;
|
||||
if (!(sh->logged & 16)) { sh->logged |= 16; static int nlog; if (nlog++ < 16) MLOG("uniform slot %d of shader %s (stage %d) is bound with %llu bytes and read up to byte %u at a fixed offset: reads past its size give 0 (%llu such encodes so far)", reg, sh->key, st, (unsigned long long)size, need, (unsigned long long)n); }
|
||||
}
|
||||
|
||||
static int stage_of(NSString *stage) {
|
||||
if ([stage isEqualToString:@"vertex"]) return 0; if ([stage isEqualToString:@"pixel"]) return 1; if ([stage isEqualToString:@"compute"]) return 5;
|
||||
@@ -5786,7 +5797,7 @@ static int rt_range_bindings_ro(NSDictionary *j) {
|
||||
if (![b isKindOfClass:[NSDictionary class]] || ![b[@"kind"] isKindOfClass:[NSString class]] || ![b[@"msl_type"] isKindOfClass:[NSString class]]) return 0;
|
||||
NSString *k=b[@"kind"], *t=b[@"msl_type"];
|
||||
if (b[@"rw"] && (![b[@"rw"] isKindOfClass:[NSNumber class]] || [b[@"rw"] boolValue])) return 0;
|
||||
if ([k isEqual:@DMSH_KIND_CBUF] || [k isEqual:@DMSH_KIND_C1]) { if (![t hasPrefix:@"constant "]) return 0; }
|
||||
if ([k isEqual:@DMSH_KIND_CBUF] || [k isEqual:@DMSH_KIND_C1] || [k isEqual:@DMSH_KIND_CBSIZE]) { if (![t hasPrefix:@"constant "]) return 0; }
|
||||
else if ([k isEqual:@DMSH_KIND_SBUF]) { if (![b[@"rw"] isKindOfClass:[NSNumber class]] || [b[@"rw"] boolValue] || ![t hasPrefix:@"const device "]) return 0; }
|
||||
else if ([k isEqual:@DMSH_KIND_SAMP] || [k isEqual:@DMSH_KIND_SAMP_TEX]) { if (![t isEqual:@"sampler"]) return 0; }
|
||||
else if ([k isEqual:@DMSH_KIND_TEX] || [k isEqual:@DMSH_KIND_TBUF]) {
|
||||
@@ -6815,7 +6826,7 @@ static int prog_swrites(NvProg *pr) {
|
||||
static void order_note(NvProg *pr) { // after each draw of the pass: does it read memory in a stage after the vertex stage (anything bound there but samplers and driver data)
|
||||
for (int st = 1; pr && st < 6 && !g_pass_late_res; st++) { __unsafe_unretained NvShader *sh = pr->sh[st]; if (!sh) continue;
|
||||
for (int i = 0; i < sh->rf.nb; i++) { int k = sh->rf.b[i].kind;
|
||||
if (k != NVN_RB_SAMP && k != NVN_RB_SAMPT && k != NVN_RB_SAMPU && k != NVN_RB_SAMPI && k != NVN_RB_SAMPD && k != NVN_RB_SAMPA && k != NVN_RB_SAMPP && k != NVN_RB_SAMPH && k != NVN_RB_SUPPORT && k != NVN_RB_C1 && k != NVN_RB_DRV0 && k != NVN_RB_DRV2 && k != NVN_RB_PUSH) { g_pass_late_res = 1; break; } } }
|
||||
if (k != NVN_RB_SAMP && k != NVN_RB_SAMPT && k != NVN_RB_SAMPU && k != NVN_RB_SAMPI && k != NVN_RB_SAMPD && k != NVN_RB_SAMPA && k != NVN_RB_SAMPP && k != NVN_RB_SAMPH && k != NVN_RB_SUPPORT && k != NVN_RB_C1 && k != NVN_RB_DRV0 && k != NVN_RB_DRV2 && k != NVN_RB_PUSH && k != NVN_RB_CBSIZE) { g_pass_late_res = 1; break; } } }
|
||||
}
|
||||
// A draw that writes, after an ordering barrier in a pass whose earlier draws did not write (g_pass_order): when those draws read memory only in their vertex stage, or the barrier
|
||||
// orders only primitives (whose fragments NVN leaves unordered too), a barrier inside the pass from the vertex stage to the stages that write keeps the pass and its attachments (the
|
||||
@@ -10342,6 +10353,11 @@ static int encode_args_(id<MTLCommandEncoder> en, NvShader *sh, int nvn_stage, i
|
||||
} else if (b->kind == NVN_RB_SUPPORT) { // support_buffer: scale 1.0, BGRA swap 0, viewport transform not disabled (viewport fields are not read)
|
||||
slots[aid] = support_gpu();
|
||||
USE(support_buf(), MTLResourceUsageRead);
|
||||
} else if (b->kind == NVN_RB_CBSIZE) { // the uniform slots' bound sizes (DMSH_CBSIZE_BANK), which the translator's reads compare with: a read past its slot's size gives 0, as on Maxwell
|
||||
id<MTLBuffer> db; size_t doff = arena_alloc(16 * ((DMSH_CBSIZE_SLOTS + 3) / 4), &db); uint32_t *d = (uint32_t *)(g_cur_arena->cpu + doff);
|
||||
memset(d, 0, 16 * ((DMSH_CBSIZE_SLOTS + 3) / 4)); // a slot with nothing bound reads the zero bank (above) and gets 0 here too
|
||||
for (int r = 0; r < DMSH_CBSIZE_SLOTS; r++) { const p_bind_buf *u = &S.ubo[nvn_stage][r]; if (u->addr) { d[r] = u->size < 65536 ? (uint32_t)u->size : 65536; ub_short(sh, nvn_stage, r, u->size); } }
|
||||
slots[aid] = g_cur_arena->gpu + doff; USE(db, MTLResourceUsageRead);
|
||||
} else if (b->kind == NVN_RB_PUSH) { // NVN2 push constants (c[24]): the stage group's current block
|
||||
id<MTLBuffer> db; size_t doff = arena_alloc(DMSH_PUSH_SIZE, &db);
|
||||
memcpy(g_cur_arena->cpu + doff, S.push[nvn_stage == 5 ? 1 : 0], DMSH_PUSH_SIZE);
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
#include <stdint.h>
|
||||
|
||||
enum { NVN_RB_CBUF = 1, NVN_RB_SAMP, NVN_RB_TEX, NVN_RB_IMG, NVN_RB_TBUF,
|
||||
NVN_RB_SBUFP, NVN_RB_SUPPORT, NVN_RB_C1, NVN_RB_DRV0, NVN_RB_DRV2, NVN_RB_SAMPT, NVN_RB_UBOP, NVN_RB_TEXU, NVN_RB_SAMPU, NVN_RB_SAMPI, NVN_RB_SBUFU, NVN_RB_TEXD, NVN_RB_SAMPD, NVN_RB_TEXA, NVN_RB_SAMPA, NVN_RB_GEOMETRY, NVN_RB_TEXP, NVN_RB_SAMPP, NVN_RB_TEXH, NVN_RB_SAMPH, NVN_RB_BORDER, NVN_RB_PUSH, NVN_RB_GMEM, NVN_RB_GMEML, NVN_RB_IMGU, NVN_RB_TBUFU };
|
||||
NVN_RB_SBUFP, NVN_RB_SUPPORT, NVN_RB_C1, NVN_RB_DRV0, NVN_RB_DRV2, NVN_RB_SAMPT, NVN_RB_UBOP, NVN_RB_TEXU, NVN_RB_SAMPU, NVN_RB_SAMPI, NVN_RB_SBUFU, NVN_RB_TEXD, NVN_RB_SAMPD, NVN_RB_TEXA, NVN_RB_SAMPA, NVN_RB_GEOMETRY, NVN_RB_TEXP, NVN_RB_SAMPP, NVN_RB_TEXH, NVN_RB_SAMPH, NVN_RB_BORDER, NVN_RB_PUSH, NVN_RB_GMEM, NVN_RB_GMEML, NVN_RB_IMGU, NVN_RB_TBUFU, NVN_RB_CBSIZE };
|
||||
// IMGU / TBUFU: an image / a buffer texture whose handle the game keeps in uniform slot reg at byte off, as TEXU (Unreal Engine 5.4 on the Switch 2 keeps every image in c[3]). Read at encode time
|
||||
// GMEM: the host's memory pool table for global memory the translator traced to no storage buffer (dmsh_abi.h DMSH_GMEM_MAP_*, nvn_mtl.m gmem_map_gpu): the shader may read, and with rw
|
||||
// write, anything in any pool. GMEML: the write log of those stores (dmsh_abi.h DMSH_GMEM_LOG_*, nvn_mtl.m gml_take)
|
||||
|
||||
@@ -101,6 +101,7 @@ int nvn_refl_from_json(NSDictionary *j, nvn_refl *o, char *err, int errlen) {
|
||||
else if ([k isEqualToString:@DMSH_KIND_GMEM_MAP]) { r->kind = NVN_RB_GMEM; r->rw = [b[@"rw"] boolValue]; }
|
||||
else if ([k isEqualToString:@DMSH_KIND_GMEM_LOG]) { r->kind = NVN_RB_GMEML; r->rw = 1; }
|
||||
else if ([k isEqualToString:@DMSH_KIND_C1]) r->kind = NVN_RB_C1;
|
||||
else if ([k isEqualToString:@DMSH_KIND_CBSIZE]) r->kind = NVN_RB_CBSIZE;
|
||||
else if ([k isEqualToString:@DMSH_KIND_DRVCB]) r->kind = [b[@"bank"] intValue] == DMSH_PUSH_BANK ? NVN_RB_PUSH : [b[@"bank"] intValue] == 2 ? NVN_RB_DRV2 : NVN_RB_DRV0;
|
||||
else if ([k isEqualToString:@DMSH_KIND_BORDER]) { if (o->border) FAIL("two border colour blocks"); r->kind = NVN_RB_BORDER; o->border = (uint8_t)(o->nb + 1); }
|
||||
else FAIL("B binding kind %s not implemented (%s)", k.UTF8String, [b[@"msl_name"] UTF8String]);
|
||||
|
||||
@@ -226,6 +226,11 @@ class PixelPositionSample(unittest.TestCase):
|
||||
src = FS_POS.replace(' float _47 = _43 / _45;\n', '').replace('_47 * (*spvDescriptorSet0.fp_c3)._m0[6].x', '(*spvDescriptorSet0.fp_c3)._m0[6].x * _43')
|
||||
self.assertEqual(self.calls(src)[0]['frag_pos'], [[0, 6, 0], [0, 6, 1]])
|
||||
|
||||
def test_through_the_uniform_bounds(self): # the translator's bounded read (TranslationFlags.MetalUniformBounds, GitHub issue #1860), in parentheses as a product writes it
|
||||
v, meta = dmsh_fetch.fold(guarded(FS_POS), BINDINGS)
|
||||
self.assertEqual(meta['calls'], [{'fc': 0, 'tex_reg': 0, 'frag_pos': [[0, 6, 0], [0, 6, 1]]}])
|
||||
self.assertIn(GUARD.format(w=24, r='(*spvDescriptorSet0.fp_c3)._m0[6].x'), v, 'the compiled source keeps the guard')
|
||||
|
||||
def test_not_rewritten(self):
|
||||
for why, src in (('y from x', FS_POS.replace('float _49 = gl_FragCoord.y;', 'float _49 = gl_FragCoord.x;')),
|
||||
('divided by a uniform', FS_POS.replace('float _45 = (*spvDescriptorSet0.support_buffer)._m5[0].x;', 'float _45 = (*spvDescriptorSet0.fp_c3)._m0[1].x;')),
|
||||
@@ -244,6 +249,36 @@ class PixelPositionSample(unittest.TestCase):
|
||||
except subprocess.CalledProcessError as e: self.fail(e.stderr)
|
||||
|
||||
|
||||
# A uniform read as the translator bounds it: the word when the slot's size in words (the size table, bank DMSH_CBSIZE_BANK) holds its index w, else 0
|
||||
GUARD = '(({w}u < ((*spvDescriptorSet0.fp_c%d)._m0[0].x >> 2u)) ? {r} : 0.0)' % dmsh_abi.CBSIZE_BANK
|
||||
|
||||
def guarded(src): # FS_POS with its two c[6] words bounded, and the size table declared
|
||||
for c, w in (('x', 24), ('y', 25)): src = src.replace('(*spvDescriptorSet0.fp_c3)._m0[6].%s' % c, GUARD.format(w=w, r='(*spvDescriptorSet0.fp_c3)._m0[6].%s' % c))
|
||||
return src.replace('struct spvDescriptorSetBuffer0', 'struct _23\n{\n uint4 _m0[4];\n};\n\nstruct spvDescriptorSetBuffer0').replace(
|
||||
' sampler fp_t_tcb_8Smplr_w [[id(5)]];', ' sampler fp_t_tcb_8Smplr_w [[id(5)]];\n constant _23* fp_c%d [[id(6)]];' % dmsh_abi.CBSIZE_BANK)
|
||||
|
||||
class UniformBounds(unittest.TestCase):
|
||||
def test_unguard(self):
|
||||
read = '(*spvDescriptorSet0.vp_c5)._m0[29].y'
|
||||
bare = GUARD.format(w=117, r=read)[1:-1].replace('fp_c', 'vp_c')
|
||||
for why, src, want in (('in parentheses', 'float _1 = _2 * %s;' % GUARD.format(w=117, r=read).replace('fp_c', 'vp_c'), 'float _1 = _2 * %s;' % read),
|
||||
('a function argument', 'float _1 = fma(_2, %s, _3);' % bare, 'float _1 = fma(_2, %s, _3);' % read),
|
||||
('bit-cast', 'bool _1 = 0 >= as_type<int>(%s);' % bare, 'bool _1 = 0 >= as_type<int>(%s);' % read)):
|
||||
with self.subTest(why=why): self.assertEqual(dmsh_fetch.unguard(src), want)
|
||||
|
||||
def test_a_computed_offset_stays(self): # its guard is a value of its own, and the read's index chooses row 0 when out of bounds
|
||||
src = ('bool _5 = ((uint(_3) << 2u) | uint(_4)) < ((*spvDescriptorSet0.fp_c%d)._m0[2].w >> 2u);\n'
|
||||
'float _6 = _5 ? (*spvDescriptorSet0.fp_c14)._m0[_5 ? _3 : 0][_4] : 0.0;' % dmsh_abi.CBSIZE_BANK)
|
||||
self.assertEqual(dmsh_fetch.unguard(src), src)
|
||||
|
||||
def test_compiles_on_both_platforms(self):
|
||||
v, _ = dmsh_fetch.fold(guarded(FS_POS), BINDINGS)
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
for sdk in ('macosx', 'iphoneos'):
|
||||
with self.subTest(sdk=sdk):
|
||||
try: compile_lib(v, pathlib.Path(d), 'bounded_' + sdk, sdk)
|
||||
except subprocess.CalledProcessError as e: self.fail(e.stderr)
|
||||
|
||||
class ScreenVaryings(unittest.TestCase):
|
||||
def test_both_spellings_after_a_branch(self):
|
||||
self.assertEqual(dmsh_fetch.screen_varyings(VS), [4, 5])
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
# cb_extent.py <dmsh_b version dir> <output tsv>: how far into each uniform slot (cbuf binding) a shader can read, from the translated MSL. A line lists, per shader key, the slots whose
|
||||
# reads are all proven to stay inside the first <bytes> bytes: `<key>\t<reg>:<bytes> ...` (reg as in the reflection json, bytes a multiple of 16). A slot left out may be read anywhere in its
|
||||
# binding. Indices are bounded with c1_guard.py's interval arithmetic; any other use of the binding's name (a pointer handed on, a member other than _m0) leaves the slot out.
|
||||
# `s<reg>` marks a storage slot the shader never writes (unwritten); the host notes GPU writes for every other storage binding (nvn_mtl.m sbw_note).
|
||||
# `f<reg>:<bytes>` gives a slot left out the end of its highest row read at a constant index: the host counts the encodes that bind less (nvn_mtl.m ub_short), whose reads past the
|
||||
# binding give 0 as on Maxwell (GitHub issue #1860). `s<reg>` marks a storage slot the shader never writes (unwritten); the host notes GPU writes for every other storage binding (nvn_mtl.m sbw_note).
|
||||
# The host (nvn_mtl.m cb_ext) reads only that much of a binding when it has to copy one: a uniform block the game updates in part inside a render pass (ubp_get). Breath of the Wild binds
|
||||
# a 64 KiB block to the vertex stage and updates its first 64 bytes 221 times a frame, while its vertex shaders read at most 544 bytes of it.
|
||||
# The host loads the table only when its header names its library's chain version and inputs stamp (like c1_full.tsv); dmsh_build.py makes it after each full build
|
||||
@@ -44,6 +45,17 @@ def extents(source, bindings):
|
||||
return out
|
||||
|
||||
|
||||
def fixed_extents(source, bindings, proven):
|
||||
"""{reg: bytes} up to the end of the highest row each cbuf binding is read at by a constant index, for the slots extents() leaves out. The host counts the encodes where a slot
|
||||
is bound shorter than that (nvn_mtl.m ub_short): those reads give 0, as Maxwell's do (GitHub issue #1860)"""
|
||||
out = {}
|
||||
for b in bindings:
|
||||
if b.get("kind") != abi.KIND_CBUF or "reg" not in b or b["reg"] in proven: continue
|
||||
rows = [int(i) for i in re.findall(r"\(\*spvDescriptorSet0\." + re.escape(b["msl_name"]) + r"\)\._m0\[(\d+)\]", source)]
|
||||
if rows and 16 * (max(rows) + 1) < MAX: out[b["reg"]] = 16 * (max(rows) + 1)
|
||||
return out
|
||||
|
||||
|
||||
WRITE = re.compile(r"\s*(?:=(?!=)|[-+*/%&|^]=|<<=|>>=|\+\+|--)")
|
||||
|
||||
|
||||
@@ -79,7 +91,8 @@ def row(path):
|
||||
with romfs.open(path[:-5] + ".metal", encoding="utf-8") as stream: source = stream.read()
|
||||
except (OSError, ValueError):
|
||||
return None
|
||||
toks = [f"{r}:{n}" for r, n in sorted(extents(source, bindings).items())] + [f"s{r}" for r in unwritten(source, bindings)]
|
||||
proven = extents(source, bindings)
|
||||
toks = [f"{r}:{n}" for r, n in sorted(proven.items())] + [f"f{r}:{n}" for r, n in sorted(fixed_extents(source, bindings, proven).items())] + [f"s{r}" for r in unwritten(source, bindings)]
|
||||
return os.path.basename(path)[:-len("_b.json")] + "\t" + " ".join(toks) if toks else None
|
||||
|
||||
|
||||
@@ -90,12 +103,12 @@ def main():
|
||||
version_dir = str(shader_lib.view(lib)) # its folder or its one file, read in place
|
||||
paths = [os.path.join(version_dir, n) for n in outputs(version_dir, "json") if n.endswith("_b.json")]
|
||||
with multiprocessing.Pool() as pool: rows = [r for r in pool.map(row, paths, chunksize=64) if r]
|
||||
slots, ro = sum(r.count(":") for r in rows), sum(len(re.findall(r"\bs\d+", r.split("\t", 1)[1])) for r in rows)
|
||||
slots, ro = sum(len(re.findall(r"(?<![fs\w])\d+:", r.split("\t", 1)[1])) for r in rows), sum(len(re.findall(r"\bs\d+", r.split("\t", 1)[1])) for r in rows)
|
||||
os.makedirs(os.path.dirname(output), exist_ok=True)
|
||||
with open(output, "w", encoding="utf-8", newline="") as stream:
|
||||
stamp = datetime.datetime.now().astimezone().isoformat(timespec="seconds")
|
||||
stream.write(f"{shader_lib.table_head(lib)} {stamp}\n") # the library's chain version and the profile inputs it was built from
|
||||
stream.write("# shader key, then reg:bytes for each uniform slot whose reads stay inside its first bytes, and s<reg> for each storage slot it never writes (cb_extent.py)\n")
|
||||
stream.write("# shader key, then reg:bytes for each uniform slot whose reads stay inside its first bytes, f<reg>:<bytes> for each other slot up to its highest fixed-offset read, and s<reg> for each storage slot it never writes (cb_extent.py)\n")
|
||||
for line in rows: stream.write(line + "\n")
|
||||
print(f"bounded uniform reads: {slots} slots; storage slots never written: {ro}; {len(rows)} shaders")
|
||||
|
||||
|
||||
@@ -938,7 +938,7 @@ def raster_facts(stage, src):
|
||||
scr = {'screen': dmsh_fetch.screen_varyings(src)} # clip → screen varyings (dmsh_fetch.py): the vertex side of a projective sample's tile read
|
||||
body = re.search(r'\bvertex\s+\w+\s+\w+\s*\(.*?\)\s*\{(.*)\}\s*$', src, re.S) # the main function is the last function in the file
|
||||
if not body or re.search(r'\b(if|for|while|switch|do)\b|clip_distance|ClipDistance', body.group(1)): return {'pos_attr': -1, **scr}
|
||||
b = body.group(1)
|
||||
b = dmsh_fetch.unguard(body.group(1)) # a bounded uniform word read bare (the host's proof reads it only from inside its binding)
|
||||
attr = {m.group(2): int(m.group(3)) for m in attributes(src)}
|
||||
var = {m.group(1): (m.group(2), m.group(3)) for m in re.finditer(r'float\s+(_\w+)\s*=\s*in\.(\w+)\.([xyzw]);', b)}
|
||||
last = {}
|
||||
@@ -1119,7 +1119,9 @@ def reflect(key, stage, msl, res):
|
||||
elif nm == 'support_buffer': e.update(kind=abi.KIND_SUPPORT)
|
||||
elif re.fullmatch(r'[a-z]+_c(\d+)', nm):
|
||||
n = int(re.fullmatch(r'[a-z]+_c(\d+)', nm).group(1))
|
||||
e.update(kind=abi.KIND_CBUF, reg=n - 3) if 3 <= n <= 16 else e.update(kind=abi.KIND_C1 if n == 1 else abi.KIND_DRVCB, bank=n)
|
||||
if 3 <= n <= 16: e.update(kind=abi.KIND_CBUF, reg=n - 3)
|
||||
elif n == abi.CBSIZE_BANK: e.update(kind=abi.KIND_CBSIZE) # the uniform slots' bound sizes, which the translator's bounded reads compare with
|
||||
else: e.update(kind=abi.KIND_C1 if n == 1 else abi.KIND_DRVCB, bank=n)
|
||||
elif re.fullmatch(r'[a-z]+_s(\d+)', nm):
|
||||
e.update(kind=abi.KIND_SBUF, index=int(re.fullmatch(r'[a-z]+_s(\d+)', nm).group(1)))
|
||||
elif decode_ubo_tex(nm[:-5] if nm.endswith('Smplr') else nm): # bindless: the handle is in a uniform buffer (reg = uniform slot, off = byte offset)
|
||||
@@ -1416,6 +1418,7 @@ def int_outputs(src, body, cols):
|
||||
constants, shifts and ORs). So each write is followed back through the locals: a value computed by an integer operation or a small integer constant counts as integer, the bits of a computed
|
||||
float as float; zero, larger constants (the bits of a float constant) and words copied from a uniform or an input say nothing. A denormal float literal is a small integer constant SPIRV-Cross
|
||||
printed through the output's type. → the outputs with integers and no float bits, or, when none is that clean (a register reused by two branches), the outputs with integers"""
|
||||
body = dmsh_fetch.unguard(body) # a bounded uniform word is a word copied from a uniform
|
||||
types = {v: t for t, v in re.findall(r'^\s*(u?int\d?|float\d?|bool)\s+(_\d+)\b', body, re.M)}
|
||||
defs = collections.defaultdict(list)
|
||||
for v, e in re.findall(r'^\s*(?:(?:u?int\d?|float\d?|bool)\s+)?(_\d+)\s*=\s*([^;]+);', body, re.M): defs[v].append(e.strip())
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
# Translation chain tool fingerprints (written by tool_lock.py --update-lock; regenerate after changing tools and commit it)
|
||||
dmsh_xlate.dll 551da0c078b5d588
|
||||
Ryujinx.Graphics.Shader.dll 8d1cbd203398bab8
|
||||
Ryujinx.Common.dll 1bd68db8a0843eb8
|
||||
xlate_source 0bd66426675438a9
|
||||
dmsh_xlate.dll f2d1a53df023344a
|
||||
Ryujinx.Graphics.Shader.dll cbb2a0c24869eefa
|
||||
Ryujinx.Common.dll ffe1bca8ca60ee61
|
||||
xlate_source 8986080b40b79cab
|
||||
spirv-cross e37945d8e441d34d
|
||||
metal_macosx Apple metal version 32023.922 (metalfe-32023.922.4)
|
||||
metal_iphoneos Apple metal version 32023.922 (metalfe-32023.922.4)
|
||||
@@ -43,6 +43,17 @@ def _proj(msl, var, comp, locn):
|
||||
return src(m.group(1), comp) if m and src(m.group(1), comp) == src(m.group(2), 'w') else None
|
||||
|
||||
_UNI = re.compile(r'\(\*spvDescriptorSet0\.fp_c(\d+)\)\._m0\[(\d+)\]\.([xyzw])')
|
||||
|
||||
# A read of a game uniform slot at a fixed offset, as the translator bounds it (TranslationFlags.MetalUniformBounds, GitHub issue #1860): the word when the slot's bound size (the size
|
||||
# table, bank DMSH_CBSIZE_BANK) holds it, else 0, wrapped in parentheses or not as the expression around it needs. unguard gives back the bare read for the analyses that look for a
|
||||
# uniform's word (_frag_pos below, dmsh_build.py raster_facts and int_outputs): the host takes such a word's value only from inside the binding (nvn_mtl.m ubo_float refuses a word
|
||||
# past its size), where the guard chooses the read. Only for analysis: never in source that is compiled
|
||||
_GCOND = r'\(\d+u < \(\(\*spvDescriptorSet0\.[a-z]+_c%d\)\._m0\[\d\]\.[xyzw] >> 2u\)\)' % abi.CBSIZE_BANK
|
||||
_GREAD = r'(\(\*spvDescriptorSet0\.[a-z]+_c\d+\)\._m0\[\d+\]\.[xyzw])'
|
||||
_GUARDED = re.compile(r'(?<![\w>])\(%s \? %s : 0(?:\.0|u)?\)|%s \? %s : 0(?:\.0|u)?(?![\w.])' % (_GCOND, _GREAD, _GCOND, _GREAD)) # parentheses after a name or > are a call's
|
||||
|
||||
def unguard(msl):
|
||||
return _GUARDED.sub(lambda m: m.group(1) or m.group(2), msl) if 'spvDescriptorSet0' in msl else msl
|
||||
_SCALE = '(*spvDescriptorSet0.support_buffer)._m5[0].x' # the support buffer's render scale (Ryujinx's layout), which the host fills with 1 (nvn_mtl.m support buffer)
|
||||
|
||||
def _frag_pos(msl, var, comp):
|
||||
@@ -212,7 +223,8 @@ def fold(msl, bindings, om_only_ok=False):
|
||||
if a and b and a.group(1) == b.group(1) and a.group(1) in locn: how = {'varying_locn': locn[a.group(1)]}
|
||||
else:
|
||||
pa, pb = (_proj(text, d.group(1), 'x', locn), _proj(text, d.group(2), 'y', locn)) if d else (None, None)
|
||||
fx, fy = (_frag_pos(text, d.group(1), 'x'), _frag_pos(text, d.group(2), 'y')) if d else (None, None)
|
||||
bare = unguard(text) if d else text # the uniform words the proof names, read bare (unguard)
|
||||
fx, fy = (_frag_pos(bare, d.group(1), 'x'), _frag_pos(bare, d.group(2), 'y')) if d else (None, None)
|
||||
if pa and pa == pb: how = {'varying_locn': locn[pa], 'proj': 1}
|
||||
elif fx and fy: how = {'frag_pos': [fx, fy]}
|
||||
else: continue
|
||||
|
||||
@@ -201,7 +201,7 @@ static class SwshXlate
|
||||
byte[] code = File.ReadAllBytes((string)job["code"]);
|
||||
var acc = new Accessor(code, job);
|
||||
// Job debug = false: turn off DebugMode (DebugMode skips the AST optimizer and the output is full of temporaries; semantics unchanged)
|
||||
var flags = TranslationFlags.MetalImageAtomics | (job["debug"] is JsonNode dbg && !(bool)dbg ? 0 : TranslationFlags.DebugMode) | ((string)job["stage"] == "cs" ? TranslationFlags.Compute : 0) | ((string)job["arch"] == "sm86" ? TranslationFlags.Ampere : 0);
|
||||
var flags = TranslationFlags.MetalImageAtomics | TranslationFlags.MetalUniformBounds | (job["debug"] is JsonNode dbg && !(bool)dbg ? 0 : TranslationFlags.DebugMode) | ((string)job["stage"] == "cs" ? TranslationFlags.Compute : 0) | ((string)job["arch"] == "sm86" ? TranslationFlags.Ampere : 0);
|
||||
var ctx = Translator.CreateContext(0, acc, new TranslationOptions(TargetLanguage.Spirv, TargetApi.Vulkan, flags));
|
||||
bool geometry = job["geometry_topology"] != null;
|
||||
ShaderProgram p = ctx.Translate(geometry);
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Vendored
+2
@@ -15,5 +15,7 @@ Three projects from Ryujinx 1.3.2: `Ryujinx.Graphics.Shader`, `Ryujinx.Common` a
|
||||
|
||||
- `Ryujinx.Graphics.Shader/Instructions/InstEmitSurface.cs`, `IntermediateRepresentation/TextureFlags.cs` and `CodeGen/Spirv/Instructions.cs`: the Metal path (`TranslationFlags.MetalImageAtomics`) bounds image atomics before forming the texel pointer, which SPIRV-Cross writes as a native texture atomic (MSL 3.1) on buffer, 2D, 2D-array and 3D images. Returning `IGN` atomics preserve the old texel on the valid edge and return zero outside the image; CAS is a native texture compare-exchange behind the same guard; predicate results and non-IGN modes remain rejected. See [bounds of image atomics](../../../docs/reference/shaders.md#bounds-of-image-atomics) and [image atomics](../../../docs/reference/shaders.md#image-atomics), found on SHIN MEGAMI TENSEI V: Vengeance's particle counters.
|
||||
|
||||
- `Ryujinx.Graphics.Shader/CodeGen/Spirv/Instructions.cs` (`TryGenerateBoundedUniformLoad`), `Translation/ResourceManager.cs`, `StructuredIr/ShaderProperties.cs`, `Constants.cs` and `Translation/TranslationFlags.cs`: the Metal path (`TranslationFlags.MetalUniformBounds`) gives 0 for a read of a game uniform slot (c[3] to c[16]) past the size the game bound, as Maxwell does, comparing the word's index with the slot's size from a table in bank 25 that the host fills. Upstream relied on Vulkan's robust buffer access, which Metal does not have. See [reads past a uniform binding's size](../../../docs/reference/shaders.md#reads-past-a-uniform-bindings-size), found on Paper Mario: The Thousand-Year Door (GitHub issue #1860).
|
||||
|
||||
The shader translation tool in `dm/gfx/tools/dmsh_xlate` references them to translate the original Switch shaders to SPIR-V.
|
||||
License: MIT, see `LICENSE.txt`. Upstream: <https://github.com/Ryubing>.
|
||||
+73
@@ -1797,6 +1797,11 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv
|
||||
return GenerateRawVectorLoad(context, operation);
|
||||
}
|
||||
|
||||
if (!isStore && operation.StorageKind == StorageKind.ConstantBuffer && TryGenerateBoundedUniformLoad(context, operation, out OperationResult bounded))
|
||||
{
|
||||
return bounded;
|
||||
}
|
||||
|
||||
SpvInstruction pointer = GetStoragePointer(context, operation, out AggregateType varType);
|
||||
|
||||
// nxnative: a load or store through a physical storage buffer pointer must state its alignment (a 32-bit word)
|
||||
@@ -1860,6 +1865,74 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv
|
||||
return new OperationResult(AggregateType.U32, context.CompositeExtract(context.TypeU32(), value, (SpvLiteralInteger)0));
|
||||
}
|
||||
|
||||
// nxnative: a read of a game uniform slot (TranslationFlags.MetalUniformBounds) gives 0 past the size the game bound, as Maxwell's constant buffers do. Metal has no
|
||||
// bounds of its own: the read reached the guest memory past the binding. Paper Mario: The Thousand-Year Door binds 16 bytes to a slot whose shader reads its light
|
||||
// count at byte 0x900 and loops over that many lights, and the GPU hung on what lay there (GitHub issue #1860). The size is the u32 the host puts in the size table
|
||||
// (Constants.NxUniformSizesBank); the word read is in bounds when its index is below the size in words. A read at a fixed offset keeps its constant address (Metal
|
||||
// reads it as before) and only its value is chosen; a read at a computed offset reads row 0 when out of bounds, so it reaches no memory past the binding either
|
||||
private static bool TryGenerateBoundedUniformLoad(CodeGenContext context, AstOperation operation, out OperationResult result)
|
||||
{
|
||||
result = OperationResult.Invalid;
|
||||
|
||||
if (operation.GetSource(0) is not AstOperand { Type: OperandType.Constant } bindingIndex ||
|
||||
!context.Properties.BoundedConstantBuffers.TryGetValue(bindingIndex.Value, out int sizeIndex))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (operation.SourcesCount != 4 || operation.GetSource(1) is not AstOperand { Type: OperandType.Constant } fieldIndex)
|
||||
{
|
||||
throw new InvalidOperationException($"A uniform slot read with {operation.SourcesCount} sources cannot be bounded (binding {bindingIndex.Value}).");
|
||||
}
|
||||
|
||||
StructureField field = context.Properties.ConstantBuffers[bindingIndex.Value].Type.Fields[fieldIndex.Value];
|
||||
AggregateType varType = field.Type & AggregateType.ElementTypeMask;
|
||||
SpvInstruction type = context.GetType(varType);
|
||||
SpvInstruction u32 = context.TypeU32();
|
||||
SpvInstruction s32 = context.TypeS32();
|
||||
|
||||
SpvInstruction sizePointer = context.AccessChain(
|
||||
context.TypePointer(StorageClass.Uniform, u32),
|
||||
context.ConstantBuffers[context.Properties.UniformSizesBinding],
|
||||
context.Constant(s32, 0),
|
||||
context.Constant(s32, sizeIndex >> 2),
|
||||
context.Constant(s32, sizeIndex & 3));
|
||||
SpvInstruction sizeWords = context.ShiftRightLogical(u32, context.Load(u32, sizePointer), context.Constant(u32, 2u));
|
||||
|
||||
IAstNode vecNode = operation.GetSource(2);
|
||||
IAstNode elemNode = operation.GetSource(3);
|
||||
SpvInstruction vec = context.Get(AggregateType.S32, vecNode);
|
||||
SpvInstruction elem = context.Get(AggregateType.S32, elemNode);
|
||||
bool fixedOffset = vecNode is AstOperand { Type: OperandType.Constant } && elemNode is AstOperand { Type: OperandType.Constant };
|
||||
|
||||
SpvInstruction word = fixedOffset
|
||||
? context.Constant(u32, (uint)(((AstOperand)vecNode).Value * 4 + ((AstOperand)elemNode).Value))
|
||||
: context.BitwiseOr(u32, context.ShiftLeftLogical(u32, context.Bitcast(u32, vec), context.Constant(u32, 2u)), context.Bitcast(u32, elem));
|
||||
SpvInstruction inBounds = context.ULessThan(context.TypeBool(), word, sizeWords);
|
||||
|
||||
if (!fixedOffset)
|
||||
{
|
||||
vec = context.Select(s32, inBounds, vec, context.Constant(s32, 0));
|
||||
}
|
||||
|
||||
SpvInstruction pointer = context.AccessChain(
|
||||
context.TypePointer(StorageClass.Uniform, type),
|
||||
context.ConstantBuffers[bindingIndex.Value],
|
||||
context.Get(AggregateType.S32, fieldIndex),
|
||||
vec,
|
||||
elem);
|
||||
SpvInstruction zero = varType switch
|
||||
{
|
||||
AggregateType.FP32 => context.Constant(type, 0f),
|
||||
AggregateType.U32 => context.Constant(type, 0u),
|
||||
AggregateType.S32 => context.Constant(type, 0),
|
||||
_ => throw new InvalidOperationException($"A uniform slot read of type {varType} cannot be bounded."),
|
||||
};
|
||||
|
||||
result = new OperationResult(varType, context.Select(type, inBounds, context.Load(type, pointer), zero));
|
||||
return true;
|
||||
}
|
||||
|
||||
private static SpvInstruction GetStoragePointer(CodeGenContext context, AstOperation operation, out AggregateType varType)
|
||||
{
|
||||
StorageKind storageKind = operation.StorageKind;
|
||||
|
||||
@@ -10,5 +10,11 @@ namespace Ryujinx.Graphics.Shader
|
||||
public const int NvnBaseVertexByteOffset = 0x640;
|
||||
public const int NvnBaseInstanceByteOffset = 0x644;
|
||||
public const int NvnDrawIndexByteOffset = 0x648;
|
||||
|
||||
// nxnative: uniform bounds (TranslationFlags.MetalUniformBounds). Uniform slots c[3] to c[16] are the game's (NVN's 14 a stage); the host gives the bound size of each
|
||||
// as a u32 in the table of bank 25 (dm/gfx/nvn/dmsh_abi.h DMSH_CBSIZE_BANK, kind DMSH_KIND_CBSIZE), slot c[s] at index s - 3, in four uint4
|
||||
public const int NxFirstUniformSlot = 3;
|
||||
public const int NxUniformSlots = 14;
|
||||
public const int NxUniformSizesBank = 25;
|
||||
}
|
||||
}
|
||||
+12
@@ -22,6 +22,18 @@ namespace Ryujinx.Graphics.Shader.StructuredIr
|
||||
// nxnative: a global memory access traced to no storage buffer goes through a physical storage buffer pointer (GlobalToStorage.TryGenerateRawStorageOp)
|
||||
public bool UsesPhysicalPointers { get; set; }
|
||||
|
||||
// nxnative: uniform bounds (TranslationFlags.MetalUniformBounds). The binding of each game uniform slot's buffer whose reads past the bound size give 0, with its
|
||||
// index in the size table, and the binding of that table (Constants.NxUniformSizesBank), -1 when no read is bounded
|
||||
private readonly Dictionary<int, int> _boundedConstantBuffers = new();
|
||||
public IReadOnlyDictionary<int, int> BoundedConstantBuffers => _boundedConstantBuffers;
|
||||
public int UniformSizesBinding { get; private set; } = -1;
|
||||
|
||||
public void AddBoundedConstantBuffer(int binding, int sizeIndex, int sizesBinding)
|
||||
{
|
||||
_boundedConstantBuffers[binding] = sizeIndex;
|
||||
UniformSizesBinding = sizesBinding;
|
||||
}
|
||||
|
||||
public ShaderProperties()
|
||||
{
|
||||
_constantBuffers = new Dictionary<int, BufferDefinition>();
|
||||
|
||||
+34
-2
@@ -58,6 +58,9 @@ namespace Ryujinx.Graphics.Shader.Translation
|
||||
|
||||
public ResourceReservations Reservations { get; }
|
||||
|
||||
// nxnative: TranslationFlags.MetalUniformBounds
|
||||
public bool UniformBounds { get; set; }
|
||||
|
||||
public ResourceManager(ShaderStage stage, IGpuAccessor gpuAccessor, ResourceReservations reservations = null)
|
||||
{
|
||||
_gpuAccessor = gpuAccessor;
|
||||
@@ -66,8 +69,8 @@ namespace Ryujinx.Graphics.Shader.Translation
|
||||
_stage = stage;
|
||||
_stagePrefix = GetShaderStagePrefix(stage);
|
||||
|
||||
// Constant buffer banks 0-17 (Maxwell's), and 24: NVN2's push constants (c[24])
|
||||
_cbSlotToBindingMap = new SetBindingPair[25];
|
||||
// Constant buffer banks 0-17 (Maxwell's), 24: NVN2's push constants (c[24]), and 25: the uniform slots' sizes (Constants.NxUniformSizesBank)
|
||||
_cbSlotToBindingMap = new SetBindingPair[Constants.NxUniformSizesBank + 1];
|
||||
// Storage buffers the global-to-storage pass found: the stage's storage buffer table and, for compute, its uniform buffer address table (NVN 16 + 16 slots)
|
||||
_sbSlotToBindingMap = new SetBindingPair[32];
|
||||
_cbSlotToBindingMap.AsSpan().Fill(new(-1, -1));
|
||||
@@ -193,6 +196,35 @@ namespace Ryujinx.Graphics.Shader.Translation
|
||||
_cbSlotToBindingMap[slot] = setAndBinding;
|
||||
string slotNumber = slot.ToString(CultureInfo.InvariantCulture);
|
||||
AddNewConstantBuffer(setAndBinding.SetIndex, setAndBinding.Binding, $"{_stagePrefix}_c{slotNumber}");
|
||||
|
||||
// nxnative: a game uniform slot's reads are bounded by the size the host puts in the size table (Constants.NxUniformSizesBank)
|
||||
if (UniformBounds && slot >= Constants.NxFirstUniformSlot && slot < Constants.NxFirstUniformSlot + Constants.NxUniformSlots)
|
||||
{
|
||||
Properties.AddBoundedConstantBuffer(setAndBinding.Binding, slot - Constants.NxFirstUniformSlot, GetUniformSizesBinding());
|
||||
}
|
||||
}
|
||||
|
||||
return setAndBinding.Binding;
|
||||
}
|
||||
|
||||
// nxnative: the size table, bank Constants.NxUniformSizesBank: one u32 a game uniform slot, in uint4 data[4] (a std140 array of u32 would take 16 bytes an element)
|
||||
private int GetUniformSizesBinding()
|
||||
{
|
||||
int slot = Constants.NxUniformSizesBank;
|
||||
SetBindingPair setAndBinding = _cbSlotToBindingMap[slot];
|
||||
|
||||
if (setAndBinding.Binding < 0)
|
||||
{
|
||||
setAndBinding = _gpuAccessor.CreateConstantBufferBinding(slot);
|
||||
_cbSlotToBindingMap[slot] = setAndBinding;
|
||||
|
||||
StructureType type = new(new[]
|
||||
{
|
||||
new StructureField(AggregateType.Array | AggregateType.Vector4 | AggregateType.U32, "data", (Constants.NxUniformSlots + 3) / 4),
|
||||
});
|
||||
|
||||
Properties.AddOrUpdateConstantBuffer(new(BufferLayout.Std140, setAndBinding.SetIndex, setAndBinding.Binding, $"{_stagePrefix}_c{slot.ToString(CultureInfo.InvariantCulture)}", type));
|
||||
SetUsedConstantBufferBinding(setAndBinding.Binding);
|
||||
}
|
||||
|
||||
return setAndBinding.Binding;
|
||||
|
||||
+3
@@ -15,5 +15,8 @@ namespace Ryujinx.Graphics.Shader.Translation
|
||||
// Ampere (sm_86) machine code, as NVN2 (Switch 2) ships it: a 0x80-byte shader header (SPH version 4, its first 0x50 bytes laid out as version 3)
|
||||
// and 128-bit instructions, decoded and emitted by the Ampere frontend.
|
||||
Ampere = 1 << 4,
|
||||
// Offline Metal: a read of a game uniform slot (c[3] to c[16]) past the size the game bound gives 0, as Maxwell's constant buffers do; Metal has no bounds
|
||||
// of its own, so the read reached the guest memory past the binding (Constants.NxUniformSizesBank)
|
||||
MetalUniformBounds = 1 << 5,
|
||||
}
|
||||
}
|
||||
+2
@@ -397,6 +397,8 @@ namespace Ryujinx.Graphics.Shader.Translation
|
||||
{
|
||||
ResourceManager resourceManager = new(Definitions.Stage, GpuAccessor, GetResourceReservations());
|
||||
|
||||
resourceManager.UniformBounds = Options.Flags.HasFlag(TranslationFlags.MetalUniformBounds); // nxnative: before any uniform slot gets its binding
|
||||
|
||||
if (IsTransformFeedbackEmulated)
|
||||
{
|
||||
StructureType tfeDataStruct = new(new StructureField[]
|
||||
|
||||
@@ -136,6 +136,13 @@ class Host(unittest.TestCase):
|
||||
self.assertEqual(int(m.group(1)), abi.C2_SEP_SLOTS)
|
||||
self.assertEqual(abi.C2_ROW, 8)
|
||||
|
||||
def test_uniform_bounds_agree(self): # the translator's size table (Ryujinx Constants.cs) is the bank and the slots the host fills (nvn_mtl.m NVN_RB_CBSIZE)
|
||||
src = (REPO / 'dm/third_party/ryujinx/src/Ryujinx.Graphics.Shader/Constants.cs').read_text()
|
||||
got = {n: int(v) for n, v in re.findall(r'public const int (Nx\w+) = (\d+);', src)}
|
||||
self.assertEqual(got, {'NxFirstUniformSlot': 3, 'NxUniformSlots': abi.CBSIZE_SLOTS, 'NxUniformSizesBank': abi.CBSIZE_BANK})
|
||||
self.assertEqual(abi.CBSIZE_SLOTS, 16 - 3 + 1, 'uniform slots c[3] to c[16], as dmsh_build.py reflects them')
|
||||
self.assertIn('TranslationFlags.MetalUniformBounds', (REPO / 'dm/gfx/tools/dmsh_xlate/Program.cs').read_text())
|
||||
|
||||
|
||||
class Ratchet(unittest.TestCase):
|
||||
def test_no_new_abi_literals(self):
|
||||
|
||||
@@ -18,7 +18,7 @@ import dmsh_atomic # noqa: E402
|
||||
import dmsh_fetch # noqa: E402
|
||||
import dmsh_side # noqa: E402
|
||||
|
||||
ns: dict[str, Any] = {'re': re, 'collections': collections, 'dmsh_side': dmsh_side} # dmsh_build.py is a script that runs a build when imported
|
||||
ns: dict[str, Any] = {'re': re, 'collections': collections, 'dmsh_side': dmsh_side, 'dmsh_fetch': dmsh_fetch} # dmsh_build.py is a script that runs a build when imported
|
||||
exec(compile(ast.Module(body=[n for n in ast.parse((TOOLS / 'dmsh_build.py').read_text()).body if isinstance(n, ast.FunctionDef) and n.name in {'attributes', 'in_word', 'has_word', 'int_outputs', 'fs_uint'}], type_ignores=[]), 'dmsh_build', 'exec'), ns)
|
||||
attributes, has_word, fs_uint = ns['attributes'], ns['has_word'], ns['fs_uint']
|
||||
|
||||
|
||||
@@ -1007,6 +1007,7 @@ One line per symptom in the [subsystem references](../reference/): what you see
|
||||
- `image atomics: unsupported or overflowing IMG extent` at the first dispatch, despite a valid four-byte counter buffer. → [Buffer image reflection keeps its texture type](../reference/shaders.md#buffer-image-reflection-keeps-its-texture-type)
|
||||
- `[RED] image atomics on a texture Metal cannot run them on`, and whatever the shader computes through them is lost: its writes go to a sink. → [Image atomics on a 32-bit colour texture](../reference/shaders.md#image-atomics-on-a-32-bit-colour-texture)
|
||||
- Metal shader validation reports invalid image-atomic stores even with an image-sized scratch buffer; without validation, GPU page faults can freeze rendering. → [Bounds of image atomics](../reference/shaders.md#bounds-of-image-atomics)
|
||||
- the GPU hangs (Metal command-buffer timeouts, `GPU access revoked`, exit 70; on the Mac WindowServer can lose its watchdog check-in and the session restarts) or a draw reads garbage, where a shader reads a uniform slot further than the game bound it. No `[RED]` line. → [Reads past a uniform binding's size](../reference/shaders.md#reads-past-a-uniform-bindings-size)
|
||||
- the NSP script stops with `captured only 0 run-time shaders` although the game reaches its frame loop with precompiled shaders. → [A GLSL language preamble is not a complete shader](../reference/shaders.md#a-glsl-language-preamble-is-not-a-complete-shader)
|
||||
- shaders missing from the map that no game file holds. → [Built-in shaders compiled with the game's own GLSLC](../reference/shaders.md#built-in-shaders-compiled-with-the-games-own-glslc)
|
||||
- the NSP script stops with `captured only 0 run-time shaders` while the capture run reaches the game's frame loop and runs to the end of its 30 s. → [A run-time compile that waits for a button press](../reference/shaders.md#a-run-time-compile-that-waits-for-a-button-press)
|
||||
|
||||
@@ -1769,6 +1769,14 @@ Finding, keying and translating shaders (`dm/gfx/tools/shader_split.py`, `dmsh_b
|
||||
- **Found on:** [Pokémon Legends: Z-A](../../dm/games/0100F43008C44000/README.md#rendering) ([PR #178](https://github.com/seedds/nxnative/pull/178)); [SHIN MEGAMI TENSEI V: Vengeance](../../dm/games/010069C01AB82000/README.md), whose two buffer-image counter shaders dispatched at boot consume their returned values.
|
||||
- **Check:** `dm/tools/tests/test_image_atomic_bounds.py`. Portable tests check the MSL version choice and the rejection of the pointer form. With `DMSH_TEST_XLATE` set to a rebuilt translator (and `spirv-val` on `PATH`; spirv-cross is the in-repo build) the synthetic shaders are translated, the guard's dataflow is checked in the SPIR-V (the size query and comparison dominate the atomic, the phi carries zero on the invalid edge), and the MSL is produced; `DMSH_TEST_METAL=1` compiles and links it (`DMSH_TEST_METAL_SDKS=macosx,iphoneos` for both SDKs) and `DMSH_TEST_GPU=1` runs the returning fixtures (above). Changing this path changes the chain version: rebuild the translator and update the lock before building shaders.
|
||||
|
||||
### Reads past a uniform binding's size
|
||||
|
||||
- **Symptom:** the GPU hangs (Metal command-buffer timeouts, `GPU access revoked`, exit 70; on the Mac WindowServer can lose its watchdog check-in and the session restarts) or a draw reads garbage, where a shader reads a uniform slot further than the game bound it. No `[RED]` line.
|
||||
- **Cause:** Maxwell bounds every constant buffer read by the size the game bound (`nvnCommandBufferBindUniformBuffer`): past it a read gives 0, and games rely on that. The translator declared each slot as `float4 _m0[4096]` behind a plain pointer, and Metal has no bounds of its own, so such a read reached the guest memory after the binding. Paper Mario: The Thousand-Year Door's `forward.bfsha` variant `f1e0f08cc43e21e3` reads its light count at byte 0x900 of uniform slot 11 and loops over that many lights, filling a 19-entry local array and reading c14 at `0x440 + 0x30 i`; the game binds 2,384 bytes to the slot for some materials and 16 bytes for others (501 of 1,024 bindings sampled in Peach's invisibility-potion scene). On the 16-byte bindings the count was whatever lay past them.
|
||||
- **Fix:** in the chain, for every game. The translator (`TranslationFlags.MetalUniformBounds`, Metal only) reads every game uniform slot (c[3] to c[16]) through a guard: the word is read when its index is below the slot's size in words, else the value is 0 (`TryGenerateBoundedUniformLoad` in `CodeGen/Spirv/Instructions.cs`). The sizes come from a table in a bank of its own, `DMSH_CBSIZE_BANK` (25), a u32 for each of the 14 slots in four `uint4` (binding kind `cbsize`, `NVN_RB_CBSIZE`), which the host fills from the current bindings at each argument-buffer encode, 0 for an unbound slot (whose reads already go to [the zero bank](rendering.md#an-unbound-uniform-slot-reads-the-zero-bank)), at most 64 KiB; a binding change re-encodes the block, since the size is part of the bind. A read at a fixed offset keeps its constant address and only its value is chosen (`(576u < (sizes[2].w >> 2u)) ? c14[144].x : 0.0`); a read at a computed offset also reads row 0 when out of bounds, so no read reaches memory past the binding. The driver segments (c0, c2), the shader's own c1, NVN2's push constants (c[24]) and compute's uniform pointers (`ubo_ptr`, global memory on Maxwell too) are not bounded. The build's analyses that look for a uniform word (`dmsh_fetch.py` `_frag_pos`, `dmsh_build.py` `raster_facts` and `int_outputs`) read the guarded form bare (`dmsh_fetch.unguard`): the host takes such a word only from inside its binding (`ubo_float` refuses a word past the size), where the guard chooses the read. `cb_extent.tsv` also gives a slot it cannot bound its highest fixed-offset read (`f<reg>:<bytes>`), and the host logs the first shaders bound shorter than that with a running count (`uniform slot N of shader K (stage S) is bound with B bytes and read up to byte E at a fixed offset`).
|
||||
- **Found on:** [Paper Mario: The Thousand-Year Door](../../dm/games/0100ECD018EBE000/README.md#rendering) ([GitHub issue #1860](https://github.com/seedds/nxnative/issues/1860)): the reporter found the variant and the short bindings, and padding those bindings with zeros let Peach's scene through on an M3 Ultra Mac and an M4 iPad Pro.
|
||||
- **Check:** `dm/tools/tests/test_dmsh_abi.py` `test_uniform_bounds_agree` (the translator's bank and slots are the header's). On the shader above, the chain without the guard and with it give the same reflection apart from the size table, and the same `cb_extent.tsv` row (`0:480 2:480 3:32 4:144 f11:2368`). `regress.py check --quick` against the chain without the guard: NieR:Automata (1,225 shaders, 1,171 changed) and Return of the Obra Dinn (1,272, 1,134 changed), none newly failing, no interface or `[RED]` change, the same frames reached and the same scenes in the screenshots; neither route binds a slot shorter than its shader reads. The cost, `bench.py` on NieR:Automata's opening flight (M6, two runs each, 60 s window): GPU time p50 6.43 → 6.53 ms (+1.6%), p95 9.12 → 9.70 ms (+6.4%), frame time unchanged at 60 fps. Changing this path changes the chain version: rebuild the translator, update the lock and rebuild the shaders.
|
||||
|
||||
## Shaders compiled at run time
|
||||
|
||||
### A GLSL language preamble is not a complete shader
|
||||
|
||||
Reference in new issue
Block a user