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 8b5b46c435..b2ade8b9b0 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 df3f0e36b4..d1d0e93b3a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3977,6 +3977,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/CMakePresets.json b/CMakePresets.json index 8fff29df28..91e9b7f6b5 100644 --- a/CMakePresets.json +++ b/CMakePresets.json @@ -48,7 +48,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_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)$" + "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|image_desc_word|sad_hi_msad)_controls|startup_indirect_(dispatch|count_split|draw(_indexed)?|mesh(_xmem_arguments(_skip_wait)?)?|counts_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)$" } } }, diff --git a/docs/experiments.md b/docs/experiments.md index 75d3674ea3..b4f7b902be 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -16924,6 +16924,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. 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 +``` + ## 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/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index 3d18422106..563d89d9ec 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. @@ -167,6 +210,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; @@ -496,6 +540,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()); @@ -522,7 +571,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)))) @@ -2181,6 +2231,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"; @@ -2886,6 +2937,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 new file mode 100644 index 0000000000..45aff98fe9 --- /dev/null +++ b/tests/startup_gfx2hlsl_image_desc_word_check.py @@ -0,0 +1,292 @@ +"""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. +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 +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 +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) + assert '\nimagedim 0\n' 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_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') + 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') + overwritten = splice(WORDS['lz'], ( + 's_add_u32 s17, s17, 1', + 's_bfe_u32 s10, s17, 0x2001e', + 'v_mov_b32_e32 v4, s10', + ), 'image') + refused(overwritten, 'numeric use of s10 holding descnum') + + # The upper image in an x16 load is a distinct descriptor even though it shares the load's table address. + x16 = WORDS['lz'].replace(smem(0x03, 16, 8), smem(0x04, 16, 8), 1) + assert x16 != WORDS['lz'] + load_end = x16.index(smem(0x04, 16, 8)) + len(smem(0x04, 16, 8)) + copies = b''.join(OPS['s_mov_b32 s%d, s%d' % (40 + i, 24 + i)] for i in range(8)) + x16 = x16[:load_end] + copies + x16[load_end:] + x16 = splice(x16, ('s_and_b32 s10, s42, 0xfff', 'v_mov_b32_e32 v4, s10'), 'after-image') + refused(x16, 'numeric use of s10 holding descnum') + + # The conservative pre-scan refuses a branched program even when the branch is after the sample. + branched = use('lz', 's_bfe_u32 s10, s17, 0x2001e') + end_at = next(off for off, _n, name, _asm in G.decode(branched) if name == 's_endpgm') + branched = branched[:end_at] + bytes.fromhex('000084bf') + branched[end_at:] + refused(branched, 'numeric use of s10 holding descnum') + + 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) + _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. + 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 '\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') + 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') + + +if __name__ == '__main__': + controls() diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 9ed3372a55..dba1080214 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:] @@ -1017,6 +1027,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 +2594,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 +2704,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 +2730,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 +3101,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 +4113,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 +4123,7 @@ def translate(self): self.vconst = {} self.blocks = [] # (offset, [lines], terminator) self.sym = dict(init_sym) + self.image_span = {} self.exec_known = init_exec_known self.wqm_exec = init_wqm_exec self.wqm_count, self.execcopy_epoch = 0, {} @@ -5898,6 +5954,179 @@ def _complete_resheap_carry(self, base, ops, mods): self.scc_verified = False return True + def note_image_descriptors(self): + """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': + 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: + 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 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) + 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 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_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: + return None + count, index = span + if count not in (8, 16) or sym[3] != index: + return None + 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. + + 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 + 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): + """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 + # 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])) + 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 @@ -6011,10 +6240,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) @@ -6039,10 +6267,19 @@ def src_sym(t): self.resheap_low_add = (dst[1], self.pc + size, heap_mark) self.scc_verified = True return None + # After the resource-heap add returns: a pixel size field is not that pointer add. + 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') + 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') @@ -6055,13 +6292,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). @@ -6087,7 +6330,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 @@ -6881,6 +7130,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 @@ -11897,6 +12150,8 @@ 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.image_size_srvs = set() self.uses_store_d16_x = False self.uses_sad = set() self.uses_dot8 = set() @@ -12174,6 +12429,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(): @@ -12593,6 +12852,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':