Bounded uniform reads are written as select(0, read, cond), the translator's own load and choice, not a branch for each: OCTOPATH TRAVELER's dither-fading trees no longer show blue, green and white blocks on an M1 (chain eaa843a79149, PR #2127)

The translator bounds a uniform read with OpLoad then OpSelect, but spirv-cross writes OpSelect on a scalar as a conditional expression and forwards the load into it, cond ? read : 0, which Metal's compiler turns into a branch, a load inside it and a phi (its LLVM IR at -O1 and -O2). On an M1 Pro (macOS 26) that form gives OCTOPATH TRAVELER's tree material (pixel shader 040208cd98c2ac2f) a wrong volumetric lightmap word while every guard is true; the lighting makes NaN of it and depth of field spreads it into blocks. Bisected to 26062f9e by the PR's author (5 against 0 of 96 shots on the dog route in S'warkii; 0 of 192 with the fixed-offset reads as selects). Which step of Apple's compiler fails is not known: a platform fault the select form avoids.

- dmsh_fetch.select_guards: every bounded read as a select, at a fixed offset and at a computed one (whose index already chooses row 0 when out of bounds, so the load stays inside the binding); a bounded read it cannot write as a select is an error, so the branches cannot come back unseen. One guard pattern for it and unguard, which reads both forms
- dmsh_build.py calls it on each spirv-cross output: the shader, the geometry stage and its reader (uniform bounds rewrite failed)
- Tests: test_dmsh_fetch UniformBounds (the forms spirv-cross writes, the same unguard result, the error for an unknown form, Mac and iPhone compiles)
- docs/reference/shaders.md: Bounded uniform reads written as select; OCTOPATH TRAVELER's note; symptom index regenerated

Three NieR:Automata shaders at -O1: 454 -> 118, 636 -> 146 and 90 -> 8 conditional branches. Regression (quick, against 25c2546e): NieR:Automata, 1,171 shaders changed in MSL only, none failing, no reflection or RED change, the same frames reached. Return of the Obra Dinn not run. Not run on an M1 in this form: the author's retest is open.

Co-authored-by: sid350 <[email protected]>
This commit is contained in:
seeddsandsid350 committed 2026-11-10 21:39:20 +08:00
1 parent 156de5a11a
commit 918e9f34dc
7 files changed
+108 -11

No files matched your search

