From cd60a025a24458fa58554322363b32726ee5c8ae Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Fri, 27 Nov 2026 23:31:03 +0000 Subject: [PATCH 1/4] startup: lower pixel image descriptor size fields A pixel stage can read the exact GFX10 width, height and 3D depth fields of an image descriptor as numbers. Other words and uses stay refused. Fixes part of #2022 Co-authored-by: SimSalabimse --- .github/workflows/windows.yml | 1 + AGENTS.md | 1 + CMakeLists.txt | 3 + docs/experiments.md | 8 + .../startup_gfx2hlsl_image_desc_word_check.py | 223 +++++++++++++++++ tools/startup/gfx2hlsl.py | 233 +++++++++++++++++- 6 files changed, 461 insertions(+), 8 deletions(-) create mode 100644 tests/startup_gfx2hlsl_image_desc_word_check.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index 3934f75db8..a97ea229ca 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -288,6 +288,7 @@ jobs: tests/startup_gfx2hlsl_mask_overwrite_check.py \ tests/startup_gfx2hlsl_mask_data_check.py \ tests/startup_gfx2hlsl_image_get_lod_check.py \ + tests/startup_gfx2hlsl_image_desc_word_check.py \ tests/startup_gfx2hlsl_add_sub_co_check.py \ tests/startup_gfx2hlsl_add_sub_co_ci_check.py \ tests/startup_gfx2hlsl_saveexec_same_reg_check.py \ diff --git a/AGENTS.md b/AGENTS.md index d9b460cc2c..a40b1a5c29 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -225,6 +225,7 @@ python3 -m venv out/pe-env ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_bfm_b64_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_mask_data_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_image_get_lod_check.py +./out/pe-env/bin/python -B tests/startup_gfx2hlsl_image_desc_word_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_add_sub_co_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_add_sub_co_ci_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_saveexec_same_reg_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index e3425e05f6..5eb5a82e13 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -4063,6 +4063,9 @@ if(EXISTS "${INTAKE_PYTHON}") # Startup shader translator: image_get_lod on 2D and 2D-array textures. add_test(NAME startup_gfx2hlsl_image_get_lod_controls COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_image_get_lod_check.py") + # Pixel image descriptor words used as numbers: exact width, height and 3D depth fields only. + add_test(NAME startup_gfx2hlsl_image_desc_word_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_image_desc_word_check.py") foreach(adapter IN ITEMS warp hardware) add_test(NAME startup_image_get_lod_view_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_image_get_lod_view_check.py" "${DXC_EXECUTABLE}" diff --git a/docs/experiments.md b/docs/experiments.md index e7fa723759..34f6def3ee 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -16938,6 +16938,14 @@ The pixel translator lowers `quad_perm:[k,k,k,k]` (k = 0 to 3) with full `row_ma Reproduce: `ctest --preset dev --no-tests=error -R "^startup_gfx2hlsl_dpp_quad_broadcast" -V`. The controls cover the translation, every refusal, the missing `s_wqm`, the loop fixture and the divergent-EXEC control; the WARP and hardware draws compare all 256 pixels of the integer, float and loop fixtures with a CPU reference, with wrong-lane and own-lane translations as failing controls. This does not establish full-game startup. +### Pixel image descriptor size fields + +A pixel stage can read the GFX10 size fields of an 8-dword image descriptor that an image instruction uses. `s_bfe_u32`, `s_and_b32` and `s_lshr_b32` lower only when the control or mask is exactly the field. WIDTH is word 1 bits 31:30 and word 2 bits 11:0, stored as width minus one. HEIGHT is word 2 bits 27:14, stored as height minus one. DEPTH is word 4 bits 12:0 and is lowered only for a 3D image. The HLSL reads that component from `GetDimensions(0)` on the texture the image instruction binds. That matches the descriptor when the bound view starts at resource mip 0, the same base-mip contract as the image loads. A whole word, any other word or field, a shift of word 2 that keeps the resource-level bit, depth of a 1D, 2D or 2D-array image, height of a 1D image, a modified word and `m0` stay refused. A 4-dword buffer descriptor and the compute and vertex stages are unchanged. + +```powershell +ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_image_desc_word' -V +``` + ## Startup root signature changes `tests/startup_root_reset.cpp` and `tests/startup_root_reset_check.py` bind a 1D texture through a descriptor table diff --git a/tests/startup_gfx2hlsl_image_desc_word_check.py b/tests/startup_gfx2hlsl_image_desc_word_check.py new file mode 100644 index 0000000000..7b858572bd --- /dev/null +++ b/tests/startup_gfx2hlsl_image_desc_word_check.py @@ -0,0 +1,223 @@ +"""Pixel-stage numeric use of an image descriptor word in tools/startup/gfx2hlsl.py. + +The pixel stage loads an 8-dword image descriptor and an image instruction uses those registers. Exact GFX10 +size fields lower to GetDimensions(0) on that texture. WIDTH minus one is split into word 1 bits 31:30 and +word 2 bits 11:0. HEIGHT minus one is word 2 bits 27:14. DEPTH minus one is word 4 bits 12:0 and only for a +3D image. s_bfe_u32, s_and_b32 and s_lshr_b32 qualify only with that field's control or mask. + +Everything else stays refused: a whole word, any other word or field, a shift of word 2 that keeps the +resource-level bit, depth of a 1D, 2D or 2D-array image, height of a 1D image, a modified word, m0, a +4-dword buffer descriptor, a load with no image instruction, and the vertex stage. + +The pixel prologue is the source-built image_sample fixture. The scalar ops are encoded from the SOP1/SOP2 +layouts and the decoder must print each one back. With image_field_expr removed, every accepted case is +refused. +""" +import struct +import sys +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +from startup_image_sample_l_check import WORDS # noqa: E402 +from startup_sampler_heap_check import VS_WORDS, root_blob # noqa: E402 + +END = bytes.fromhex('0f1800f804050607000081bf') # exp mrt0 v4..v7; s_endpgm + + +def sop1(op, d, a): + return struct.pack(' tex) { uint w, h, m; tex.GetDimensions(0u, w, h, m); return w; }', + 'tex2d-h': 'uint img_height_tex2d(Texture2D tex) { uint w, h, m; tex.GetDimensions(0u, w, h, m); return h; }', + 'tex1d': 'uint img_width_tex1d(Texture1D tex) { uint w, m; tex.GetDimensions(0u, w, m); return w; }', + 'tex2da': 'uint img_height_tex2da(Texture2DArray tex) { uint w, h, e, m; tex.GetDimensions(0u, w, h, e, m); return h; }', + 'tex3d': 'uint img_depth_tex3d(Texture3D tex) { uint w, h, d, m; tex.GetDimensions(0u, w, h, d, m); return d; }', +} + +ACCEPTED = ( + ('width lo bfe', use('lz', 's_bfe_u32 s10, s17, 0x2001e'), W_LO, 'tex2d-w'), + ('width lo lshr', use('lz', 's_lshr_b32 s10, s17, 0x1e'), W_LO, 'tex2d-w'), + ('width lo and', use('lz', 's_and_b32 s10, s17, 0xc0000000'), W_AND, 'tex2d-w'), + ('width hi and', use('lz', 's_and_b32 s10, s18, 0xfff'), W_HI, 'tex2d-w'), + ('width hi bfe', use('lz', 's_bfe_u32 s10, s18, 0xc0000'), W_HI, 'tex2d-w'), + ('height bfe', use('lz', 's_bfe_u32 s10, s18, 0xe000e'), H, 'tex2d-h'), + ('height and', use('lz', 's_and_b32 s10, s18, 0xfffc000'), H_AND, 'tex2d-h'), + ('width 1d', use('dim1d', 's_bfe_u32 s10, s17, 0x2001e'), WIDTH_1D, 'tex1d'), + ('height array', use('array', 's_bfe_u32 s10, s18, 0xe000e'), H_ARRAY, 'tex2da'), + ('depth and', use('three', 's_and_b32 s10, s20, 0x1fff'), DEPTH, 'tex3d'), + ('depth bfe', use('three', 's_bfe_u32 s10, s20, 0xd0000'), DEPTH, 'tex3d'), + ('copied word', use('lz', 's_mov_b32 s28, s18', 's_and_b32 s10, s28, 0xfff'), W_HI, 'tex2d-w'), +) + + +def ps(code, vs=None): + pipe = G.Pipeline(vs or VS_WORDS, code, root_blob(flags=0)) + return pipe.hlsl_ps(), pipe.manifest() + + +def refused(code, text, vs=None): + try: + ps(code, vs) + except G.Unsupported as error: + assert text in str(error), str(error) + else: + raise AssertionError('accepted, expected %r' % text) + + +def without_field(code, vs=None): + saved = G.Stage.image_field_expr + G.Stage.image_field_expr = lambda self, base, srcs, syms: None + try: + try: + ps(code, vs) + except G.Unsupported: + return + raise AssertionError('translated with image_field_expr removed') + finally: + G.Stage.image_field_expr = saved + + +def controls(): + for label, code, expr, helper in ACCEPTED: + text, manifest = ps(code) + assert expr in text, (label, text) + assert HELPERS[helper] in text, (label, text) + assert 'srv 0 ' in manifest, (label, manifest) + without_field(code) + composed = splice(WORDS['lz'], ( + 's_bfe_u32 s10, s17, 0x2001e', + 's_and_b32 s11, s18, 0xfff', + 's_lshl_b32 s11, s11, 2', + 's_or_b32 s12, s10, s11', + 's_add_u32 s12, s12, 1', + 'v_mov_b32_e32 v4, s12', + ), 'image') + # The and writes s11, so the recorded v_mov of s10 is not part of this chain. + text, _manifest = ps(composed) + assert W_LO in text and W_HI in text and 's12 = s12 + 0x00000001u;' in text, text + without_field(composed) + + for word in range(8): + refused(splice(WORDS['lz'], ('v_mov_b32_e32 v4, s%d' % (16 + word),), 'image'), + 'numeric use of s%d holding image descriptor word %d' % (16 + word, word)) + refused(use('lz', 's_lshr_b32 s10, s18, 0xe'), 's_lshr_b32 of image descriptor word 2') + refused(use('lz', 's_bfe_u32 s10, s18, 0xe000f'), 's_bfe_u32 of image descriptor word 2') + refused(use('lz', 's_bfe_u32 s10, s19, 0x4000c'), 's_bfe_u32 of image descriptor word 3') + refused(use('lz', 's_bfe_u32 s10, s21, 0x40004'), 's_bfe_u32 of image descriptor word 5') + refused(use('lz', 's_bfe_u32 s10, s17, 0x90014'), 's_bfe_u32 of image descriptor word 1') + refused(use('lz', 's_and_b32 s10, s17, 0x80000000'), 's_and_b32 of image descriptor word 1') + refused(use('lz', 's_add_u32 s10, s18, 1'), 's_add_u32 of image descriptor word 2') + refused(use('lz', 's_and_b32 s10, s20, 0x1fff'), 'image descriptor depth of a 2D image') + refused(use('dim1d', 's_bfe_u32 s10, s18, 0xe000e'), 'image descriptor height of a 1D image') + refused(use('array', 's_and_b32 s10, s20, 0x1fff'), 'image descriptor depth of a 2D-array image') + refused(splice(WORDS['lz'], ('s_mov_b32 m0, s17', 'v_mov_b32_e32 v4, m0'), 'image'), + 'numeric use of m0 holding image descriptor word 1') + refused(splice(WORDS['lz'], ('s_add_u32 s17, s17, 1', 'v_mov_b32_e32 v4, s17'), 'after-image'), + 'numeric use of s17 holding a modified image descriptor word 1') + refused(splice(WORDS['lz'], ('s_cselect_b32 s10, 0, s17',), 'image'), + 'numeric use of s17 holding image descriptor word 1') + image3d = next(WORDS['three'][off:off + n] + for off, n, name, _asm in G.decode(WORDS['three']) if name.startswith('image_')) + both = splice(WORDS['lz'], ('s_bfe_u32 s10, s17, 0x2001e', 'v_mov_b32_e32 v4, s10'), 'image') + end_at = next(off for off, _n, name, _asm in G.decode(both) if name == 's_endpgm') + both = both[:end_at] + image3d + both[end_at:] + refused(both, 'image descriptor word used as two dimensions') + + bare_image = smem(0x03, 16, 8) + OPS['s_bfe_u32 s10, s17, 0x2001e'] + VMOV + END + refused(bare_image, 'numeric use of s10 holding descnum') + bare_buf = smem(0x02, 16, 8) + OPS['s_and_b32 s10, s18, 0xfff'] + VMOV + END + refused(bare_buf, 'numeric use of s10 holding descnum') + vertex = smem(0x03, 16, 8) + OPS['s_bfe_u32 s10, s17, 0x2001e'] + VMOV + VS_WORDS + refused(WORDS['lz'], 'numeric use of s10 holding descnum', vs=vertex) + print('pixel image descriptor size fields: width, height and 3D depth lowered; other words refused') + + +if __name__ == '__main__': + controls() diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index ac83e12139..7d8ce47e7d 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -1017,6 +1017,46 @@ def raw_descriptor_alu(base, syms, constants): return None +# GFX10 image resource fields that are the bound view's mip-0 size minus one (Mesa radv_image.c: +# width = WIDTH_LO + (WIDTH_HI << 2) + 1, height = HEIGHT + 1). WIDTH_LO is word 1 bits 31:30, +# WIDTH_HI is word 2 bits 11:0, HEIGHT is word 2 bits 27:14. DEPTH is word 4 bits 12:0 and is the +# view depth only for a 3D image; on 1D and 2D the same bits hold pitch. s_bfe_u32's control is +# (width << 16) | offset. A shift that keeps bits outside the field is not an entry. +IMAGE_FIELDS = { + (1, 's_bfe_u32', 0x0002001e): ('width', '(({0} - 1u) & 3u)'), + (1, 's_lshr_b32', 30): ('width', '(({0} - 1u) & 3u)'), + (1, 's_and_b32', 0xc0000000): ('width', '((({0} - 1u) & 3u) << 30)'), + (2, 's_and_b32', 0xfff): ('width', '(({0} - 1u) >> 2)'), + (2, 's_bfe_u32', 0x000c0000): ('width', '(({0} - 1u) >> 2)'), + (2, 's_bfe_u32', 0x000e000e): ('height', '(({0} - 1u) & 0x3fffu)'), + (2, 's_and_b32', 0x0fffc000): ('height', '((({0} - 1u) & 0x3fffu) << 14)'), + (4, 's_and_b32', 0x1fff): ('depth', '(({0} - 1u) & 0x1fffu)'), + (4, 's_bfe_u32', 0x000d0000): ('depth', '(({0} - 1u) & 0x1fffu)'), +} +IMAGE_DIM = { + 'SQ_RSRC_IMG_1D': 'tex1d', 'SQ_RSRC_IMG_2D': 'tex2d', + 'SQ_RSRC_IMG_2D_ARRAY': 'tex2da', 'SQ_RSRC_IMG_3D': 'tex3d', +} +IMAGE_DIM_HAS = { + 'tex1d': frozenset(('width',)), + 'tex2d': frozenset(('width', 'height')), + 'tex2da': frozenset(('width', 'height')), + 'tex3d': frozenset(('width', 'height', 'depth')), +} +IMAGE_DIM_NAME = {'tex1d': '1D', 'tex2d': '2D', 'tex2da': '2D-array', 'tex3d': '3D'} +IMAGE_DIM_TYPE = { + 'tex1d': 'Texture1D', 'tex2d': 'Texture2D', + 'tex2da': 'Texture2DArray', 'tex3d': 'Texture3D', +} +IMAGE_DIM_READ = { + 'tex1d': ('uint w, m;', 'tex.GetDimensions(0u, w, m);', {'width': 'w'}), + 'tex2d': ('uint w, h, m;', 'tex.GetDimensions(0u, w, h, m);', {'width': 'w', 'height': 'h'}), + 'tex2da': ('uint w, h, e, m;', 'tex.GetDimensions(0u, w, h, e, m);', {'width': 'w', 'height': 'h'}), + 'tex3d': ('uint w, h, d, m;', 'tex.GetDimensions(0u, w, h, d, m);', + {'width': 'w', 'height': 'h', 'depth': 'd'}), +} + + def smem_offset(tok): """The SMEM offset operand as a token: 'off' (no offset operand) is the literal 0, anything else unchanged.""" return '0' if tok == 'off' else tok @@ -2544,6 +2584,7 @@ def __init__(self, pipe, kind, code, refusals=None, decoded=None): self.lines = [] # body statements (per block) self.vconst = {} # VGPR -> literal 32-bit value while the program is straight-line self.sym = {} # scalar register -> symbolic value + self.image_span = {} # SGPR -> (load dword count, index) for an 8- or 16-dword image load self.used_s, self.used_v = set(), set() self.used_atomic = set() self.exec_known = True # exec still equals the entry mask (the lane is active) @@ -2653,7 +2694,7 @@ def S(self, n): return 's%d' % n if s[0] == 'tg_size': raise Unsupported('TG_SIZE register s%d read outside s_and_b32 with 0xfc0' % n) - raise Unsupported('numeric use of s%d holding %s' % (n, s[0])) + raise Unsupported(self.held_message('s%d' % n, s, n)) self.used_s.add(n) return 's%d' % n @@ -2679,7 +2720,7 @@ def u(self, tok, *, low16_only=False): if tok == 'm0': m = self.sym.get('m0') if m: - raise Unsupported('numeric use of m0 holding %s' % m[0]) + raise Unsupported(self.held_message('m0', m, 'm0')) return 'm0' if tok == 'null': return '0x00000000u' @@ -3050,6 +3091,9 @@ def set_s(self, n, expr, sym=None, scc=None, uniform=None, align4=False): self.record_scalar_uniformity(n, uniform) getattr(self, 'masks', set()).discard(n) # unit probes build a Stage without __init__ getattr(self, 'mask_high', set()).discard(n) + span = getattr(self, 'image_span', None) + if isinstance(span, dict): + span.pop(n, None) getattr(self, 'float_const_s', {}).pop(n, None) if isinstance(self.align4_s, set): if sym is not None and sym[0] == 'const': @@ -4059,6 +4103,7 @@ def translate(self): every_sgpr = set(range(106)) | {'m0'} init_entry = [r for r in set(init_sym) | init_used_s if isinstance(r, int)] init_written = set(range(max(init_entry + [-1 if getattr(self, 'kind', None) == 'cs' else 15]) + 1)) | {'m0'} + self.note_image_descriptors() for _ in range(max(4, len(self.ins) + 2)): scc_effects = {} @@ -4068,6 +4113,9 @@ def translate(self): self.vconst = {} self.blocks = [] # (offset, [lines], terminator) self.sym = dict(init_sym) + self.image_span = {} + if isinstance(getattr(self, 'image_reg_dim', None), dict): + self.image_reg_dim.pop('m0', None) self.exec_known = init_exec_known self.wqm_exec = init_wqm_exec self.wqm_count, self.execcopy_epoch = 0, {} @@ -5901,6 +5949,141 @@ def _complete_resheap_carry(self, base, ops, mods): self.scc_verified = False return True + def note_image_descriptors(self): + """Pixel SGPRs that are an 8-dword image descriptor, including copies through s_mov. + + The kind is the image instruction's dimension. Two dimensions on one register are recorded as None + so a numeric use refuses instead of picking one. Other stages leave the map empty.""" + dim, copies, conflict = {}, [], set() + if getattr(self, 'kind', None) != 'ps': + self.image_reg_dim = dim + return + for _off, _n, name, asm in self.ins: + _op, operands, mods = parse(asm) + if name.startswith('image_') and len(operands) >= 3: + reg = reg_range(operands[2]) + kinds = [IMAGE_DIM[m[4:]] for m in mods if m.startswith('dim:') and m[4:] in IMAGE_DIM] + if reg and reg[0] == 's' and reg[2] == reg[1] + 7 and len(kinds) == 1: + for n in range(reg[1], reg[2] + 1): + if n in dim and dim[n] != kinds[0]: + conflict.add(n) + dim[n] = kinds[0] + if name in ('s_mov_b32', 's_mov_b64') and len(operands) >= 2: + dst, src = reg_range(operands[0]), reg_range(operands[1]) + if (dst and src and dst[0] == 's' and src[0] == 's' + and dst[2] - dst[1] == src[2] - src[1] and dst[2] - dst[1] in (0, 1)): + for i in range(dst[2] - dst[1] + 1): + copies.append((dst[1] + i, src[1] + i)) + changed = True + while changed: + changed = False + for dst, src in copies: + if src in dim and dst not in dim: + dim[dst] = dim[src] + if src in conflict: + conflict.add(dst) + changed = True + elif dst in dim and src not in dim: + dim[src] = dim[dst] + if dst in conflict: + conflict.add(src) + changed = True + elif src in dim and dst in dim and dim[src] != dim[dst]: + conflict.add(src) + conflict.add(dst) + for n in conflict: + dim[n] = None + self.image_reg_dim = dim + + def _copy_image_span(self, src, dest): + span = getattr(self, 'image_span', None) + if not isinstance(span, dict): + return + if src and src[0] == 's' and src[1] in span: + span[dest] = span[src[1]] + else: + span.pop(dest, None) + + def image_word(self, reg): + """(field 0..7, kind or None, symbol, modified) for a pixel image descriptor word, else None. + + kind is None when the register is used as two image dimensions. An 8- or 16-dword load is what + marks the word; a 4-dword buffer load is not an image.""" + if getattr(self, 'kind', None) != 'ps': + return None + sym = self.sym.get(reg) + span = (getattr(self, 'image_span', None) or {}).get(reg) + dims = getattr(self, 'image_reg_dim', {}) + if not sym or sym[0] != 'desc' or not span or reg not in dims or len(sym) < 4: + return None + modified = 'modified' in sym[4:] + if len(sym) != 4 and not modified: + return None + count, index = span + if count not in (8, 16) or sym[3] != index: + return None + return (index % 8, dims[reg], sym, modified) + + def image_dim_call(self, sym, kind, component): + """GetDimensions(0) of the texture this image descriptor binds, for one component.""" + base, dword = sym[2], sym[3] & ~7 + tex = self.pipe.resource((sym[1], None if base is None else base + 4 * dword), kind) + helpers = getattr(self.pipe, 'image_dim_helpers', None) + if helpers is None: + helpers = self.pipe.image_dim_helpers = set() + helpers.add((kind, component)) + return 'img_%s_%s(%s)' % (component, kind, tex) + + def image_field_expr(self, base, srcs, syms): + """A pixel extract of one exact image size field, or ('opaque', word, op, reason). + + None leaves the old descnum path. The value is the bound view's mip-0 size with that field's + bits. GetDimensions(0) matches the descriptor when the view starts at resource mip 0.""" + if getattr(self, 'kind', None) != 'ps' or len(srcs) != 2 or len(syms) != 2: + return None + constants = [self.const_u32(t) for t in srcs] + hits = [] + for i, _sym in enumerate(syms): + reg = reg_range(srcs[i]) + if not reg or reg[0] != 's' or reg[1] != reg[2]: + continue + info = self.image_word(reg[1]) + if not info or info[3]: + continue + field, kind, sym, _modified = info + if kind is None: + hits.append(('opaque', field, base, 'word used as two dimensions')) + continue + if base == 's_bfe_u32' and i != 0: + hits.append(('opaque', field, base, '')) + continue + found = IMAGE_FIELDS.get((field, base, constants[1 - i])) + if found is None: + hits.append(('opaque', field, base, '')) + continue + component, template = found + if component not in IMAGE_DIM_HAS[kind]: + hits.append(('opaque', field, base, '%s of a %s image' % (component, IMAGE_DIM_NAME[kind]))) + continue + hits.append(('value', template.format(self.image_dim_call(sym, kind, component)))) + if len(hits) != 1: + return None + return hits[0] + + def held_message(self, name, sym, reg): + """Refusal for a numeric read of a symbol. Image words name the word, the op, or the field.""" + if sym and sym[0] == 'descnum' and len(sym) >= 5 and sym[1] == 'image': + if sym[4]: + return 'numeric use of %s holding image descriptor %s' % (name, sym[4]) + return 'numeric use of %s holding %s of image descriptor word %d' % (name, sym[3], sym[2]) + if sym and sym[0] == 'desc': + info = self.image_word(reg) + if info: + if info[3]: + return 'numeric use of %s holding a modified image descriptor word %d' % (name, info[0]) + return 'numeric use of %s holding image descriptor word %d' % (name, info[0]) + return 'numeric use of %s holding %s' % (name, sym[0]) + def scalar(self, base, ops, mods=()): # Every SALU form in SCA is dst, src (the two templates below use {0} and {1}); a short list would # index past the end and leave `translator crash in : IndexError` in the census instead of a @@ -6014,10 +6197,9 @@ def src_sym(t): raise Unsupported('scc from descriptor data') if word_pack: raise Unsupported('%s on descriptor data' % base) - # Every path below writes the destination's symbol directly, not through set_s, or refuses. The - # written word is descriptor data, so a lane-mask mark the SGPR held from an earlier write ends here as - # set_s ends it. lower() has already classified the sources, so a mask read by this instruction is - # still refused. + # Paths below either refuse, keep a descriptor symbol, or (an exact pixel image size field) assign + # the number through set_s. A lane-mask mark the SGPR held ends here as set_s ends it. lower() has + # already classified the sources, so a mask read by this instruction is still refused. if dst and dst[0] == 's': for reg in range(dst[1], dst[2] + 1): getattr(self, 'masks', set()).discard(reg) @@ -6042,10 +6224,24 @@ def src_sym(t): self.resheap_low_add = (dst[1], self.pc + size, heap_mark) self.scc_verified = True return None + field = self.image_field_expr(base, srcs, syms) if dname == 'm0': if scc: raise Unsupported('scc from descriptor data') - self.sym['m0'] = syms[0] if base == 's_mov_b32' else ('descnum',) + if base == 's_mov_b32': + self.sym['m0'] = syms[0] + src = reg_range(srcs[0]) if srcs else None + self._copy_image_span(src, 'm0') + dims = getattr(self, 'image_reg_dim', None) + if isinstance(dims, dict): + if src and src[0] == 's' and src[1] in dims: + dims['m0'] = dims[src[1]] + else: + dims.pop('m0', None) + elif field and field[0] == 'opaque': + self.sym['m0'] = ('descnum', 'image', field[1], field[2], field[3]) + else: + self.sym['m0'] = ('descnum',) return None if mask_dest: raise Unsupported('mask from descriptor data') @@ -6058,13 +6254,19 @@ def src_sym(t): own = self.sym.get(d) raw = (raw_descriptor_alu(base, syms, [self.const_u32(t) for t in srcs]) if getattr(self, 'kind', None) in ('cs', 'vs') and len(syms) == 2 else None) + if field and field[0] == 'value' and not pair and dst[1] == dst[2]: + # The field is a number, so SCC is that number's zero flag rather than descriptor data. + self.set_s(d, field[1], scc='($) != 0', uniform=True) + return None if base in ('s_mov_b32', 's_mov_b64'): self.sym[d] = syms[0] + self._copy_image_span(reg_range(srcs[0]) if srcs else None, d) if pair: high = reg_range(ops[1])[2] hi = self.sym.get(high) if hi and not run_time_symbol(hi): self.sym[d + 1] = hi # a descriptor word, a pointer or an unassigned constant: symbol only + self._copy_image_span(('s', high, high), d + 1) else: # A value the high word holds at run time is copied at run time too, so a join that later # reads the register at run time finds it (a constant keeps its symbol for folding). @@ -6090,7 +6292,13 @@ def src_sym(t): else: self.sym[d] = own[:2] + ('added',) # this operation has no proven byte offset else: - self.sym[d] = ('descnum',) + if field and field[0] == 'opaque': + self.sym[d] = ('descnum', 'image', field[1], field[2], field[3]) + else: + self.sym[d] = ('descnum',) + span = getattr(self, 'image_span', None) + if isinstance(span, dict): + span.pop(d, None) return None # The table templates name their sources as {0}, {1}, ...; a short operand list would make # str.format raise IndexError, which the single-shader path records as a translator crash @@ -6898,6 +7106,10 @@ def op_s_load_dwordx4(self, ops, mods, count=4): load = (self.pc,) for i in range(count): self.sym[dst[1] + i] = ('desc', p[1], base_off + off, i) + load + span = getattr(self, 'image_span', None) + if isinstance(span, dict) and count in (8, 16): + for i in range(count): + span[dst[1] + i] = (count, i) if into_vcc: self.mark_vcc_descriptor() return @@ -12010,6 +12222,7 @@ def _init_pixel_context(self, root_blob, sampler_heap=None, rtv_formats=(), ps_h self.uses_bvh = False self.uses_cube_dir = False self.uses_gather_2d_lod = False + self.image_dim_helpers = set() self.uses_store_d16_x = False self.uses_dot2 = set() self.uses_sad = set() @@ -12289,6 +12502,10 @@ def common(self): out.append('%s r%d : register(t%d);' % ({'buf': 'ByteAddressBuffer', 'bvh': 'ByteAddressBuffer', 'tex1d': 'Texture1D', 'tex2d': 'Texture2D', 'tex2da': 'Texture2DArray', 'tex3d': 'Texture3D', 'texcube': 'TextureCube'}[r['kind']], r['index'], r['index'])) if getattr(self, 'resheap_count', 0): out.append('ByteAddressBuffer rh[%d] : register(t0, space%d);' % (self.resheap_count, RESHEAP_RANGE_SPACE)) + for kind, component in sorted(getattr(self, 'image_dim_helpers', ()) or ()): + decl, call, names = IMAGE_DIM_READ[kind] + out.append('uint img_%s_%s(%s tex) { %s %s return %s; }' % ( + component, kind, IMAGE_DIM_TYPE[kind], decl, call, names[component])) for key, r in sorted(self.stored_images().items(), key=lambda kv: kv[1]['index']): out.append('%s %s%d : register(u%d);' % ({'tex1d': 'RWTexture1D', 'tex2d': 'RWTexture2D', 'tex2da': 'RWTexture2DArray', 'tex3d': 'RWTexture3D', 'raw': 'RWByteAddressBuffer'}[r['kind']], 'u' if r['kind'] == 'raw' else 'w', r['index'], r['index'])) for key, i in self.samplers.items(): From 9292d9e6b08feaf9a4abcb1227da68e2d851e2e8 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sat, 28 Nov 2026 00:13:21 +0000 Subject: [PATCH 2/4] startup: key image size fields by the descriptor load A pixel size-field read uses the dimension of the descriptor load the image instruction reads. Another load into the same SGPRs does not borrow it. A copy of the sampled words still does. Co-authored-by: SimSalabimse --- docs/experiments.md | 2 +- .../startup_gfx2hlsl_image_desc_word_check.py | 37 +++++- tools/startup/gfx2hlsl.py | 122 +++++++++++------- 3 files changed, 112 insertions(+), 49 deletions(-) diff --git a/docs/experiments.md b/docs/experiments.md index 34f6def3ee..78a48b4a84 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -16940,7 +16940,7 @@ Reproduce: `ctest --preset dev --no-tests=error -R "^startup_gfx2hlsl_dpp_quad_b ### Pixel image descriptor size fields -A pixel stage can read the GFX10 size fields of an 8-dword image descriptor that an image instruction uses. `s_bfe_u32`, `s_and_b32` and `s_lshr_b32` lower only when the control or mask is exactly the field. WIDTH is word 1 bits 31:30 and word 2 bits 11:0, stored as width minus one. HEIGHT is word 2 bits 27:14, stored as height minus one. DEPTH is word 4 bits 12:0 and is lowered only for a 3D image. The HLSL reads that component from `GetDimensions(0)` on the texture the image instruction binds. That matches the descriptor when the bound view starts at resource mip 0, the same base-mip contract as the image loads. A whole word, any other word or field, a shift of word 2 that keeps the resource-level bit, depth of a 1D, 2D or 2D-array image, height of a 1D image, a modified word and `m0` stay refused. A 4-dword buffer descriptor and the compute and vertex stages are unchanged. +A pixel stage can read the GFX10 size fields of an 8-dword image descriptor that an image instruction uses. `s_bfe_u32`, `s_and_b32` and `s_lshr_b32` lower only when the control or mask is exactly the field. WIDTH is word 1 bits 31:30 and word 2 bits 11:0, stored as width minus one. HEIGHT is word 2 bits 27:14, stored as height minus one. DEPTH is word 4 bits 12:0 and is lowered only for a 3D image. The HLSL reads that component from `GetDimensions(0)` on the texture the image instruction binds. The dimension is taken from the descriptor load that instruction reads, not from the register: a later or earlier load of a different descriptor into the same SGPRs does not borrow it. A copy of the sampled words keeps the load. That matches the descriptor when the bound view starts at resource mip 0, the same base-mip contract as the image loads. A whole word, any other word or field, a shift of word 2 that keeps the resource-level bit, depth of a 1D, 2D or 2D-array image, height of a 1D image, a modified word and `m0` stay refused. A 4-dword buffer descriptor and the compute and vertex stages are unchanged. ```powershell ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_image_desc_word' -V diff --git a/tests/startup_gfx2hlsl_image_desc_word_check.py b/tests/startup_gfx2hlsl_image_desc_word_check.py index 7b858572bd..f676b8a6d6 100644 --- a/tests/startup_gfx2hlsl_image_desc_word_check.py +++ b/tests/startup_gfx2hlsl_image_desc_word_check.py @@ -7,7 +7,10 @@ Everything else stays refused: a whole word, any other word or field, a shift of word 2 that keeps the resource-level bit, depth of a 1D, 2D or 2D-array image, height of a 1D image, a modified word, m0, a -4-dword buffer descriptor, a load with no image instruction, and the vertex stage. +4-dword buffer descriptor, a load with no image instruction, and the vertex stage. A size field is +the descriptor load the image instruction reads: an earlier load at table offset 32 into the same +registers does not borrow the sampled dimension, and a reload of those registers after the sample does +not either. A copy of the sampled word taken before the reload still does. The pixel prologue is the source-built image_sample fixture. The scalar ops are encoded from the SOP1/SOP2 layouts and the decoder must print each one back. With image_field_expr removed, every accepted case is @@ -76,6 +79,8 @@ def smem(op, sdata, sbase, offset=0): 's_lshl_b32 s11, s11, 2': sop2(LSHL, 11, 11, TWO), 's_or_b32 s12, s10, s11': sop2(OR, 12, 10, 11), 's_add_u32 s12, s12, 1': sop2(ADD, 12, 12, ONE), + 's_load_dwordx8 s[16:23], s[8:9], 0x20': smem(0x03, 16, 8, 0x20), + 's_waitcnt lgkmcnt(0)': bytes.fromhex('7fc08cbf'), 'v_mov_b32_e32 v4, s10': VMOV, 'v_mov_b32_e32 v4, s12': vop1(0x01, 4, 12), 'v_mov_b32_e32 v4, s17': vop1(0x01, 4, 17), @@ -216,6 +221,36 @@ def controls(): refused(bare_buf, 'numeric use of s10 holding descnum') vertex = smem(0x03, 16, 8) + OPS['s_bfe_u32 s10, s17, 0x2001e'] + VMOV + VS_WORDS refused(WORDS['lz'], 'numeric use of s10 holding descnum', vs=vertex) + + # The offset-32 load is read before the fixture's own offset-0 load. The sample uses offset 0, so + # the earlier word must not borrow that dimension. The v_mov is after the image instruction. + early = (OPS['s_load_dwordx8 s[16:23], s[8:9], 0x20'] + OPS['s_waitcnt lgkmcnt(0)'] + + OPS['s_and_b32 s10, s18, 0xfff'] + WORDS['lz']) + early = splice(early, ('v_mov_b32_e32 v4, s10',), 'after-image') + refused(early, 'numeric use of s10 holding descnum') + + # s18 is copied before the sample. After it, s[16:23] is loaded again from offset 32. + # The copy is still the sampled descriptor. The reloaded s18 is not. + kept = splice(WORDS['lz'], ('s_mov_b32 s28, s18',), 'image') + kept = splice(kept, ( + 's_load_dwordx8 s[16:23], s[8:9], 0x20', + 's_waitcnt lgkmcnt(0)', + 's_and_b32 s10, s28, 0xfff', + 'v_mov_b32_e32 v4, s10', + ), 'after-image') + text, manifest = ps(kept) + assert W_HI in text, text + assert manifest.count('\nsrv ') == 1 and 'srv 0 tex2d table 0 0' in manifest, manifest + assert 'table 0 32' not in manifest, manifest + without_field(kept) + reloaded = splice(WORDS['lz'], ('s_mov_b32 s28, s18',), 'image') + reloaded = splice(reloaded, ( + 's_load_dwordx8 s[16:23], s[8:9], 0x20', + 's_waitcnt lgkmcnt(0)', + 's_and_b32 s10, s18, 0xfff', + 'v_mov_b32_e32 v4, s10', + ), 'after-image') + refused(reloaded, 'numeric use of s10 holding descnum') print('pixel image descriptor size fields: width, height and 3D depth lowered; other words refused') diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 7d8ce47e7d..ff3f8a7963 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -979,6 +979,16 @@ def desc_key(sym): return sym[1], None if sym[2] is None else sym[2] + 4 * (sym[3] & ~3) +def image_desc_key(sym): + """Descriptor load an image word belongs to: (source, byte offset of its 8-dword image). + + The dword index is aligned down to the image, so word 2 of a load at byte 32 is that load and not the + image a later load placed in the same registers.""" + if not sym or sym[0] != 'desc' or len(sym) < 4 or not isinstance(sym[2], int) or not isinstance(sym[3], int): + return None + return (sym[1], sym[2] + 4 * (sym[3] & ~7)) + + def desc_word(sym, dword): return sym[:3] + (dword,) + sym[4:] @@ -4114,8 +4124,6 @@ def translate(self): self.blocks = [] # (offset, [lines], terminator) self.sym = dict(init_sym) self.image_span = {} - if isinstance(getattr(self, 'image_reg_dim', None), dict): - self.image_reg_dim.pop('m0', None) self.exec_known = init_exec_known self.wqm_exec = init_wqm_exec self.wqm_count, self.execcopy_epoch = 0, {} @@ -5950,50 +5958,74 @@ def _complete_resheap_carry(self, base, ops, mods): return True def note_image_descriptors(self): - """Pixel SGPRs that are an 8-dword image descriptor, including copies through s_mov. - - The kind is the image instruction's dimension. Two dimensions on one register are recorded as None - so a numeric use refuses instead of picking one. Other stages leave the map empty.""" - dim, copies, conflict = {}, [], set() + """Pixel: descriptor load -> image dimension, for the load an image instruction actually reads. + + The key is image_desc_key of the operand's words at that instruction, not the SGPR number. A copy + keeps the symbol, so it keeps the key; a later load into the same registers is a different key. + Two dimensions on one key are None. A branch leaves the map empty: the load the image reads is + then not proved. Other stages leave the map empty.""" + dims = {} + self.image_desc_dim = dims if getattr(self, 'kind', None) != 'ps': - self.image_reg_dim = dim return + if any(name.startswith(('s_cbranch', 's_branch', 's_setpc')) for _off, _n, name, _asm in self.ins): + return + sym = dict(self.sym) + counts = {'s_load_dword': 1, 's_load_dwordx2': 2, 's_load_dwordx4': 4, + 's_load_dwordx8': 8, 's_load_dwordx16': 16} for _off, _n, name, asm in self.ins: _op, operands, mods = parse(asm) if name.startswith('image_') and len(operands) >= 3: reg = reg_range(operands[2]) kinds = [IMAGE_DIM[m[4:]] for m in mods if m.startswith('dim:') and m[4:] in IMAGE_DIM] if reg and reg[0] == 's' and reg[2] == reg[1] + 7 and len(kinds) == 1: - for n in range(reg[1], reg[2] + 1): - if n in dim and dim[n] != kinds[0]: - conflict.add(n) - dim[n] = kinds[0] + first = sym.get(reg[1]) + key = image_desc_key(first) + same = key is not None and first[3] % 8 == 0 and all( + sym.get(reg[1] + i) == desc_word(first, first[3] + i) + and 'modified' not in (sym.get(reg[1] + i) or ())[4:] + for i in range(8)) + if same: + if key in dims and dims[key] != kinds[0]: + dims[key] = None + elif key not in dims: + dims[key] = kinds[0] + continue + if name in counts and len(operands) >= 1: + dst = reg_range(operands[0]) + count = counts[name] + if dst and dst[0] == 's': + for i in range(dst[1], dst[2] + 1): + sym.pop(i, None) + base = reg_range(operands[1]) if len(operands) >= 3 else None + p = sym.get(base[1]) if base and base[0] == 's' else None + token = operands[2] if len(operands) >= 3 else '' + extra = 0 + for mod in mods: + if mod.startswith('offset:') and re.fullmatch(r'(?:0[xX][0-9a-fA-F]+|\d+)', mod[7:]): + extra = int(mod[7:], 0) + if (p and p[0] == 'ptr' and dst[2] - dst[1] + 1 == count + and re.fullmatch(r'(?:0[xX][0-9a-fA-F]+|\d+)', token) + and (len(p) == 2 or isinstance(p[2], int))): + off = int(token, 0) + extra + (p[2] if len(p) > 2 else 0) + for i in range(count): + sym[dst[1] + i] = ('desc', p[1], off, i) + continue if name in ('s_mov_b32', 's_mov_b64') and len(operands) >= 2: dst, src = reg_range(operands[0]), reg_range(operands[1]) - if (dst and src and dst[0] == 's' and src[0] == 's' - and dst[2] - dst[1] == src[2] - src[1] and dst[2] - dst[1] in (0, 1)): - for i in range(dst[2] - dst[1] + 1): - copies.append((dst[1] + i, src[1] + i)) - changed = True - while changed: - changed = False - for dst, src in copies: - if src in dim and dst not in dim: - dim[dst] = dim[src] - if src in conflict: - conflict.add(dst) - changed = True - elif dst in dim and src not in dim: - dim[src] = dim[dst] - if dst in conflict: - conflict.add(src) - changed = True - elif src in dim and dst in dim and dim[src] != dim[dst]: - conflict.add(src) - conflict.add(dst) - for n in conflict: - dim[n] = None - self.image_reg_dim = dim + if dst and dst[0] == 's' and src and src[0] == 's' and dst[2] - dst[1] == src[2] - src[1]: + vals = [sym.get(src[1] + i) for i in range(dst[2] - dst[1] + 1)] + for i, val in enumerate(vals): + if val is None: + sym.pop(dst[1] + i, None) + else: + sym[dst[1] + i] = val + continue + for dest in scalar_destinations(name, asm): + if dest == 'any': + sym.clear() + break + sym.pop(dest, None) def _copy_image_span(self, src, dest): span = getattr(self, 'image_span', None) @@ -6007,14 +6039,16 @@ def _copy_image_span(self, src, dest): def image_word(self, reg): """(field 0..7, kind or None, symbol, modified) for a pixel image descriptor word, else None. - kind is None when the register is used as two image dimensions. An 8- or 16-dword load is what - marks the word; a 4-dword buffer load is not an image.""" + kind is None when that descriptor load is used as two image dimensions. The load has to be one an + image instruction reads (image_desc_dim). An 8- or 16-dword load is what marks the word; a 4-dword + buffer load is not an image.""" if getattr(self, 'kind', None) != 'ps': return None sym = self.sym.get(reg) span = (getattr(self, 'image_span', None) or {}).get(reg) - dims = getattr(self, 'image_reg_dim', {}) - if not sym or sym[0] != 'desc' or not span or reg not in dims or len(sym) < 4: + dims = getattr(self, 'image_desc_dim', {}) + key = image_desc_key(sym) + if not sym or sym[0] != 'desc' or not span or key not in dims or len(sym) < 4: return None modified = 'modified' in sym[4:] if len(sym) != 4 and not modified: @@ -6022,7 +6056,7 @@ def image_word(self, reg): count, index = span if count not in (8, 16) or sym[3] != index: return None - return (index % 8, dims[reg], sym, modified) + return (index % 8, dims[key], sym, modified) def image_dim_call(self, sym, kind, component): """GetDimensions(0) of the texture this image descriptor binds, for one component.""" @@ -6232,12 +6266,6 @@ def src_sym(t): self.sym['m0'] = syms[0] src = reg_range(srcs[0]) if srcs else None self._copy_image_span(src, 'm0') - dims = getattr(self, 'image_reg_dim', None) - if isinstance(dims, dict): - if src and src[0] == 's' and src[1] in dims: - dims['m0'] = dims[src[1]] - else: - dims.pop('m0', None) elif field and field[0] == 'opaque': self.sym['m0'] = ('descnum', 'image', field[1], field[2], field[3]) else: From 15095ee34960cdbeae9d83279d64f4e3eb5c9045 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sat, 28 Nov 2026 10:35:29 +0000 Subject: [PATCH 3/4] startup: refuse a shifted image-size view and a swapped shift s_lshr_b32 of a size field lowers only when the descriptor word is the value being shifted. A size-field SRV is marked imagedim, and the draw path refuses that view when MostDetailedMip is not 0. Sampling a shifted view that does not read a size field is unchanged. Co-authored-by: SimSalabimse --- docs/experiments.md | 2 +- src/startup_stubs/d3d12_draw.inl | 64 ++++++++++++++++++- .../startup_gfx2hlsl_image_desc_word_check.py | 8 +++ tools/startup/gfx2hlsl.py | 21 +++++- 4 files changed, 90 insertions(+), 5 deletions(-) diff --git a/docs/experiments.md b/docs/experiments.md index 78a48b4a84..f156da5db1 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -16940,7 +16940,7 @@ Reproduce: `ctest --preset dev --no-tests=error -R "^startup_gfx2hlsl_dpp_quad_b ### Pixel image descriptor size fields -A pixel stage can read the GFX10 size fields of an 8-dword image descriptor that an image instruction uses. `s_bfe_u32`, `s_and_b32` and `s_lshr_b32` lower only when the control or mask is exactly the field. WIDTH is word 1 bits 31:30 and word 2 bits 11:0, stored as width minus one. HEIGHT is word 2 bits 27:14, stored as height minus one. DEPTH is word 4 bits 12:0 and is lowered only for a 3D image. The HLSL reads that component from `GetDimensions(0)` on the texture the image instruction binds. The dimension is taken from the descriptor load that instruction reads, not from the register: a later or earlier load of a different descriptor into the same SGPRs does not borrow it. A copy of the sampled words keeps the load. That matches the descriptor when the bound view starts at resource mip 0, the same base-mip contract as the image loads. A whole word, any other word or field, a shift of word 2 that keeps the resource-level bit, depth of a 1D, 2D or 2D-array image, height of a 1D image, a modified word and `m0` stay refused. A 4-dword buffer descriptor and the compute and vertex stages are unchanged. +A pixel stage can read the GFX10 size fields of an 8-dword image descriptor that an image instruction uses. `s_bfe_u32`, `s_and_b32` and `s_lshr_b32` lower only when the control or mask is exactly the field. WIDTH is word 1 bits 31:30 and word 2 bits 11:0, stored as width minus one. HEIGHT is word 2 bits 27:14, stored as height minus one. DEPTH is word 4 bits 12:0 and is lowered only for a 3D image. The HLSL reads that component from `GetDimensions(0)` on the texture the image instruction binds. The dimension is taken from the descriptor load that instruction reads, not from the register: a later or earlier load of a different descriptor into the same SGPRs does not borrow it. A copy of the sampled words keeps the load. `s_lshr_b32` lowers only when the descriptor word is the value being shifted. The manifest marks each such SRV with `imagedim `. The draw path refuses that view when the recorded descriptor's `MostDetailedMip` is not 0, because `GetDimensions(0)` is the view's first mip and the descriptor fields are resource mip 0. A sample that does not read a size field is not marked, so a shifted view can still be sampled. A whole word, any other word or field, a shift of word 2 that keeps the resource-level bit, depth of a 1D, 2D or 2D-array image, height of a 1D image, a modified word and `m0` stay refused. A 4-dword buffer descriptor and the compute and vertex stages are unchanged. ```powershell ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_image_desc_word' -V diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index 9c1c2b2a2f..0d064ca463 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -11,6 +11,49 @@ #include "startup_stubs/typed_uav_load.h" +// 'imagedim ': the pixel stage reads a GFX10 size field of SRV through GetDimensions(0). +// That is the view's first mip. It matches the descriptor only when the view starts at resource mip 0. +struct ImageSizeSrvs { + std::uint32_t mask = 0; + + bool read_manifest_line(const std::string& line) + { + int index = -1, used = 0; + if (std::sscanf(line.c_str(), "imagedim %d%n", &index, &used) != 1 || used != static_cast(line.size())) + return false; + if (index < 0 || index >= 32) return false; + const char* digits = line.c_str() + 9; + if (digits[0] == '0' && digits[1] != '\0') return false; + const auto bit = std::uint32_t{1} << index; + if (mask & bit) return false; + mask |= bit; + return true; + } + + bool requires(unsigned index) const + { + return index < 32 && (mask & (std::uint32_t{1} << index)) != 0; + } + + template + bool valid_for_srvs(const SrvVec& srvs) const + { + if (!mask) return true; + if (srvs.size() < 32 && (mask >> srvs.size()) != 0) return false; + for (std::size_t i = 0; i < srvs.size() && i < 32; ++i) { + if (requires(static_cast(i)) && (srvs[i].kind < 1 || srvs[i].kind > 5)) + return false; + } + return true; + } +}; + +// MostDetailedMip is the first field of every texture SRV in the union. +bool image_size_view_starts_at_resource_mip0(const D3D12_SHADER_RESOURCE_VIEW_DESC& desc) +{ + return desc.Texture2D.MostDetailedMip == 0; +} + // A pixel-stage image store (#1996 item F, #2742): tools/startup/gfx2hlsl.py writes 'uav N tex2d|tex2da table P O' // for the RWTexture2D or RWTexture2DArray at u, whose descriptor is at byte O of the title's // root table P. The native compiler also emits raw table views; a view qualifier or a 'channels' field, as in the compute line, is refused. @@ -169,6 +212,7 @@ struct Translation { x2w_startup::TranslatedSamplers samplers; x2w_startup::ExportWriteMasks write_masks; // manifest 'wmask': channels each export leaves unwritten (#1674) x2w_startup::D16ImageSrvs d16_srvs; // manifest 'd16srv': texture views that must match proven D16 formats (#2023) + ImageSizeSrvs image_size_srvs; // manifest 'imagedim': size-field reads that need resource mip 0 ID3DBlob* vs = nullptr; ID3DBlob* ps = nullptr; ID3D12RootSignature* root = nullptr; @@ -563,6 +607,11 @@ void load_translation(Translation& tr, const std::string& rtv_request = {}, std: log("x2w-draw invalid write mask manifest line for %016llx: %s", tr.key, line.c_str()); return; } + } else if (line.compare(0, 9, "imagedim ") == 0) { + if (!tr.image_size_srvs.read_manifest_line(line)) { + log("x2w-draw invalid imagedim manifest line for %016llx: %s", tr.key, line.c_str()); + return; + } } else if (line.compare(0, 7, "d16srv ") == 0) { if (!tr.d16_srvs.read_manifest_line(line)) { log("x2w-draw invalid d16srv manifest line for %016llx: %s", tr.key, line.c_str()); @@ -590,7 +639,8 @@ void load_translation(Translation& tr, const std::string& rtv_request = {}, std: log("x2w-draw RTV manifest missing for %016llx", tr.key); return; } - if (tr.uds.empty() || tr.uds.size() > 32 || tr.srvs.size() > 32 || !tr.d16_srvs.valid_for_srvs(tr.srvs)) return; + if (tr.uds.empty() || tr.uds.size() > 32 || tr.srvs.size() > 32 || !tr.d16_srvs.valid_for_srvs(tr.srvs) || + !tr.image_size_srvs.valid_for_srvs(tr.srvs)) return; for (const Translation::Ud& ud : tr.uds) { if (ud.kind == Translation::d16_unorm16 && (ud.a < 0 || static_cast(ud.a) >= tr.srvs.size() || !tr.d16_srvs.requires_exact(static_cast(ud.a)))) @@ -2354,6 +2404,7 @@ constexpr const char* indexed_rect_unavailable = "indexed_rect_unavailable"; constexpr const char* pipeline_unavailable = "pipeline_unavailable"; constexpr const char* sampler_heap_unavailable = "sampler_heap_unavailable"; constexpr const char* sampled_texture_mismatch = "sampled_texture_mismatch"; +constexpr const char* image_size_mip = "image_size_mip"; constexpr const char* sampled_texture_unbindable = "sampled_texture_unbindable"; constexpr const char* incomplete_vertex_stream = "incomplete_vertex_stream"; constexpr const char* incomplete_table_buffer = "incomplete_table_buffer"; @@ -3317,6 +3368,17 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI if (texture && record.desc_bytes >= 40) { std::memcpy(&desc, record.desc, 40); desc.Format = desktop_format(desc.Format); + if (tr->image_size_srvs.requires(i) && !image_size_view_starts_at_resource_mip0(desc)) { + static LONG refused; + if (first_calls(refused, 6)) + log("x2w-draw %016llx srv %u: image size field refused (view starts at mip %u)", + tr->key, i, desc.Texture2D.MostDetailedMip); + if (indirect) + indirect->set_refusal("translated draw reads an image size from a view that does not start at resource mip 0", + indirect_refusal_code::image_size_mip); + ReleaseSRWLockExclusive(&draw_lock); + return false; + } } if (texture && x2w_startup::packed_target_format(desc.Format)) { // The view recorded from the title names a packed format: follow a stand-in texture, diff --git a/tests/startup_gfx2hlsl_image_desc_word_check.py b/tests/startup_gfx2hlsl_image_desc_word_check.py index f676b8a6d6..79f9130a84 100644 --- a/tests/startup_gfx2hlsl_image_desc_word_check.py +++ b/tests/startup_gfx2hlsl_image_desc_word_check.py @@ -4,6 +4,8 @@ size fields lower to GetDimensions(0) on that texture. WIDTH minus one is split into word 1 bits 31:30 and word 2 bits 11:0. HEIGHT minus one is word 2 bits 27:14. DEPTH minus one is word 4 bits 12:0 and only for a 3D image. s_bfe_u32, s_and_b32 and s_lshr_b32 qualify only with that field's control or mask. +s_lshr_b32 also requires the descriptor word to be the value, not the shift amount. A translation +that reads a size field marks that SRV with imagedim. A sample that does not read one does not. Everything else stays refused: a whole word, any other word or field, a shift of word 2 that keeps the resource-level bit, depth of a 1D, 2D or 2D-array image, height of a 1D image, a modified word, m0, a @@ -56,6 +58,7 @@ def smem(op, sdata, sbase, offset=0): OPS = { 's_bfe_u32 s10, s17, 0x2001e': sop2(BFE, 10, 17, LIT, 0x2001e), 's_lshr_b32 s10, s17, 0x1e': sop2(LSHR, 10, 17, LIT, 30), + 's_lshr_b32 s10, 0x1e, s17': sop2(LSHR, 10, LIT, 17, 30), 's_and_b32 s10, s17, 0xc0000000': sop2(AND, 10, 17, LIT, 0xc0000000), 's_and_b32 s10, s18, 0xfff': sop2(AND, 10, 18, LIT, 0xfff), 's_and_b32 s11, s18, 0xfff': sop2(AND, 11, 18, LIT, 0xfff), @@ -175,6 +178,7 @@ def controls(): assert expr in text, (label, text) assert HELPERS[helper] in text, (label, text) assert 'srv 0 ' in manifest, (label, manifest) + assert '\nimagedim 0\n' in manifest, (label, manifest) without_field(code) composed = splice(WORDS['lz'], ( 's_bfe_u32 s10, s17, 0x2001e', @@ -193,6 +197,7 @@ def controls(): refused(splice(WORDS['lz'], ('v_mov_b32_e32 v4, s%d' % (16 + word),), 'image'), 'numeric use of s%d holding image descriptor word %d' % (16 + word, word)) refused(use('lz', 's_lshr_b32 s10, s18, 0xe'), 's_lshr_b32 of image descriptor word 2') + refused(use('lz', 's_lshr_b32 s10, 0x1e, s17'), 's_lshr_b32 of image descriptor word 1') refused(use('lz', 's_bfe_u32 s10, s18, 0xe000f'), 's_bfe_u32 of image descriptor word 2') refused(use('lz', 's_bfe_u32 s10, s19, 0x4000c'), 's_bfe_u32 of image descriptor word 3') refused(use('lz', 's_bfe_u32 s10, s21, 0x40004'), 's_bfe_u32 of image descriptor word 5') @@ -221,6 +226,8 @@ def controls(): refused(bare_buf, 'numeric use of s10 holding descnum') vertex = smem(0x03, 16, 8) + OPS['s_bfe_u32 s10, s17, 0x2001e'] + VMOV + VS_WORDS refused(WORDS['lz'], 'numeric use of s10 holding descnum', vs=vertex) + _sample, sample_manifest = ps(WORDS['lz']) + assert 'imagedim' not in sample_manifest, sample_manifest # The offset-32 load is read before the fixture's own offset-0 load. The sample uses offset 0, so # the earlier word must not borrow that dimension. The v_mov is after the image instruction. @@ -241,6 +248,7 @@ def controls(): text, manifest = ps(kept) assert W_HI in text, text assert manifest.count('\nsrv ') == 1 and 'srv 0 tex2d table 0 0' in manifest, manifest + assert '\nimagedim 0\n' in manifest and 'imagedim 1' not in manifest, manifest assert 'table 0 32' not in manifest, manifest without_field(kept) reloaded = splice(WORDS['lz'], ('s_mov_b32 s28, s18',), 'image') diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index ff3f8a7963..b0fe8da9f5 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -6059,13 +6059,23 @@ def image_word(self, reg): return (index % 8, dims[key], sym, modified) def image_dim_call(self, sym, kind, component): - """GetDimensions(0) of the texture this image descriptor binds, for one component.""" + """GetDimensions(0) of the texture this image descriptor binds, for one component. + + The SRV is marked in the manifest. The draw path refuses that view unless it starts at + resource mip 0, because GetDimensions(0) reads the view's first mip.""" base, dword = sym[2], sym[3] & ~7 - tex = self.pipe.resource((sym[1], None if base is None else base + 4 * dword), kind) + key = (sym[1], None if base is None else base + 4 * dword) + tex = self.pipe.resource(key, kind) helpers = getattr(self.pipe, 'image_dim_helpers', None) if helpers is None: helpers = self.pipe.image_dim_helpers = set() helpers.add((kind, component)) + marked = getattr(self.pipe, 'image_size_srvs', None) + if marked is None: + marked = self.pipe.image_size_srvs = set() + entry = self.pipe.resources.get(key) + if entry is not None: + marked.add(entry['index']) return 'img_%s_%s(%s)' % (component, kind, tex) def image_field_expr(self, base, srcs, syms): @@ -6088,7 +6098,9 @@ def image_field_expr(self, base, srcs, syms): if kind is None: hits.append(('opaque', field, base, 'word used as two dimensions')) continue - if base == 's_bfe_u32' and i != 0: + # s_bfe_u32 and s_lshr_b32 are not commutative. The descriptor word is the value + # (operand 0). A shift whose amount is the descriptor word is a different number. + if base in ('s_bfe_u32', 's_lshr_b32') and i != 0: hits.append(('opaque', field, base, '')) continue found = IMAGE_FIELDS.get((field, base, constants[1 - i])) @@ -12251,6 +12263,7 @@ def _init_pixel_context(self, root_blob, sampler_heap=None, rtv_formats=(), ps_h self.uses_cube_dir = False self.uses_gather_2d_lod = False self.image_dim_helpers = set() + self.image_size_srvs = set() self.uses_store_d16_x = False self.uses_dot2 = set() self.uses_sad = set() @@ -12997,6 +13010,8 @@ def manifest(self): lines.append('srv %d %s %s' % (r['index'], r['kind'], where)) if r.get('d16_exact'): lines.append('d16srv %d exact' % r['index']) + for index in sorted(getattr(self, 'image_size_srvs', ()) or ()): + lines.append('imagedim %d' % index) for key, r in sorted(self.stored_images().items(), key=lambda kv: kv[1]['index']): source, off = key if source[0] != 'table': From 1820f8763ce4488848e6701ab35edf17c72910bb Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sun, 29 Nov 2026 12:30:56 +0000 Subject: [PATCH 4/4] startup: test image size binds and refuse a null marked view A marked SRV is refused when MostDetailedMip is not 0 and when the direct draw would bind no texture. The imagedim parser and both refusals are covered without a device. An unmarked sample is unchanged. Co-authored-by: SimSalabimse --- CMakeLists.txt | 10 +++ CMakePresets.json | 5 +- docs/experiments.md | 2 +- src/startup_stubs/d3d12_draw.inl | 84 +++++++------------ src/startup_stubs/d3d12_xs_device.cpp | 1 + src/startup_stubs/image_size_mip.h | 69 ++++++++++++++++ tests/startup_image_size_mip_check.cpp | 109 +++++++++++++++++++++++++ 7 files changed, 222 insertions(+), 58 deletions(-) create mode 100644 src/startup_stubs/image_size_mip.h create mode 100644 tests/startup_image_size_mip_check.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 5eb5a82e13..63d344c393 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2736,6 +2736,16 @@ target_compile_features(startup_d16_image_format_check PRIVATE cxx_std_17) add_test(NAME startup_d16_image_format COMMAND startup_d16_image_format_check) add_test(NAME startup_d16_image_format_accept_uint_control COMMAND startup_d16_image_format_check --mutate accept-uint) set_tests_properties(startup_d16_image_format_accept_uint_control PROPERTIES WILL_FAIL TRUE) +# Image size-field manifest lines and the mip-0 / null-texture bind decision, without a device. +add_executable(startup_image_size_mip_check tests/startup_image_size_mip_check.cpp) +target_include_directories(startup_image_size_mip_check PRIVATE src) +target_compile_features(startup_image_size_mip_check PRIVATE cxx_std_17) +add_test(NAME startup_image_size_mip COMMAND startup_image_size_mip_check) +add_test(NAME startup_image_size_mip_drop_mip_control COMMAND startup_image_size_mip_check --mutate drop-mip) +add_test(NAME startup_image_size_mip_drop_null_control COMMAND startup_image_size_mip_check --mutate drop-null) +add_test(NAME startup_image_size_mip_reject_lines_control COMMAND startup_image_size_mip_check --mutate reject-lines) +set_tests_properties(startup_image_size_mip_drop_mip_control startup_image_size_mip_drop_null_control + startup_image_size_mip_reject_lines_control PROPERTIES WILL_FAIL TRUE) # Composite provenance (#1628): one VS and two pixel shaders from one HLSL file. set(startup_composite_provenance_headers "") foreach(stage IN ITEMS "vs_6_0;vs_main;vs" "ps_6_0;ps_fill;fill" "ps_6_0;ps_composite;composite") diff --git a/CMakePresets.json b/CMakePresets.json index 57f5998522..ab9dbb8dcb 100644 --- a/CMakePresets.json +++ b/CMakePresets.json @@ -34,7 +34,8 @@ "xmem_run_break_readers_check", "xmem_run_break_readers_control", "xmem_cross_call_merge_check", "xmem_placeholder_split_check", "xmem_map_split_first_check", "startup_dstorage_break_window_check", "xmem_page_runs_device_check", "linear_buffer_backing_check", - "bcpack_formats_check", "startup_stub_consumer", "startup_inline_retire", "startup_resource_retire_title", "startup_table_lock" + "bcpack_formats_check", "startup_stub_consumer", "startup_inline_retire", "startup_resource_retire_title", "startup_table_lock", + "startup_image_size_mip_check" ] }, { "name": "release", "configurePreset": "release" }, @@ -48,7 +49,7 @@ "displayName": "Windows pull request smoke tests", "filter": { "include": { - "name": "^(bcpack_all_formats(_golden_control)?|startup_bcpack_storage|desktop_root_signature|era_heap_(allocation|failure)|xmem_shim_mapped_pages|cpu_aot_fuzz_smoke|cpu_archive_texture_gpu_warp|dual_uav_warp|spirv_.*_warp|static_exe_intake|descriptor_heap_paging(_swapped)?_warp|startup_launch|startup_tools_lint|startup_gfx2hlsl_cvt_off_f32_i4_controls|startup_gfx2hlsl_sad_hi_msad_controls|startup_indirect_(dispatch|count_split|draw(_indexed)?|mesh(_xmem_arguments(_skip_wait)?)?|counts_control)_warp|startup_indirect_(dispatch|constants|count)_inline_warp|startup_inline_retire_(on|control)_warp|startup_resource_retire_title_inline_warp_debug0|startup_table_lock_(control_)?warp|startup_indirect_mesh_lease_warp_dual(-trace(-disabled)?)?|startup_shader_cache_key|startup_present_readback|xmem_(run_break_readers|cross_call_merge|placeholder_split|map_split_first)(_[a-z_]+)?|startup_dstorage_break_window(_[a-z_]+)?|xmem_page_runs_device(_join)?_warp|linear_buffer_backing_share_warp|startup_stage_package|startup_compute_packed_d16_x_uav_reference)$" + "name": "^(bcpack_all_formats(_golden_control)?|startup_bcpack_storage|desktop_root_signature|era_heap_(allocation|failure)|xmem_shim_mapped_pages|cpu_aot_fuzz_smoke|cpu_archive_texture_gpu_warp|dual_uav_warp|spirv_.*_warp|static_exe_intake|descriptor_heap_paging(_swapped)?_warp|startup_launch|startup_tools_lint|startup_gfx2hlsl_cvt_off_f32_i4_controls|startup_gfx2hlsl_sad_hi_msad_controls|startup_indirect_(dispatch|count_split|draw(_indexed)?|mesh(_xmem_arguments(_skip_wait)?)?|counts_control)_warp|startup_indirect_(dispatch|constants|count)_inline_warp|startup_inline_retire_(on|control)_warp|startup_resource_retire_title_inline_warp_debug0|startup_table_lock_(control_)?warp|startup_indirect_mesh_lease_warp_dual(-trace(-disabled)?)?|startup_shader_cache_key|startup_present_readback|xmem_(run_break_readers|cross_call_merge|placeholder_split|map_split_first)(_[a-z_]+)?|startup_dstorage_break_window(_[a-z_]+)?|xmem_page_runs_device(_join)?_warp|linear_buffer_backing_share_warp|startup_stage_package|startup_compute_packed_d16_x_uav_reference|startup_gfx2hlsl_image_desc_word_controls|startup_image_size_mip(_[a-z_]+)?)$" } } }, diff --git a/docs/experiments.md b/docs/experiments.md index f156da5db1..2eb06bee51 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -16940,7 +16940,7 @@ Reproduce: `ctest --preset dev --no-tests=error -R "^startup_gfx2hlsl_dpp_quad_b ### Pixel image descriptor size fields -A pixel stage can read the GFX10 size fields of an 8-dword image descriptor that an image instruction uses. `s_bfe_u32`, `s_and_b32` and `s_lshr_b32` lower only when the control or mask is exactly the field. WIDTH is word 1 bits 31:30 and word 2 bits 11:0, stored as width minus one. HEIGHT is word 2 bits 27:14, stored as height minus one. DEPTH is word 4 bits 12:0 and is lowered only for a 3D image. The HLSL reads that component from `GetDimensions(0)` on the texture the image instruction binds. The dimension is taken from the descriptor load that instruction reads, not from the register: a later or earlier load of a different descriptor into the same SGPRs does not borrow it. A copy of the sampled words keeps the load. `s_lshr_b32` lowers only when the descriptor word is the value being shifted. The manifest marks each such SRV with `imagedim `. The draw path refuses that view when the recorded descriptor's `MostDetailedMip` is not 0, because `GetDimensions(0)` is the view's first mip and the descriptor fields are resource mip 0. A sample that does not read a size field is not marked, so a shifted view can still be sampled. A whole word, any other word or field, a shift of word 2 that keeps the resource-level bit, depth of a 1D, 2D or 2D-array image, height of a 1D image, a modified word and `m0` stay refused. A 4-dword buffer descriptor and the compute and vertex stages are unchanged. +A pixel stage can read the GFX10 size fields of an 8-dword image descriptor that an image instruction uses. `s_bfe_u32`, `s_and_b32` and `s_lshr_b32` lower only when the control or mask is exactly the field. WIDTH is word 1 bits 31:30 and word 2 bits 11:0, stored as width minus one. HEIGHT is word 2 bits 27:14, stored as height minus one. DEPTH is word 4 bits 12:0 and is lowered only for a 3D image. The HLSL reads that component from `GetDimensions(0)` on the texture the image instruction binds. The dimension is taken from the descriptor load that instruction reads, not from the register: a later or earlier load of a different descriptor into the same SGPRs does not borrow it. A copy of the sampled words keeps the load. `s_lshr_b32` lowers only when the descriptor word is the value being shifted. The manifest marks each such SRV with `imagedim `. The draw path refuses that view when the recorded descriptor's `MostDetailedMip` is not 0, because `GetDimensions(0)` is the view's first mip and the descriptor fields are resource mip 0. It also refuses a marked SRV that has no texture, including on a direct draw, so the size is not taken from a null view. A sample that does not read a size field is not marked, so a shifted view can still be sampled and a null sample binding is unchanged. A whole word, any other word or field, a shift of word 2 that keeps the resource-level bit, depth of a 1D, 2D or 2D-array image, height of a 1D image, a modified word and `m0` stay refused. A 4-dword buffer descriptor and the compute and vertex stages are unchanged. ```powershell ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_image_desc_word' -V diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index 0d064ca463..6eb7ae7d5e 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -11,49 +11,6 @@ #include "startup_stubs/typed_uav_load.h" -// 'imagedim ': the pixel stage reads a GFX10 size field of SRV through GetDimensions(0). -// That is the view's first mip. It matches the descriptor only when the view starts at resource mip 0. -struct ImageSizeSrvs { - std::uint32_t mask = 0; - - bool read_manifest_line(const std::string& line) - { - int index = -1, used = 0; - if (std::sscanf(line.c_str(), "imagedim %d%n", &index, &used) != 1 || used != static_cast(line.size())) - return false; - if (index < 0 || index >= 32) return false; - const char* digits = line.c_str() + 9; - if (digits[0] == '0' && digits[1] != '\0') return false; - const auto bit = std::uint32_t{1} << index; - if (mask & bit) return false; - mask |= bit; - return true; - } - - bool requires(unsigned index) const - { - return index < 32 && (mask & (std::uint32_t{1} << index)) != 0; - } - - template - bool valid_for_srvs(const SrvVec& srvs) const - { - if (!mask) return true; - if (srvs.size() < 32 && (mask >> srvs.size()) != 0) return false; - for (std::size_t i = 0; i < srvs.size() && i < 32; ++i) { - if (requires(static_cast(i)) && (srvs[i].kind < 1 || srvs[i].kind > 5)) - return false; - } - return true; - } -}; - -// MostDetailedMip is the first field of every texture SRV in the union. -bool image_size_view_starts_at_resource_mip0(const D3D12_SHADER_RESOURCE_VIEW_DESC& desc) -{ - return desc.Texture2D.MostDetailedMip == 0; -} - // A pixel-stage image store (#1996 item F, #2742): tools/startup/gfx2hlsl.py writes 'uav N tex2d|tex2da table P O' // for the RWTexture2D or RWTexture2DArray at u, whose descriptor is at byte O of the title's // root table P. The native compiler also emits raw table views; a view qualifier or a 'channels' field, as in the compute line, is refused. @@ -212,7 +169,7 @@ struct Translation { x2w_startup::TranslatedSamplers samplers; x2w_startup::ExportWriteMasks write_masks; // manifest 'wmask': channels each export leaves unwritten (#1674) x2w_startup::D16ImageSrvs d16_srvs; // manifest 'd16srv': texture views that must match proven D16 formats (#2023) - ImageSizeSrvs image_size_srvs; // manifest 'imagedim': size-field reads that need resource mip 0 + x2w_startup::ImageSizeSrvs image_size_srvs; // manifest 'imagedim': size-field reads that need resource mip 0 ID3DBlob* vs = nullptr; ID3DBlob* ps = nullptr; ID3D12RootSignature* root = nullptr; @@ -2405,6 +2362,7 @@ constexpr const char* pipeline_unavailable = "pipeline_unavailable"; constexpr const char* sampler_heap_unavailable = "sampler_heap_unavailable"; constexpr const char* sampled_texture_mismatch = "sampled_texture_mismatch"; constexpr const char* image_size_mip = "image_size_mip"; +constexpr const char* image_size_null = "image_size_null"; constexpr const char* sampled_texture_unbindable = "sampled_texture_unbindable"; constexpr const char* incomplete_vertex_stream = "incomplete_vertex_stream"; constexpr const char* incomplete_table_buffer = "incomplete_table_buffer"; @@ -3368,17 +3326,6 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI if (texture && record.desc_bytes >= 40) { std::memcpy(&desc, record.desc, 40); desc.Format = desktop_format(desc.Format); - if (tr->image_size_srvs.requires(i) && !image_size_view_starts_at_resource_mip0(desc)) { - static LONG refused; - if (first_calls(refused, 6)) - log("x2w-draw %016llx srv %u: image size field refused (view starts at mip %u)", - tr->key, i, desc.Texture2D.MostDetailedMip); - if (indirect) - indirect->set_refusal("translated draw reads an image size from a view that does not start at resource mip 0", - indirect_refusal_code::image_size_mip); - ReleaseSRWLockExclusive(&draw_lock); - return false; - } } if (texture && x2w_startup::packed_target_format(desc.Format)) { // The view recorded from the title names a packed format: follow a stand-in texture, @@ -3453,6 +3400,33 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI x2w_startup::report_token_entry(line, sizeof(line), tr->key, i, entry, words); log("%s", line); } + // GetDimensions(0) is the view's first mip. A marked SRV is refused when that is not + // resource mip 0, and when there is no texture to read (a direct draw would otherwise + // bind null). An unmarked sample is unchanged. + const auto size_bind = x2w_startup::image_size_bind( + tr->image_size_srvs.marks(i), texture != nullptr, record.desc_bytes >= 40, + desc.Texture2D.MostDetailedMip); + if (size_bind != x2w_startup::ImageSizeBind::proceed) { + static LONG refused; + if (first_calls(refused, 6)) { + if (size_bind == x2w_startup::ImageSizeBind::refuse_null) + log("x2w-draw %016llx srv %u: image size field refused (no texture)", tr->key, i); + else + log("x2w-draw %016llx srv %u: image size field refused (view starts at mip %u)", + tr->key, i, desc.Texture2D.MostDetailedMip); + } + if (indirect) { + indirect->set_refusal( + size_bind == x2w_startup::ImageSizeBind::refuse_null + ? "translated draw reads an image size from a view with no texture" + : "translated draw reads an image size from a view that does not start at resource mip 0", + size_bind == x2w_startup::ImageSizeBind::refuse_null + ? indirect_refusal_code::image_size_null + : indirect_refusal_code::image_size_mip); + } + ReleaseSRWLockExclusive(&draw_lock); + return false; + } device_of(the_device)->CreateShaderResourceView(texture, texture && record.desc_bytes < 40 ? nullptr : &desc, dest); continue; } diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 3f8808e3a2..03576a3969 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -33,6 +33,7 @@ #include "startup_stubs/pso_recipe.h" #include "startup_stubs/depth_state_apply.h" #include "startup_stubs/d16_image_format.h" +#include "startup_stubs/image_size_mip.h" #include "startup_stubs/formatted_buffer.h" #include "startup_stubs/view_content_token.h" #include "startup_stubs/heap_indexed_root.h" diff --git a/src/startup_stubs/image_size_mip.h b/src/startup_stubs/image_size_mip.h new file mode 100644 index 0000000000..15cd53dbbd --- /dev/null +++ b/src/startup_stubs/image_size_mip.h @@ -0,0 +1,69 @@ +// Pixel image-descriptor size fields. gfx2hlsl writes 'imagedim ' when SRV is read +// through GetDimensions(0). That call is the view's first mip, so it matches the descriptor only when +// a texture is bound and the view starts at resource mip 0. An unmarked SRV is left alone. +#pragma once + +#include +#include + +namespace x2w_startup { + +enum class ImageSizeBind : std::uint8_t { + proceed = 0, + refuse_null = 1, + refuse_mip = 2, +}; + +struct ImageSizeSrvs { + std::uint32_t mask = 0; + + // Parses 'imagedim ' for 0 <= index < 32 without leading zeroes or duplicates. + bool read_manifest_line(std::string_view line) + { + constexpr std::string_view prefix = "imagedim "; + if (line.size() <= prefix.size() || line.substr(0, prefix.size()) != prefix) + return false; + const std::string_view digits = line.substr(prefix.size()); + if (digits.empty() || digits.size() > 2 || (digits.size() == 2 && digits[0] == '0')) + return false; + unsigned index = 0; + for (char c : digits) { + if (c < '0' || c > '9') return false; + index = index * 10u + static_cast(c - '0'); + } + if (index >= 32 || (mask & (std::uint32_t{1} << index)) != 0) return false; + mask |= std::uint32_t{1} << index; + return true; + } + + bool marks(unsigned index) const + { + return index < 32 && (mask & (std::uint32_t{1} << index)) != 0; + } + + template + bool valid_for_srvs(const SrvVec& srvs) const + { + if (!mask) return true; + if (srvs.size() < 32 && (mask >> srvs.size()) != 0) return false; + for (std::size_t i = 0; i < srvs.size() && i < 32; ++i) { + if (marks(static_cast(i)) && (srvs[i].kind < 1 || srvs[i].kind > 5)) + return false; + } + return true; + } +}; + +// marked: the SRV is named by imagedim. have_texture: a resource will be bound. +// have_recorded_desc: a 40-byte view descriptor was copied, so most_detailed_mip is MostDetailedMip. +// MostDetailedMip is the first field of every texture SRV in the union. +inline ImageSizeBind image_size_bind(bool marked, bool have_texture, bool have_recorded_desc, + std::uint32_t most_detailed_mip) +{ + if (!marked) return ImageSizeBind::proceed; + if (!have_texture) return ImageSizeBind::refuse_null; + if (have_recorded_desc && most_detailed_mip != 0) return ImageSizeBind::refuse_mip; + return ImageSizeBind::proceed; +} + +} // namespace x2w_startup diff --git a/tests/startup_image_size_mip_check.cpp b/tests/startup_image_size_mip_check.cpp new file mode 100644 index 0000000000..4dd3c25abc --- /dev/null +++ b/tests/startup_image_size_mip_check.cpp @@ -0,0 +1,109 @@ +// Unit check for src/startup_stubs/image_size_mip.h. No device: a non-square resource is the +// width and height below, and the two views are MostDetailedMip 0 and 1. +#include "startup_stubs/image_size_mip.h" + +#include +#include +#include +#include + +namespace { +struct FakeSrv { + int kind; +}; + +enum class Mutate { none, drop_mip, drop_null, reject_lines }; + +x2w_startup::ImageSizeBind bind(Mutate mutate, bool marked, bool have_texture, bool have_desc, + std::uint32_t most_detailed_mip) +{ + const auto got = x2w_startup::image_size_bind(marked, have_texture, have_desc, most_detailed_mip); + if (mutate == Mutate::drop_mip && got == x2w_startup::ImageSizeBind::refuse_mip) + return x2w_startup::ImageSizeBind::proceed; + if (mutate == Mutate::drop_null && got == x2w_startup::ImageSizeBind::refuse_null) + return x2w_startup::ImageSizeBind::proceed; + return got; +} + +bool read_line(Mutate mutate, x2w_startup::ImageSizeSrvs& srvs, std::string_view line) +{ + if (mutate == Mutate::reject_lines) return false; + return srvs.read_manifest_line(line); +} +} // namespace + +int main(int argc, char** argv) +{ + Mutate mutate = Mutate::none; + if (argc == 3 && std::strcmp(argv[1], "--mutate") == 0) { + if (std::strcmp(argv[2], "drop-mip") == 0) mutate = Mutate::drop_mip; + else if (std::strcmp(argv[2], "drop-null") == 0) mutate = Mutate::drop_null; + else if (std::strcmp(argv[2], "reject-lines") == 0) mutate = Mutate::reject_lines; + else return 2; + } else if (argc != 1) { + return 2; + } + + // Non-square resource, 8 by 4. Mip 0 of a marked SRV is allowed. MostDetailedMip 1 is refused. + constexpr std::uint32_t width = 8; + constexpr std::uint32_t height = 4; + if (width == height || width != 8u || height != 4u) return 1; + if (bind(mutate, true, true, true, 0) != x2w_startup::ImageSizeBind::proceed) { + std::fprintf(stderr, "mip 0 of %u x %u refused\n", static_cast(width), static_cast(height)); + return 1; + } + if (bind(mutate, true, true, true, 1) != x2w_startup::ImageSizeBind::refuse_mip) { + std::fprintf(stderr, "MostDetailedMip 1 of %u x %u was not refused\n", + static_cast(width), static_cast(height)); + return 1; + } + // No recorded descriptor: the stand-in view starts at mip 0, so a live texture is allowed. + if (bind(mutate, true, true, false, 1) != x2w_startup::ImageSizeBind::proceed) return 1; + // A marked SRV with no texture is refused on a direct draw. An unmarked one still binds. + if (bind(mutate, true, false, true, 0) != x2w_startup::ImageSizeBind::refuse_null) { + std::fprintf(stderr, "marked SRV with no texture was not refused\n"); + return 1; + } + if (bind(mutate, true, false, false, 1) != x2w_startup::ImageSizeBind::refuse_null) return 1; + if (bind(mutate, false, false, true, 1) != x2w_startup::ImageSizeBind::proceed) return 1; + if (bind(mutate, false, true, true, 1) != x2w_startup::ImageSizeBind::proceed) return 1; + + x2w_startup::ImageSizeSrvs srvs; + if (srvs.mask != 0 || !srvs.valid_for_srvs(std::vector{})) return 1; + if (!read_line(mutate, srvs, "imagedim 0") || !read_line(mutate, srvs, "imagedim 31")) { + std::fprintf(stderr, "imagedim 0 or 31 refused\n"); + return 1; + } + if (!srvs.marks(0) || !srvs.marks(31) || srvs.marks(1) || srvs.marks(32)) return 1; + + constexpr const char* bad_lines[] = { + "imagedim 0", // duplicate + "imagedim 00", // leading zero + "imagedim 01", // leading zero + "imagedim 32", // out of range + "imagedim -1", // negative + "imagedim ", // missing index + "imagedim 2 ", // trailing space + "wmask 0 0x1", // wrong tag + }; + for (const char* bad : bad_lines) { + if (read_line(mutate, srvs, bad)) { + std::fprintf(stderr, "accepted bad manifest line: %s\n", bad); + return 1; + } + } + + std::vector bindings(32, FakeSrv{1}); + if (!srvs.valid_for_srvs(bindings)) return 1; + bindings[31].kind = 5; + if (!srvs.valid_for_srvs(bindings)) return 1; + bindings[0].kind = 0; + if (srvs.valid_for_srvs(bindings)) return 1; + bindings[0].kind = 3; + bindings.pop_back(); + if (srvs.valid_for_srvs(bindings)) return 1; + + std::printf("image_size_mip: non-square %u x %u mip 0 allowed, MostDetailedMip 1 refused, null marked SRV refused, imagedim parser verified\n", + static_cast(width), static_cast(height)); + return 0; +}