+1
View File
@@ -67,6 +67,7 @@ General changes first needed here; each applies to every game:
- **Provisional profiles:** Unreal's 64 GB alias layout only with virtual address memory (`profile_guess.py`): [Unreal's engine address region](../../../docs/reference/memory.md#unreals-engine-address-region-and-its-options).
- **NVN:** `nvnTextureBuilderGetSparseTileLayout` / `nvnTextureGetSparseTileLayout`: [The sparse tile layout of a texture](../../../docs/reference/nvn-objects.md#the-sparse-tile-layout-of-a-texture); every virtual pool with a range of its own until its first mapping decides: [Virtual pools of one texture each](../../../docs/reference/nvn-objects.md#virtual-pools-of-one-texture-each-mapped-before-and-after-the-texture); sparse textures' block height: [Sparse textures take the block height of their 64 KB tile](../../../docs/reference/rendering.md#sparse-textures-take-the-block-height-of-their-64-kb-tile).
- **Audio:** the update lock without `SdkMutexType`: [No `SdkMutexType` in SDK 3](../../../docs/reference/audio.md#no-sdkmutextype-in-sdk-3).
- **Shaders:** blocks on dither-fading trees on an M1, from a branch for each bounded uniform read: [Bounded uniform reads written as select](../../../docs/reference/shaders.md#bounded-uniform-reads-written-as-select).
- **Frame rate:** Unreal console variables registered by inlined static constructors, from a page base made far before the name: [Unreal's frame limit and present interval, found by name](../../../docs/reference/frame-rate.md#unreals-frame-limit-and-present-interval-found-by-name).
## Open
+1 -1
View File
@@ -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 "cb2e91c138e3"
#define DMSH_CHAIN "eaa843a79149"
+51 -3
View File
@@ -257,6 +257,10 @@ def guarded(src): # FS_POS with its two c[6] words bounded, and the size table
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)
# A read at a computed offset, as spirv-cross writes the translator's: the size comparison a value of its own, which chooses row 0 for the index and 0 for the value when out of bounds
COMPUTED = ('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)
class UniformBounds(unittest.TestCase):
def test_unguard(self):
read = '(*spvDescriptorSet0.vp_c5)._m0[29].y'
@@ -267,9 +271,53 @@ class UniformBounds(unittest.TestCase):
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)
self.assertEqual(dmsh_fetch.unguard(COMPUTED), COMPUTED)
self.assertEqual(dmsh_fetch.unguard(dmsh_fetch.select_guards(COMPUTED)), dmsh_fetch.select_guards(COMPUTED))
def test_select_guards(self): # every bounded read as a load and a select (GitHub PR #2127); unguard reads both forms the same
read = '(*spvDescriptorSet0.vp_c5)._m0[29].y'
tern = GUARD.format(w=117, r=read).replace('fp_c', 'vp_c'); cond = tern[1:-1].split(' ? ')[0]
for why, src, want in (('in parentheses', 'float _1 = _2 * %s;' % tern, 'float _1 = _2 * select(0.0, %s, %s);' % (read, cond)),
('a function argument', 'float _1 = fma(_2, %s, _3);' % tern[1:-1], 'float _1 = fma(_2, select(0.0, %s, %s), _3);' % (read, cond)),
('bit-cast', 'int _1 = as_type<int>(%s) << 6;' % tern[1:-1], 'int _1 = as_type<int>(select(0.0, %s, %s)) << 6;' % (read, cond)),
('an unsigned word', 'uint _1 = %s;' % tern.replace('0.0)', '0u)'), 'uint _1 = select(0u, %s, %s);' % (read, cond)),
('the other side of a choice', 'float _1 = _2 ? 0.0 : %s;' % tern, 'float _1 = _2 ? 0.0 : select(0.0, %s, %s);' % (read, cond)),
('two in one call', 'float _1 = fma(%s, %s, _3);' % (tern[1:-1], tern[1:-1]), 'float _1 = fma(select(0.0, {0}, {1}), select(0.0, {0}, {1}), _3);'.format(read, cond))):
with self.subTest(why=why):
got = dmsh_fetch.select_guards(src)
self.assertEqual(got, want)
self.assertEqual(dmsh_fetch.unguard(got), dmsh_fetch.unguard(src))
self.assertEqual(dmsh_fetch.select_guards(got), got, 'a second pass changes nothing')
def test_select_guards_at_a_computed_offset(self): # the index keeps its row-0 choice, so the load is inside the binding without a branch
row = '(*spvDescriptorSet0.fp_c14)._m0[_5 ? _3 : 0]'
self.assertEqual(dmsh_fetch.select_guards(COMPUTED).split('\n')[1], 'float _6 = select(0.0, %s[_4], _5);' % row)
for why, a, b in (('in parentheses', 'float _6 = _5 ? %s[_4] : 0.0;' % row, 'float _6 = _7 * (_5 ? %s[_4] : 0.0);' % row),
('a fixed component', '[_4] : 0.0;', '.z : 0.0;'), ('an unsigned word', '[_4] : 0.0;', '[_4] : 0u;')):
with self.subTest(why=why):
got = dmsh_fetch.select_guards(COMPUTED.replace(a, b))
self.assertNotIn(' : 0.0', got); self.assertNotIn(' : 0u', got); self.assertEqual(got.count('select('), 1)
other = COMPUTED + '\nfloat _9 = _8 ? (*spvDescriptorSet0.fp_c14)._m0[_8 ? _3 : 0][_4] : 0.0;' # _8 is no size comparison: the game's own choice
self.assertTrue(dmsh_fetch.select_guards(other).endswith(other.split('\n')[2]))
def test_select_guards_leaves_none(self): # a bounded read in a form it does not know is an error, not a branch left in the shader
tern = GUARD.format(w=117, r='(*spvDescriptorSet0.fp_c5)._m0[29].y')
for why, src in (('another zero', 'float _1 = %s;' % tern.replace(': 0.0', ': -0.0')),
('a read of two components', 'float2 _1 = %s;' % tern.replace('.y :', '.xy :')),
('a computed offset with another index', COMPUTED.replace('[_5 ? _3 : 0]', '[_3]')),
('a size comparison used as a choice elsewhere', COMPUTED + '\nfloat _9 = _5 ? _7 : 0.0;')):
with self.subTest(why=why):
with self.assertRaisesRegex(ValueError, 'not written as a select'): dmsh_fetch.select_guards(src)
self.assertEqual(dmsh_fetch.select_guards('float _1 = _2 ? _3 : 0.0;'), 'float _1 = _2 ? _3 : 0.0;', 'no descriptor set')
def test_select_guards_compile(self):
v, _ = dmsh_fetch.fold(dmsh_fetch.select_guards(guarded(FS_POS)), BINDINGS)
self.assertEqual(v.count('select(0.0, (*spvDescriptorSet0.fp_c3)._m0[6].'), 2); self.assertNotIn(' ? (*spvDescriptorSet0.fp_c3)', v)
with tempfile.TemporaryDirectory() as d:
for sdk in ('macosx', 'iphoneos'):
with self.subTest(sdk=sdk):
try: compile_lib(v, pathlib.Path(d), 'selected_' + sdk, sdk)
except subprocess.CalledProcessError as e: self.fail(e.stderr)
def test_compiles_on_both_platforms(self):
v, _ = dmsh_fetch.fold(guarded(FS_POS), BINDINGS)
+8 -2
View File
@@ -680,7 +680,9 @@ def geometry_finish(key, w, j, c1):
dmsh_geometry.flatten_sets(spv)
r = subprocess.run([SPIRV_CROSS, *dmsh_atomic.cross_args(XC, spv), spv], capture_output=True, text=True)
if r.returncode: return 'geometry MSL failed', r.stderr.strip()[:160], None
plain = dmsh_geometry.topology_pointer(dmsh_reflect.pool_arrays(dmsh_rewrite.precise(dmsh_atomic.check_msl(r.stdout))))
try: selected = dmsh_fetch.select_guards(dmsh_rewrite.precise(dmsh_atomic.check_msl(r.stdout))) # bounded uniform reads as selects (see dmsh_fetch.select_guards)
except ValueError as e: return 'geometry MSL failed', str(e)[:160], None
plain = dmsh_geometry.topology_pointer(dmsh_reflect.pool_arrays(selected))
src = dmsh_geometry.capture_input(plain)
res = json.load(open(os.path.join(w, k + '.res.json')))
refl = {'key': key + '_bg' + str(t), 'route': 'B', 'chain': CHAIN, 'dm_ctl': key,
@@ -710,7 +712,9 @@ def geometry_finish(key, w, j, c1):
spv = os.path.join(w, k + '.reader.spv'); dmsh_geometry.flatten_sets(spv)
r = subprocess.run([SPIRV_CROSS, *dmsh_atomic.cross_args(XC, spv), spv], capture_output=True, text=True)
if r.returncode: return 'geometry reader failed', r.stderr.strip()[:160], None
reader = dmsh_entry.vs_layer(dmsh_entry.vs_init(dmsh_geometry.reader(dmsh_reflect.pool_arrays(dmsh_rewrite.precise(dmsh_atomic.check_msl(r.stdout))))))
try: selected = dmsh_fetch.select_guards(dmsh_rewrite.precise(dmsh_atomic.check_msl(r.stdout)))
except ValueError as e: return 'geometry reader failed', str(e)[:160], None
reader = dmsh_entry.vs_layer(dmsh_entry.vs_init(dmsh_geometry.reader(dmsh_reflect.pool_arrays(selected))))
analysis, full = dmsh_entry.vs_depth(reader)
meta = {'key': key + '_bgv', 'route': 'B', 'chain': CHAIN, 'dm_ctl': key,
'stage': 'vs', 'entry': 'main0', 'entry_z': 'main0_z', 'msl_entry_kind': 'vertex',
@@ -751,6 +755,8 @@ def finish(key, w, j, c1):
try: src = dmsh_atomic.check_msl(src)
except ValueError as e: return 'image atomic MSL failed', str(e), None
src = dmsh_rewrite.precise(src) # min / max / clamp with Maxwell's NaN results (see precise)
try: src = dmsh_fetch.select_guards(src) # bounded uniform reads as a load and a select, as the translator means them, not a branch for each (see dmsh_fetch.select_guards)
except ValueError as e: return 'uniform bounds rewrite failed', str(e)[:160], None
src = dmsh_rewrite.mul_extended(src) # scalar extended products without the optnone wrapper (see mul_extended)
try: src = dmsh_rewrite.gather_offsets(src) # four gathers instead of a wrapper's loop over their offsets (see gather_offsets)
except ValueError as e: return 'gather offsets rewrite failed', str(e)[:160], None
+37 -4
View File
@@ -48,12 +48,45 @@ _UNI = re.compile(r'\(\*spvDescriptorSet0\.fp_c(\d+)\)\._m0\[(\d+)\]\.([xyzw])')
# 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_reflect.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
_GSIZE = r'\(\(\*spvDescriptorSet0\.[a-z]+_c%d\)\._m0\[\d\]\.[xyzw] >> 2u\)' % abi.CBSIZE_BANK # a slot's size in words
_GCOND = r'\(\d+u < %s\)' % _GSIZE
_GREAD = r'\(\*spvDescriptorSet0\.[a-z]+_c\d+\)\._m0\[\d+\]\.[xyzw]'
_GZERO = r'0(?:\.0|u)?'
def _gchoice(cond, read): # cond ? read : 0 as spirv-cross writes it, in parentheses (those after a name or > are a call's) or not as the expression around it needs
return re.compile('|'.join(form % (n, cond, n, read % n if '%s' in read else read, n, _GZERO) for n, form in
((1, r'(?<![\w>])\((?P<q%d>%s) \? (?P<r%d>%s) : (?P<z%d>%s)\)'), (2, r'(?P<q%d>%s) \? (?P<r%d>%s) : (?P<z%d>%s)(?![\w.])'))))
_GUARDED = _gchoice(_GCOND, _GREAD)
_GSELECT = re.compile(r'select\(%s, (%s), %s\)' % (_GZERO, _GREAD, _GCOND)) # as select_guards writes it
def unguard(msl):
return _GUARDED.sub(lambda m: m.group(1) or m.group(2), msl) if 'spvDescriptorSet0' in msl else msl
if 'spvDescriptorSet0' not in msl: return msl
return _GSELECT.sub(lambda m: m.group(1), _GUARDED.sub(lambda m: m.group('r1') or m.group('r2'), msl))
# The translator's bounded read is a load and a choice (OpLoad, then OpSelect: the word is read wherever the size says, and only its value is chosen), but spirv-cross writes OpSelect
# on a scalar as a conditional expression and forwards the load into it, cond ? read : 0, which reads only when the condition holds: Metal's compiler makes a branch, a load inside it
# and a phi of every bounded read (seen in its LLVM IR at -O1 and -O2), where select(0, read, cond) is one load and a select. select_guards writes every bounded read as that select,
# the translator's own meaning. At a fixed offset the read is the one Metal made before reads were bounded; at a computed offset its index is row 0 when out of bounds
# (bool _5 = word < size; _5 ? c[_5 ? _3 : 0][_4] : 0.0), so it stays inside the binding without the branch.
# The branches are also what an M1's compiler gets wrong (GitHub PR #2127, macOS 26 on an M1 Pro): OCTOPATH TRAVELER's tree material (pixel shader 040208cd98c2ac2f) wrote a wrong
# volumetric lightmap word to G-buffer target 5 whenever a tree dither-faded, with every guard true; the lighting made NaN of it and depth of field spread that into blue, green and
# white blocks. Which compiler step fails is not known (the same source was right at -O0, without the guards and with select; not seen on newer Macs or an iPhone).
# A bounded read select_guards cannot write as a select is an error (ValueError), so a change in what spirv-cross writes cannot bring the branches back unseen
_GBOOL = re.compile(r'\bbool (_\d+) = [^;\n]* < %s;' % _GSIZE) # a computed offset's condition, a value of its own: the read's index and its choice both use it
_GROW = _gchoice(r'_\d+', r'\(\*spvDescriptorSet0\.[a-z]+_c\d+\)\._m0\[(?P<i%s>_\d+) \? [^\]\n]+ : 0\](?:\[[^\]\n]+\]|\.[xyzw])')
_GLEFT = re.compile(r'%s\) \?' % _GSIZE)
def select_guards(msl):
if 'spvDescriptorSet0' not in msl: return msl
bools = set(_GBOOL.findall(msl))
def select(m):
n = '1' if m.group('q1') else '2'; c = m.group('q' + n)
if m.re is _GROW and (c not in bools or m.group('i' + n) != c): return m.group(0)
return 'select(%s, %s, %s)' % (m.group('z' + n), m.group('r' + n), c)
msl = _GUARDED.sub(select, msl)
if bools: msl = _GROW.sub(select, msl)
left = _GLEFT.search(msl) or next((m for m in re.finditer(r'(?<!\[)\b(_\d+) \?', msl) if m.group(1) in bools), None)
if left: raise ValueError('a bounded uniform read is not written as a select: ' + msl[msl.rfind('\n', 0, left.start()) + 1:left.end() + 100].split('\n')[0].strip()[:160])
return 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):
+1
View File
@@ -1036,6 +1036,7 @@ One line per symptom in the [subsystem references](../reference/): what you see
- `[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)
- on an M1 Pro (macOS 26), blue, green and white blocks for one or two frames on trees that dither-fade (OCTOPATH TRAVELER's S'warkii, walking behind a tree); a texture dump shows NaN pixels in the scene colour and holes in the normal G-buffer target, which depth of field spreads into blocks. Not seen on an iPhone or on newer Macs. On every GPU, a branch for each uniform word a shader reads. → [Bounded uniform reads written as select](../reference/shaders.md#bounded-uniform-reads-written-as-select)
- 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)
+9 -1
View File
@@ -1819,10 +1819,18 @@ Finding, keying and translating shaders (`dm/gfx/tools/shader_split.py`, `dmsh_b
- **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_reflect.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`).
- **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 (`select(0.0, c14[144].x, (576u < (sizes[2].w >> 2u)))`, [written as a select](#bounded-uniform-reads-written-as-select)); a read at a computed offset also reads row 0 when out of bounds, so no such 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_reflect.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.
### Bounded uniform reads written as select
- **Symptom:** on an M1 Pro (macOS 26), blue, green and white blocks for one or two frames on trees that dither-fade (OCTOPATH TRAVELER's S'warkii, walking behind a tree); a texture dump shows NaN pixels in the scene colour and holes in the normal G-buffer target, which depth of field spreads into blocks. Not seen on an iPhone or on newer Macs. On every GPU, a branch for each uniform word a shader reads.
- **Cause:** the translator's bounded read ([Reads past a uniform binding's size](#reads-past-a-uniform-bindings-size)) is a load and a choice, OpLoad then OpSelect, but spirv-cross writes OpSelect on a scalar as a conditional expression and forwards the load into it: `cond ? read : 0.0`, which reads only when the condition holds. Metal's compiler makes a branch, a load inside it and a phi of each (its LLVM IR at -O1 and -O2, `xcrun metal -S -emit-llvm`), where `select(0.0, read, cond)` is one load and a select with no branch. The M1's compiler gets that form wrong in OCTOPATH TRAVELER's tree material (pixel shader `040208cd98c2ac2f`): its volumetric lightmap word (G-buffer target 5) comes out wrong although every guard is true (all its bindings are full size, and a size table of 64 KiB for every slot changes nothing), and the lighting turns it into NaN. The same shader at -O0, without the guards, or with them as `select` is right; `-fno-fast-math` does not help; only removing the guards of the whole lightmap block (c3[174..177]) fixes it, not either half. Found by bisecting to `26062f9e` (5 against 0 of 96 shots), then the shaders, then the guards inside the one shader. **Open:** which step of Apple's compiler fails is not known, nor whether it is the Metal front end of macOS 26, which built those libraries, or the M1's GPU compiler: a platform fault that the select form avoids and does not fix.
- **Fix:** every game, a chain change. `dmsh_fetch.select_guards`, called by `dmsh_build.py` on each spirv-cross output (the shader, the geometry stage and its reader), writes every bounded read as `select(0, read, cond)`, the translator's own meaning. At a fixed offset the load is the one Metal made before reads were bounded. At a computed offset the index already chooses row 0 when out of bounds (`bool _5 = word < size; select(0.0, c14[_5 ? _3 : 0][_4], _5)`), so the load stays inside the binding without the branch. A bounded read it cannot write as a select fails the shader (`uniform bounds rewrite failed`), so a change in what spirv-cross writes cannot bring the branches back unseen. `unguard` reads both forms.
- **Found on:** [OCTOPATH TRAVELER](../../dm/games/010057D006492000/README.md) ([GitHub PR #2127](https://github.com/seedds/nxnative/pull/2127): the bisection, the shader and the select form, on an M1 Pro).
- **Check:** `python3 dm/gfx/tests/test_dmsh_fetch.py UniformBounds` (the forms spirv-cross writes at fixed and computed offsets, the same `unguard` result, the error for an unknown form, Mac and iPhone compiles). On the M1 Pro, the dog route in S'warkii (walking up and down behind the tree left of the dog by the weapon shop): 5 to 14 of 96 shots with blocks before, 0 of 192 with the fixed-offset reads as selects.
## Shaders compiled at run time
### A GLSL language preamble is not a complete shader