upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorJan Trencansky <jan.trencansky@protonmail.com>2026-11-27 06:39:35 -0500
committerJan Trencansky <jan.trencansky@protonmail.com>2026-11-27 06:39:35 -0500
commitb0712ff2ce72796d0db2d833ec3d5d0a542e2142 (patch)
tree2553007a564e692af4aff036e43c98a1b4b31c06
parent23c33411962b84ecae28f4e82bd62fc6fba79444 (diff)
parent3c9820f8daae7e478cdca7f7e1d395e60d7c4ddf (diff)
Merge test/round2 into heaps-in-place: per-piece sums and the T# index word for heaps read in place
title_mirror.h: a filtered page's sums per 256-byte piece are of the title's bytes (title compared with title); the filter runs after that compare, only when a piece changed or the home is fresh, and writes the home. write_back skips a filtered home, so page_mirror_write_back takes TitleMirror::write_back as is. A home leaving its filter is copied whole once. The T# index word (tsharp_index_word) is written by finish_in_place into the home's dword 6 once the T# is bound; the filter leaves 0 (the fallback) there meanwhile, so the title's own dword 6 is never read as an index. Copy-path heaps keep fix_console_slot's write. d3d12_heap_in_place_test checks a T# slot reads the tag and index while the title's bytes keep their dword 6; title_mirror_hooks_test checks write-back skips filtered homes and the filter is not called again for unchanged title bytes. set_tsharp_index_words_for_test for the test. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
-rw-r--r--docs/d3d12_vulkan.md18
-rw-r--r--docs/design.md1
-rw-r--r--make_game.py2
-rw-r--r--runtime/CMakeLists.txt6
-rw-r--r--runtime/README.md2
-rw-r--r--runtime/cmake/translator_deps.cmake2
-rw-r--r--runtime/shims/d3d12_com.h6
-rw-r--r--runtime/shims/d3d12_vulkan_device.cpp238
-rw-r--r--runtime/shims/xmem.cpp79
-rw-r--r--runtime/src/gfx10_descriptors.h39
-rw-r--r--runtime/src/shader_library.h23
-rw-r--r--runtime/src/title_heap.h207
-rw-r--r--runtime/src/title_mirror.h114
-rw-r--r--runtime/test/d3d12_heap_in_place_test.cpp50
-rw-r--r--runtime/test/d3d12_page_mirror_test.cpp40
-rw-r--r--runtime/test/gfx10_descriptors_test.cpp20
-rw-r--r--runtime/test/shader_library_test.cpp26
-rw-r--r--runtime/test/shaders/ps_table_fetch.asm3
-rw-r--r--runtime/test/shaders/ps_texture_sample.asm5
-rw-r--r--runtime/test/title_heap_test.cpp130
-rw-r--r--runtime/test/title_mirror_hooks_test.cpp16
-rw-r--r--runtime/test/vk_texture_test.cpp18
-rw-r--r--tests/semantic/fixtures/disasm/ps_tsharp_index_word.s25
-rw-r--r--tests/semantic/test_sampled_dynamic_index.py5
-rw-r--r--tests/semantic/test_tsharp_index_word.py189
-rw-r--r--tests/test_desc_cache.py11
-rw-r--r--tests/test_image_load_typed.py16
-rw-r--r--tools/descriptor_source_census.py326
-rw-r--r--tools/descriptor_sources.py269
-rw-r--r--tools/rdna2spirv.py101
30 files changed, 1888 insertions, 99 deletions
diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md
index cd325bded..bd7acdb11 100644
--- a/docs/d3d12_vulkan.md
+++ b/docs/d3d12_vulkan.md
@@ -2202,8 +2202,12 @@ The game can use D3D12 descriptors in three ways, and the layer must handle all
2202 any reader names title memory) or in a buffer of ours as the title wrote it (`reachable_as_written`), other words 2202 any reader names title memory) or in a buffer of ours as the title wrote it (`reachable_as_written`), other words
2203 null. The filter runs inside the mirror's fills, under its lock, so it takes no other lock of ours: a V# the mirror 2203 null. The filter runs inside the mirror's fills, under its lock, so it takes no other lock of ours: a V# the mirror
2204 does not hold (an interim, until every title allocation is in the mirror) reads null until the heap's refresh 2204 does not hold (an interim, until every title allocation is in the mirror) reads null until the heap's refresh
2205 resolves it as a copied slot was, and a T# is bound there too (its bindless index in the entry comes later), each 2205 resolves it as a copied slot was, and a T# is bound there too, its home dword 6 then taking the bindless index word
2206 result written into the home unless the title rewrote the slot meanwhile (`finish_in_place`). Lock order: 2206 (`tsharp_index_word`, docs/design.md "Bindless index in the T#"; 0, the fallback, from the filter until then and
2207 while the T# waits; the title's dword 6 stays in its bytes), each result written into the home unless the title
2208 rewrote the slot meanwhile (`finish_in_place`). The upload's sums per 256-byte piece are of the title's bytes for
2209 such a page, so the mirror calls the filter only when a piece of the title's page changed, and `write_back` skips
2210 it. Lock order:
2207 `console_heap_mutex`, then the mirror's, then the change list's. The changes are applied to the homes at the 2211 `console_heap_mutex`, then the mirror's, then the change list's. The changes are applied to the homes at the
2208 mirror's refresh, before the pages written since are filled. No GPU write is ever copied back from these pages 2212 mirror's refresh, before the pages written since are filled. No GPU write is ever copied back from these pages
2209 (`TitleMirror::filtered_at`). A heap the mirror does not hold (a device without the mirror, memory outside its 2213 (`TitleMirror::filtered_at`). A heap the mirror does not hold (a device without the mirror, memory outside its
@@ -2235,7 +2239,9 @@ The layer's descriptor model:
2235 which is the assumption to verify. If it uses an opaque format, the layer must translate at bind time. 2239 which is the assumption to verify. If it uses an opaque format, the layer must translate at bind time.
2236- At execution, for each bound table (or the whole bound heap when direct indexing is enabled), the layer walks 2240- At execution, for each bound table (or the whole bound heap when direct indexing is enabled), the layer walks
2237 the declared descriptor range with the heap's stride, parses each T#/S#, and ensures a bindless entry exists: 2241 the declared descriptor range with the heap's stride, parses each T#/S#, and ensures a bindless entry exists:
2238 - image T# → `VkImageView` (format, view type, mip range, array layers) → bindless image index; 2242 - image T# → `VkImageView` (format, view type, mip range, array layers) → bindless image index, which the layer
2243 writes into dword 6 of the T# where shaders read it (the console heap copy's slot, or the layer's own heap), with
2244 the arrays it is bound in (`docs/design.md`, "Bindless index in the T#"); the hash table keeps the key as written;
2239 - sampler S# → `VkSampler` (filter, address modes, LOD, compare, anisotropy) → bindless sampler index; 2245 - sampler S# → `VkSampler` (filter, address modes, LOD, compare, anisotropy) → bindless sampler index;
2240 - buffer V# / CBV → no Vulkan view; the descriptor already contains a console VA the shader dereferences. 2246 - buffer V# / CBV → no Vulkan view; the descriptor already contains a console VA the shader dereferences.
2241- **Buffer UAVs.** `CreateUnorderedAccessView` on a buffer writes a V# in the first 16 bytes of the slot (the rest of 2247- **Buffer UAVs.** `CreateUnorderedAccessView` on a buffer writes a V# in the first 16 bytes of the slot (the rest of
@@ -4801,6 +4807,12 @@ store, load, mesh, geometry and BVH tests; this layer is the other half.
4801 4807
4802### 5.1 Descriptor hash table details 4808### 5.1 Descriptor hash table details
4803 4809
4810Since the T# index word (`docs/design.md`, "Bindless index in the T#") the table serves only what the word does not
4811reach: every S#, and the T#s a translated module cannot trace to a heap slot (1,062 of the 439,415 T# operands of
4812the 1.0.2.1 corpus, in 108 modules). A T# loaded from a heap the layer writes carries its index and kind in dword 6
4813and is never looked up. Every T# key is still inserted, as the title wrote it: a T# outside the heaps is found by
4814those words.
4815
4804The exact layout the shader reads (from `tools/rdna2spirv.py`, `desc_lookup`): 4816The exact layout the shader reads (from `tools/rdna2spirv.py`, `desc_lookup`):
4805 4817
4806``` 4818```
diff --git a/docs/design.md b/docs/design.md
index 7d7f80949..96f13981b 100644
--- a/docs/design.md
+++ b/docs/design.md
@@ -329,6 +329,7 @@ How the generated SPIR-V expects the runtime to work:
329| Images and samplers (core) | Bindless. Set 0: binding 0 = 2D sampled images, 1 = samplers, 2 = descriptor hash table (storage buffer), 3 = 2D-array images (**cube textures are bound here as 6-layer 2D-array views**, cube arrays as 6N layers: the shader already selected the face with `v_cube*`), 4 = r32ui storage images, 5 = 1D, 6 = 3D. A cube sample's s and t come in [1, 2] and its third coordinate is 8·slice + face, as the hardware takes them (Mesa `ac_nir_lower_tex_coords.c`, LLPC `ImageBuilder.cpp`); the view is read at (s − 1, t − 1), layer 6·slice + face. GPU-checked with `runtime/test/shaders/ps_cube_sample.asm` (`vk_texture_test cube`). For a native Metal path, `tools/spirv_metal_set0.py` sizes set 0's runtime arrays from `vulkan_bindless.h` and moves each binding to its own argument-buffer ID range (binding b starts at the capacities of bindings 0..b-1 added up), to convert with SPIRV-Cross `--msl-decoration-binding`: SPIRV-Cross 1.4.363.0 otherwise puts every runtime array at one ID and comments all but one out as "Overlapping binding" (SHADER-161). `cs_imgstore` converted this way writes all 3×64 texels correctly in a native Metal dispatch on an Apple A18 Pro. | 329| Images and samplers (core) | Bindless. Set 0: binding 0 = 2D sampled images, 1 = samplers, 2 = descriptor hash table (storage buffer), 3 = 2D-array images (**cube textures are bound here as 6-layer 2D-array views**, cube arrays as 6N layers: the shader already selected the face with `v_cube*`), 4 = r32ui storage images, 5 = 1D, 6 = 3D. A cube sample's s and t come in [1, 2] and its third coordinate is 8·slice + face, as the hardware takes them (Mesa `ac_nir_lower_tex_coords.c`, LLPC `ImageBuilder.cpp`); the view is read at (s − 1, t − 1), layer 6·slice + face. GPU-checked with `runtime/test/shaders/ps_cube_sample.asm` (`vk_texture_test cube`). For a native Metal path, `tools/spirv_metal_set0.py` sizes set 0's runtime arrays from `vulkan_bindless.h` and moves each binding to its own argument-buffer ID range (binding b starts at the capacities of bindings 0..b-1 added up), to convert with SPIRV-Cross `--msl-decoration-binding`: SPIRV-Cross 1.4.363.0 otherwise puts every runtime array at one ID and comments all but one out as "Overlapping binding" (SHADER-161). `cs_imgstore` converted this way writes all 3×64 texels correctly in a native Metal dispatch on an Apple A18 Pro. |
330| Typed buffer loads | The format is V# word3[18:12] (GFX10_FORMAT, from Mesa's `gfx10-rsrc.json`, saved as `tools\gfx10_formats.json`). Supported: f32 ×1–4, u32 ×1–4, i32 ×1–4 (formats 21/63/73/76), f16 ×1/2/4, unorm8 ×1/2/4, snorm8 ×1/2/4, uint8 ×1/2/4, sint8 ×1/2/4, unorm16 ×1/2/4, snorm16 ×1/2/4, uint16 ×1/2/4, sint16 ×1/2/4, 10-10-10-2 and 2-10-10-10 unorm, and, since 2026-11-22, the other GFX10 buffer codes 1–77 (every USCALED/SSCALED, 10_11_11 and 11_11_10 FLOAT, the 10_10_10_2 and 2_10_10_10 families, 8_8_8_8 and 16_16_16_16 SINT and SCALED; see *Typed buffer formats*). Others (code 0 and 78 up) give 0. The 8- and 16-bit UINT/SINT formats 5, 6, 11, 12, 18, 19, 28, 61 and 70 were missing until 2026-11-22 and read 0: UINT channels zero-extend, SINT channels sign-extend, d16 packs them as 16-bit integers, measured natively on gfx1036 (wave32 and wave64) with `tools/hw_oracle` and checked word for word by `tests/semantic/test_buffer_format_narrow_int.py`; GPU-checked by `runtime/test/shaders/cs_fmt_int_narrow.asm`, whose 136 expected words are the same program run natively on gfx1036 (exact on an RTX 5080 and on the gfx1036 iGPU through Vulkan). Full-width SINT accesses preserve integer bits. D16 SINT loads saturate to signed 16-bit and D16 stores sign-extend, covered by the synthetic `cs_fmt_sint32.asm` readback. DST_SEL swizzle is applied (0→0, 1→1.0f for float/norm or integer 1 for UINT/SINT, 4..7→X..W). Missing channels repeat the format's own (component *c* = *c* mod *n*), measured on an RX 6700 (SHADER-86). UNORM/SNORM give the correctly rounded quotient by (2ⁿ−1), as the hardware does (0 mismatches vs hardware over 395,776 conversions on that GPU). It is built with integer ops (`Gen.norm_bits`): x/(2ⁿ−1) in binary is x's bits repeated, so a 64-bit multiply by the repeat pattern, `FindUMsb` and the round bit give the f32 exactly (the tail never ends, so there are no ties). `OpFDiv` is not enough on the GPU: Vulkan allows it 2.5 ULP, and on an RX 6700 (AMD Windows 26.11.2) and an RTX 5090 it returned the reciprocal-multiply bits (8_UNORM 130/256 exact, #599). Checked against exact values in `tests/semantic/test_norm_decode.py` (every value up to 8 bits, edges and the reciprocal-multiply misses for 10, 15 and 16 bits). 8_SNORM (2), 16_SNORM (8) and 8_8_SNORM (15) were missing until 2026-11-22 and decoded to 0. Format names list the channel widths from the top bit, so `2_10_10_10` (50) is R10G10B10A2 and `10_10_10_2` (44) has a 2-bit x (Mesa `gfx10_format_table.py`, `ac_formats.c`). Until 2026-11-22 the two were swapped, in stores too. Until 2026-11-21 an element that started mid-dword re-read dword 0 for its tail (`need` was `ceil(size/4)` and only the first dword was shifted); loads now take `need = ceil((byte_shift + size) / 4)` dwords and shift the whole window so the packed stream starts at the element (FUZZ-5, leftover from #234). The 10:10:10:2 order is checked by `cs_fmt_1010102` in `tests/semantic/test_value_semantics.py` (the shader decodes the format, so a GPU run can't check it). Mid-dword spanning elements are checked by `tests/semantic/test_buffer_load_format.py` (`CrossingDwordBoundary`); repeat / UNORM / DST_SEL 1 by the SHADER-86 cases in the same file. The `_xy` and `_xyz` forms (buffer and tbuffer) are GPU-checked by `cs_fmt_xy_xyz.asm`, whose words were measured natively on a Radeon 680M (gfx1035, RDNA2): they write only their 2 or 3 VGPRs, and missing channels repeat there too (TEST-185). | 330| Typed buffer loads | The format is V# word3[18:12] (GFX10_FORMAT, from Mesa's `gfx10-rsrc.json`, saved as `tools\gfx10_formats.json`). Supported: f32 ×1–4, u32 ×1–4, i32 ×1–4 (formats 21/63/73/76), f16 ×1/2/4, unorm8 ×1/2/4, snorm8 ×1/2/4, uint8 ×1/2/4, sint8 ×1/2/4, unorm16 ×1/2/4, snorm16 ×1/2/4, uint16 ×1/2/4, sint16 ×1/2/4, 10-10-10-2 and 2-10-10-10 unorm, and, since 2026-11-22, the other GFX10 buffer codes 1–77 (every USCALED/SSCALED, 10_11_11 and 11_11_10 FLOAT, the 10_10_10_2 and 2_10_10_10 families, 8_8_8_8 and 16_16_16_16 SINT and SCALED; see *Typed buffer formats*). Others (code 0 and 78 up) give 0. The 8- and 16-bit UINT/SINT formats 5, 6, 11, 12, 18, 19, 28, 61 and 70 were missing until 2026-11-22 and read 0: UINT channels zero-extend, SINT channels sign-extend, d16 packs them as 16-bit integers, measured natively on gfx1036 (wave32 and wave64) with `tools/hw_oracle` and checked word for word by `tests/semantic/test_buffer_format_narrow_int.py`; GPU-checked by `runtime/test/shaders/cs_fmt_int_narrow.asm`, whose 136 expected words are the same program run natively on gfx1036 (exact on an RTX 5080 and on the gfx1036 iGPU through Vulkan). Full-width SINT accesses preserve integer bits. D16 SINT loads saturate to signed 16-bit and D16 stores sign-extend, covered by the synthetic `cs_fmt_sint32.asm` readback. DST_SEL swizzle is applied (0→0, 1→1.0f for float/norm or integer 1 for UINT/SINT, 4..7→X..W). Missing channels repeat the format's own (component *c* = *c* mod *n*), measured on an RX 6700 (SHADER-86). UNORM/SNORM give the correctly rounded quotient by (2ⁿ−1), as the hardware does (0 mismatches vs hardware over 395,776 conversions on that GPU). It is built with integer ops (`Gen.norm_bits`): x/(2ⁿ−1) in binary is x's bits repeated, so a 64-bit multiply by the repeat pattern, `FindUMsb` and the round bit give the f32 exactly (the tail never ends, so there are no ties). `OpFDiv` is not enough on the GPU: Vulkan allows it 2.5 ULP, and on an RX 6700 (AMD Windows 26.11.2) and an RTX 5090 it returned the reciprocal-multiply bits (8_UNORM 130/256 exact, #599). Checked against exact values in `tests/semantic/test_norm_decode.py` (every value up to 8 bits, edges and the reciprocal-multiply misses for 10, 15 and 16 bits). 8_SNORM (2), 16_SNORM (8) and 8_8_SNORM (15) were missing until 2026-11-22 and decoded to 0. Format names list the channel widths from the top bit, so `2_10_10_10` (50) is R10G10B10A2 and `10_10_10_2` (44) has a 2-bit x (Mesa `gfx10_format_table.py`, `ac_formats.c`). Until 2026-11-22 the two were swapped, in stores too. Until 2026-11-21 an element that started mid-dword re-read dword 0 for its tail (`need` was `ceil(size/4)` and only the first dword was shifted); loads now take `need = ceil((byte_shift + size) / 4)` dwords and shift the whole window so the packed stream starts at the element (FUZZ-5, leftover from #234). The 10:10:10:2 order is checked by `cs_fmt_1010102` in `tests/semantic/test_value_semantics.py` (the shader decodes the format, so a GPU run can't check it). Mid-dword spanning elements are checked by `tests/semantic/test_buffer_load_format.py` (`CrossingDwordBoundary`); repeat / UNORM / DST_SEL 1 by the SHADER-86 cases in the same file. The `_xy` and `_xyz` forms (buffer and tbuffer) are GPU-checked by `cs_fmt_xy_xyz.asm`, whose words were measured natively on a Radeon 680M (gfx1035, RDNA2): they write only their 2 or 3 VGPRs, and missing channels repeat there too (TEST-185). |
331| Descriptor hash table | `uint mask; entries[mask+1] of 10 uints: key[0..7], index, kind`. The last word is 0 in an empty slot; otherwise bit 31 marks it occupied and bits 0..5 / 8..11 name the sampled / storage arrays the index is bound in (docs/d3d12_vulkan.md section 5.1, "Images and samplers (T# dimension)" below). A module reads it only when its index entry says `"descriptor_table": "tagged"`; `--descriptor-table plain` leaves the word unread and gives byte-identical modules to the translator before the marker (checked with a 5-instruction pixel shader: old and plain output are the same bytes). The key is a T# or a padded S#. FNV-1a over the eight key words selects the first slot by default. With `--descriptor-hash=fnv1a_fmix32` the shader applies MurmurHash3 fmix32 before masking the slot. Every translated module then records `"descriptor_hash": "fnv1a_fmix32"` in its index entry. An absent key means `fnv1a`. The runtime and shader must select the same hash. The shared SPIR-V lookup probes up to eight slots and returns index 0 on a miss. The runtime supplies a fallback at index 0 and maps live descriptor keys to bindless indices. Outside the wave64 emulation, the lookup's result goes through `OpGroupNonUniformBroadcastFirst` before it indexes the image or sampler array. The lookup key words come from SGPRs, so every invocation in a subgroup has the same index; the broadcast is an identity on all drivers and marks the value uniform for the compiler. It declares `GroupNonUniform` and `GroupNonUniformBallot`, without a shuffle capability or subgroup-lane input. The shader index records the capabilities; its `features` field lists optional Vulkan device features. Mesa ANV 26.2.7 on an Intel Alder Lake-S UHD (Xe-LP, Linux) segfaults in `vkCreate*Pipelines` on a sampler index taken straight from the probe loop when that sampler serves both a float and an integer image (`cs_sample_lz_int_d16`, `ps_ssharp`); with the broadcast both pass. Checked by the unit test `test_lookup_result_is_broadcast_before_use` in `tests/test_desc_cache.py` (standard library only: no GPU, LLVM or SPIRV-Tools). | 331| Descriptor hash table | `uint mask; entries[mask+1] of 10 uints: key[0..7], index, kind`. The last word is 0 in an empty slot; otherwise bit 31 marks it occupied and bits 0..5 / 8..11 name the sampled / storage arrays the index is bound in (docs/d3d12_vulkan.md section 5.1, "Images and samplers (T# dimension)" below). A module reads it only when its index entry says `"descriptor_table": "tagged"`; `--descriptor-table plain` leaves the word unread and gives byte-identical modules to the translator before the marker (checked with a 5-instruction pixel shader: old and plain output are the same bytes). The key is a T# or a padded S#. FNV-1a over the eight key words selects the first slot by default. With `--descriptor-hash=fnv1a_fmix32` the shader applies MurmurHash3 fmix32 before masking the slot. Every translated module then records `"descriptor_hash": "fnv1a_fmix32"` in its index entry. An absent key means `fnv1a`. The runtime and shader must select the same hash. The shared SPIR-V lookup probes up to eight slots and returns index 0 on a miss. The runtime supplies a fallback at index 0 and maps live descriptor keys to bindless indices. Outside the wave64 emulation, the lookup's result goes through `OpGroupNonUniformBroadcastFirst` before it indexes the image or sampler array. The lookup key words come from SGPRs, so every invocation in a subgroup has the same index; the broadcast is an identity on all drivers and marks the value uniform for the compiler. It declares `GroupNonUniform` and `GroupNonUniformBallot`, without a shuffle capability or subgroup-lane input. The shader index records the capabilities; its `features` field lists optional Vulkan device features. Mesa ANV 26.2.7 on an Intel Alder Lake-S UHD (Xe-LP, Linux) segfaults in `vkCreate*Pipelines` on a sampler index taken straight from the probe loop when that sampler serves both a float and an integer image (`cs_sample_lz_int_d16`, `ps_ssharp`); with the broadcast both pass. Checked by the unit test `test_lookup_result_is_broadcast_before_use` in `tests/test_desc_cache.py` (standard library only: no GPU, LLVM or SPIRV-Tools). |
332| Bindless index in the T# | On the console a texture access loads the T# and samples; the hash-table lookup above made every access hash the eight T# words and probe up to eight table slots (in `3TL_PS_NoDir_PBR_MATERIAL_STANDARD_42ad1e50`, the tiled-lighting pixel shader, 62 lookups and 19,714 RADV instructions against 3,080 in the native program). **What pack and runtime agree on:** in every heap shaders read, the layer writes dword 6 of each T# as `0xA << 28 \| storage kind << 23 \| sampled kind << 16 \| index`: the tag `0xA` in [31:28], the table's storage kind bits 8..12 in [27:23], its sampled kind bits 0..6 in [22:16] and the bindless index in [15:0] (`runtime/src/gfx10_descriptors.h`, `tsharp_index_word`). **Index 0** is the fallback of the array the instruction reads: the word is 0 while the T# has no entry (no texture at its address yet, a stream pending, no room in its array), for index 0 itself and for an index past 16 bits, and a shader reads index and kind 0 unless the word has the tag **and** dword 3 names an image (TYPE 8..15, bit 31), so a V#, a data slot or a zero slot read as a T# never passes. Then, as for a table entry, the kind bit of the instruction's array decides between the index and that array's fallback. The heaps: the copies of the console resource heaps (`fix_console_slot`, fixed again whenever the texture at the T#'s address comes, goes or is replaced, or the T#'s entry is replaced) and the layer's own heaps (`write_image_descriptor`; `scan_title_table` refreshes bound tables; a view `LEONIDA_PIPELINE_COMPILE=on-demand` defers gets its word when it is made, `materialize_table`). Dword 6 is the hardware's compression metadata, which no Vulkan view uses; the title's own bytes and the T#'s table key keep the title's dword 6 (`tsharp_key` strips the word from bytes read back from the layer's heaps). **Translator** (`Gen.tsharp_index_sgpr`, `tools/descriptor_sources.py`): a forward SGPR dataflow over the basic blocks marks each image instruction whose T# dword 6 is dword 6 of a heap slot: an `s_load` from a 32-bit pointer in a user SGPR (a descriptor table or a directly indexed heap, `docs/d3d12_vulkan.md` section 3.4) at slot position 24 (a static offset is checked; a run-time one is the heap index times 32), followed through copies, joins of two such loads, SGPRs parked in VGPR lanes (`v_writelane`/`v_readlane`) and VCC used as two more SGPRs. Those instructions read index and kind from the word, with no memory access and no lookup. Any other T# keeps the lookup inside a uniform branch taken only when its dword 6 has no tag, so a heap T# the dataflow could not place costs no probe either (`Gen.tsharp_lookup`). S#s keep the lookup: the console sampler heaps are the title's pages read in place, and S#s have no free field. **Older packs** are told apart by the module meta: every module this translator writes has `"tsharp_index": "dword6"` (with its counts `tsharp_index_reads` and `tsharp_lookups`); the runtime counts them (`TsharpIndexCensus`) and writes the word when any module reads it, logging `T# index word: written into the heaps' T#s (all N modules)` or `not read`. A pack without the key keeps working as before: no word is written and its modules find every T# by its words. A library mixing both is logged, since its older modules then miss heap T#s (their copy's dword 6 is not the key). `LEONIDA_CONSOLE_HEAP_GPU`'s pass copies T#s as written, so with an index-word pack the resource heaps are fixed on the CPU (logged once, `runtime/README.md`). Modules change, so pipeline keys change with them. **Counts** (`tools/descriptor_source_census.py`): 1.0.2.1 carve, 26,503 listings: 439,415 image instructions with a T# in 17,540 modules; 437,263 take the whole T# from such a heap load (257,962 static, 179,301 run-time offset), 1,916 are lost at joins or computed, 235 come from another base, 1 from a 64-bit pointer, none from a title buffer through a V#, none built from constants and none edited in dword 6. No scalar instruction reads dword 5, 6 or 7 of a heap T# (dword 1: 8,065, 2: 12,069, 3: 9,177, 4: 3, 0: 1), so the shaders' own maths never sees the word. The translator marks 438,693 (99.84%; 17,474 of the 17,540 modules keep no T# lookup) before the VCC rule, which only adds. Pipeline library, 2,684 programs: 113,585 of 157,410 (72%; 1,649 of 2,235 modules), the rest mostly pointers rebuilt through paths the dataflow does not follow (those run the branch above). Of the carve's 366,628 S# operands, 188,732 come from heap loads, 146,036 are literal and 31,860 from elsewhere. **Cost**, RADV (Mesa 26.3.1) on an RX 7900 XTX, `vk_pipeline_check --stats`: the lighting shader above, instructions 19,714 → 17,568, latency 73,690 → 32,458, inverse throughput 16,453 → 7,468, spilled SGPRs 31 → 17 (its 20 remaining lookups are S#s); the library program `lib_cs_01296` (screen-probe ray activation), instructions 40,901 → 36,046, latency 88,291 → 52,359, inverse throughput 20,579 → 13,451, spilled SGPRs 1,007 → 43. **Checked by** `tests/semantic/test_tsharp_index_word.py` (the interpreter reads the image the word names with no table bound; an untagged word, a 3D kind for a 2D load, a dword 3 that names no image and a zero slot read the fallback; a 64-bit-pointer T# looks the table up only without the word; the fixture `ps_tsharp_index_word.s` with a T# loaded in either arm of a branch; the dataflow's static and run-time offsets, a slot read as two halves, VGPR-lane spills, VCC, and the sources that keep the lookup), `runtime/test/gfx10_descriptors_test.cpp` (the word's bits and the key), `shader_library_test` (the census) and the Wine suite's d3d12 tests, which read the word back through `bindless_hash_lookup`. GPU-checked on the Ryzen 9 7950X3D's integrated GPU (RADV RAPHAEL_MENDOCINO, Mesa 26.3.1): `ps_texture_sample` and `ps_table_fetch` load their T# through a table pointer as the title's shaders do and `vk_texture_test` writes the word: the gradient sample and 4096 exact pixels each for SINT, UINT and the miss control (a dword 6 without the tag reads index 0), with no T# lookup in either module. |
332| Run-time format decode cost | A `buffer_load_format_*` whose format comes from the V# is decoded by table, without a branch: one shared function per output component (`%fmt_dec_c0`…`%fmt_dec_c3`) reads the format's kind, channel count and channel widths from the module table `%fmt_desc_tab`, and the kind picks the conversion with `OpSelect`; the exact UNORM/SNORM quotient comes from the shared `%fmt_norm_bits`, whose width's 64-bit repeat constant is read from `%fmt_norm_rep_tab`. A code outside the table gives zeros, a format with fewer channels repeats its own (component *c* = *c* mod *n*), and the element size is selected from the format alone (`%fmt_size_tab`), the per-lane byte offset added once. Until 2026-11-23 the shared function instead held every format's decode and a binary search over the codes (`OpSelectionMerge` with `DontFlatten`): 3,498 instructions and 306 branches in the module of a shader with one dynamic-format load (250,869 bytes). Now the four functions hold 565 instructions and no branch, and that module is 56,763 bytes. The decode functions take the format code and the element's four dwords as a `v4uint`, so their function type has a structure of its own: a type of `uint` × 5 repeats the type of the `x_round` helpers, and SPIR-V forbids two non-aggregate types with the same structure. Over the 1.0.2.1 corpus the 11,400 shaders that use this path all translate and pass \spirv-val\ (the previous translator included), and their modules shrink from 11,163,872,428 to 10,454,474,528 bytes (-6.35%). The 15,103 shaders without a run-time FORMAT come out byte for byte identical (checked on a 297-shader sample, every 51st of them). The values are unchanged: every one of the 128 codes gives the same words as the branch search, checked by `tests/semantic/test_format_decode_table.py` (each code against a reference decoded from the raw bits with exact quotients, plus the branch-free and shared-per-component shape). The old translation was confirmed on an RTX 4090 (621.01) against the decode-everything translation: identical output buffers for all 128 codes in four configurations (four byte alignments, out-of-range records, constant DST_SEL), xyzw and d16_xyzw. The branch-free decode costs more ALU per load than the search (every kind's conversion is computed and one is kept), so it trades run time for module size and compile time. | 333| Run-time format decode cost | A `buffer_load_format_*` whose format comes from the V# is decoded by table, without a branch: one shared function per output component (`%fmt_dec_c0`…`%fmt_dec_c3`) reads the format's kind, channel count and channel widths from the module table `%fmt_desc_tab`, and the kind picks the conversion with `OpSelect`; the exact UNORM/SNORM quotient comes from the shared `%fmt_norm_bits`, whose width's 64-bit repeat constant is read from `%fmt_norm_rep_tab`. A code outside the table gives zeros, a format with fewer channels repeats its own (component *c* = *c* mod *n*), and the element size is selected from the format alone (`%fmt_size_tab`), the per-lane byte offset added once. Until 2026-11-23 the shared function instead held every format's decode and a binary search over the codes (`OpSelectionMerge` with `DontFlatten`): 3,498 instructions and 306 branches in the module of a shader with one dynamic-format load (250,869 bytes). Now the four functions hold 565 instructions and no branch, and that module is 56,763 bytes. The decode functions take the format code and the element's four dwords as a `v4uint`, so their function type has a structure of its own: a type of `uint` × 5 repeats the type of the `x_round` helpers, and SPIR-V forbids two non-aggregate types with the same structure. Over the 1.0.2.1 corpus the 11,400 shaders that use this path all translate and pass \spirv-val\ (the previous translator included), and their modules shrink from 11,163,872,428 to 10,454,474,528 bytes (-6.35%). The 15,103 shaders without a run-time FORMAT come out byte for byte identical (checked on a 297-shader sample, every 51st of them). The values are unchanged: every one of the 128 codes gives the same words as the branch search, checked by `tests/semantic/test_format_decode_table.py` (each code against a reference decoded from the raw bits with exact quotients, plus the branch-free and shared-per-component shape). The old translation was confirmed on an RTX 4090 (621.01) against the decode-everything translation: identical output buffers for all 128 codes in four configurations (four byte alignments, out-of-range records, constant DST_SEL), xyzw and d16_xyzw. The branch-free decode costs more ALU per load than the search (every kind's conversion is computed and one is kept), so it trades run time for module size and compile time. |
333| 3D explicit-gradient texture samples | For `image_sample_d` and `image_sample_d_cl` on a 3D view, the first six address VGPRs contain dP/dx.xyz and dP/dy.xyz. XYZ and the optional minimum LOD follow. With `a16`, the six derivative VGPRs still hold f32; the following two words contain packed f16 coordinates and the optional clamp. The hand-written `tests/semantic/fixtures/volume_gradients.asm` checks the source registers of both gradients, coordinates and clamp. LLVM gfx1030 assembles all four forms and their modules validate for Vulkan 1.2. [LLVM GFX10 address sizing](https://reviews.llvm.org/D102231) and [SPIR-V Grad operands](https://registry.khronos.org/SPIR-V/specs/unified1/SPIRV.html#Image_Operands) | 334| 3D explicit-gradient texture samples | For `image_sample_d` and `image_sample_d_cl` on a 3D view, the first six address VGPRs contain dP/dx.xyz and dP/dy.xyz. XYZ and the optional minimum LOD follow. With `a16`, the six derivative VGPRs still hold f32; the following two words contain packed f16 coordinates and the optional clamp. The hand-written `tests/semantic/fixtures/volume_gradients.asm` checks the source registers of both gradients, coordinates and clamp. LLVM gfx1030 assembles all four forms and their modules validate for Vulkan 1.2. [LLVM GFX10 address sizing](https://reviews.llvm.org/D102231) and [SPIR-V Grad operands](https://registry.khronos.org/SPIR-V/specs/unified1/SPIRV.html#Image_Operands) |
334| `image_sample_c_l` | Scalar 2D depth comparison (`dmask:0x1`) takes the f32 reference, XY coordinates and explicit mip in that order. Under A16 the reference stays full-width; XY share a VGPR and LOD uses the next low half. D16 returns the comparison in the low half of the destination. Confirmed against LLVM AMDGPU's `llvm.amdgcn.image.sample[.a16].dim.ll` lowering and synthetic Vulkan 1.2 modules in `test_explicit_mip_depth_compare`. | 335| `image_sample_c_l` | Scalar 2D depth comparison (`dmask:0x1`) takes the f32 reference, XY coordinates and explicit mip in that order. Under A16 the reference stays full-width; XY share a VGPR and LOD uses the next low half. D16 returns the comparison in the low half of the destination. Confirmed against LLVM AMDGPU's `llvm.amdgcn.image.sample[.a16].dim.ll` lowering and synthetic Vulkan 1.2 modules in `test_explicit_mip_depth_compare`. |
diff --git a/make_game.py b/make_game.py
index 742d7980e..765b8cf11 100644
--- a/make_game.py
+++ b/make_game.py
@@ -2060,7 +2060,7 @@ def runtime_gpu_max_push_constants():
2060 2060
2061 2061
2062# Source and data files that produce the translated modules, metadata, partner stubs and native PSO catalog. 2062# Source and data files that produce the translated modules, metadata, partner stubs and native PSO catalog.
2063TRANSLATION_SOURCES = ("rdna2spirv.py", "shader_ir.py", "cfg_structure.py", "file_mode.py", "fssm_header.py", "lane_masks.py", "wave64_halves.py", 2063TRANSLATION_SOURCES = ("rdna2spirv.py", "descriptor_sources.py", "heap_index_census.py", "shader_ir.py", "cfg_structure.py", "file_mode.py", "fssm_header.py", "lane_masks.py", "wave64_halves.py",
2064 "wave64_emulate_opt.py", "spirv_loop_guard.py", "shader_meta.py", "spirv_stubs.py", "spirv_asm.py", "spirv_asm_tables.py", 2064 "wave64_emulate_opt.py", "spirv_loop_guard.py", "shader_meta.py", "spirv_stubs.py", "spirv_asm.py", "spirv_asm_tables.py",
2065 "spirv_opt.py", "report_paths.py", "replace_retry.py", "fssm_unpack.py", "shader_stage_manifest.py", 2065 "spirv_opt.py", "report_paths.py", "replace_retry.py", "fssm_unpack.py", "shader_stage_manifest.py",
2066 "rdna2_decode.py", "rdna2_isa_tables.py", "gfx10_formats.json", 2066 "rdna2_decode.py", "rdna2_isa_tables.py", "gfx10_formats.json",
diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt
index 7b2c77300..d1a07073d 100644
--- a/runtime/CMakeLists.txt
+++ b/runtime/CMakeLists.txt
@@ -4918,6 +4918,12 @@ if(TARGET Vulkan::Headers)
4918 target_compile_options(title_mirror_hooks_test PRIVATE /W4 /permissive- /utf-8) 4918 target_compile_options(title_mirror_hooks_test PRIVATE /W4 /permissive- /utf-8)
4919 endif() 4919 endif()
4920 add_test(NAME title_mirror_hooks COMMAND title_mirror_hooks_test) 4920 add_test(NAME title_mirror_hooks COMMAND title_mirror_hooks_test)
4921 # The XMemAlloc heap in the page mirror's range (src/title_heap.h).
4922 add_executable(title_heap_test test/title_heap_test.cpp)
4923 if(WIN32 AND MSVC)
4924 target_compile_options(title_heap_test PRIVATE /W4 /permissive- /utf-8)
4925 endif()
4926 add_test(NAME title_heap COMMAND title_heap_test)
4921 # Queue construction cleans its Vulkan handles if holder registration runs out of host memory. 4927 # Queue construction cleans its Vulkan handles if holder registration runs out of host memory.
4922 # Which title textures the refresh looks at: only those something says changed (src/title_texture_watch.h). 4928 # Which title textures the refresh looks at: only those something says changed (src/title_texture_watch.h).
4923 add_executable(title_texture_watch_test test/title_texture_watch_test.cpp) 4929 add_executable(title_texture_watch_test test/title_texture_watch_test.cpp)
diff --git a/runtime/README.md b/runtime/README.md
index 62321a76f..1a9fcd14d 100644
--- a/runtime/README.md
+++ b/runtime/README.md
@@ -414,7 +414,7 @@ ones marked *diagnostic* only add log lines or exist to compare a run with and w
414| `LEONIDA_COMPILE_GATE` | unset | `1`: a compute pipeline build holds the device's submit lock for its driver calls, so no compute compile runs while a queue submits. Unset: the asynchronous workers compile while other queues submit. | 414| `LEONIDA_COMPILE_GATE` | unset | `1`: a compute pipeline build holds the device's submit lock for its driver calls, so no compute compile runs while a queue submits. Unset: the asynchronous workers compile while other queues submit. |
415| `LEONIDA_FAST_PIPELINES` | unset | `graphics`, `compute` or `all` (`1` = all) creates those pipelines with `VK_PIPELINE_CREATE_DISABLE_OPTIMIZATION_BIT` (`shims/d3d12_pipeline_compile.h`): slower shaders, much shorter builds. Part of the compute journal key, so optimized and fast builds keep separate files. | 415| `LEONIDA_FAST_PIPELINES` | unset | `graphics`, `compute` or `all` (`1` = all) creates those pipelines with `VK_PIPELINE_CREATE_DISABLE_OPTIMIZATION_BIT` (`shims/d3d12_pipeline_compile.h`): slower shaders, much shorter builds. Part of the compute journal key, so optimized and fast builds keep separate files. |
416| `LEONIDA_GRAPHICS_COMPILE_WORKER` | on | A second compile worker that takes graphics pipeline builds only, so a long compute build does not hold them up (`shims/d3d12_pipeline_compile.h`). `0`: the one general worker builds everything. | 416| `LEONIDA_GRAPHICS_COMPILE_WORKER` | on | A second compile worker that takes graphics pipeline builds only, so a long compute build does not hold them up (`shims/d3d12_pipeline_compile.h`). `0`: the one general worker builds everything. |
417| `LEONIDA_CONSOLE_HEAP_GPU` | unset | `1`: the V#s of the console descriptor heaps are rebased by a compute pass at the start of each submission (`src/console_heap_gpu.h`) instead of on the CPU. The CPU still finds the changed slots and registers the T#s; a V# the pass cannot answer is resolved after its submission and its slot queued again. | 417| `LEONIDA_CONSOLE_HEAP_GPU` | unset | `1`: the V#s of the console descriptor heaps are rebased by a compute pass at the start of each submission (`src/console_heap_gpu.h`) instead of on the CPU. The CPU still finds the changed slots and registers the T#s; a V# the pass cannot answer is resolved after its submission and its slot queued again. The pass copies T#s as the title wrote them and does not write the bindless index word into their dword 6 (docs/design.md, "Bindless index in the T#"), so with a shader pack whose modules read that word (index.json `"tsharp_index": "dword6"`, every pack translated since) the setting does not apply to resource heaps: they are fixed on the CPU as without it, and the log says so once (`LEONIDA_CONSOLE_HEAP_GPU: the pass does not write the T# index word ...`). An older pack still gets the pass. |
418| `LEONIDA_CONSOLE_HEAP_ARENA` | unset | With `LEONIDA_CONSOLE_HEAP_GPU=1`, `1` puts a console heap's GPU copy and its guard in the arena (device-local where the device has ReBAR) instead of an import of host memory. No room in the arena: the import. | 418| `LEONIDA_CONSOLE_HEAP_ARENA` | unset | With `LEONIDA_CONSOLE_HEAP_GPU=1`, `1` puts a console heap's GPU copy and its guard in the arena (device-local where the device has ReBAR) instead of an import of host memory. No room in the arena: the import. |
419| `LEONIDA_CONSOLE_GPU_TSHARPS` | on | With `LEONIDA_CONSOLE_HEAP_GPU=1`, the T#s of changed slots are registered by the resolver thread and the refresh only decodes them. `0` registers them on the submitting thread, under the fix budget. | 419| `LEONIDA_CONSOLE_GPU_TSHARPS` | on | With `LEONIDA_CONSOLE_HEAP_GPU=1`, the T#s of changed slots are registered by the resolver thread and the refresh only decodes them. `0` registers them on the submitting thread, under the fix budget. |
420| `LEONIDA_CONSOLE_GPU_RETRY_MS` | `2000` | With `LEONIDA_CONSOLE_HEAP_GPU=1`, how often V# words that got no backing are asked for again, on a timer that bounds the cost per submission. | 420| `LEONIDA_CONSOLE_GPU_RETRY_MS` | `2000` | With `LEONIDA_CONSOLE_HEAP_GPU=1`, how often V# words that got no backing are asked for again, on a timer that bounds the cost per submission. |
diff --git a/runtime/cmake/translator_deps.cmake b/runtime/cmake/translator_deps.cmake
index 0cb1ecdf8..2f0d42ec9 100644
--- a/runtime/cmake/translator_deps.cmake
+++ b/runtime/cmake/translator_deps.cmake
@@ -10,10 +10,12 @@ set(LEONIDA_TRANSLATOR_DEPS
10 ${_leonida_repo}/runtime/test/shaders/compute_fixture.py 10 ${_leonida_repo}/runtime/test/shaders/compute_fixture.py
11 ${_leonida_repo}/tools/bary_fallback_gs.py 11 ${_leonida_repo}/tools/bary_fallback_gs.py
12 ${_leonida_repo}/tools/cfg_structure.py 12 ${_leonida_repo}/tools/cfg_structure.py
13 ${_leonida_repo}/tools/descriptor_sources.py
13 ${_leonida_repo}/tools/file_mode.py 14 ${_leonida_repo}/tools/file_mode.py
14 ${_leonida_repo}/tools/fssm_header.py 15 ${_leonida_repo}/tools/fssm_header.py
15 ${_leonida_repo}/tools/fssm_unpack.py 16 ${_leonida_repo}/tools/fssm_unpack.py
16 ${_leonida_repo}/tools/gfx10_formats.json 17 ${_leonida_repo}/tools/gfx10_formats.json
18 ${_leonida_repo}/tools/heap_index_census.py
17 ${_leonida_repo}/tools/lane_masks.py 19 ${_leonida_repo}/tools/lane_masks.py
18 ${_leonida_repo}/tools/mc_command.py 20 ${_leonida_repo}/tools/mc_command.py
19 ${_leonida_repo}/tools/native_pso_hashes.py 21 ${_leonida_repo}/tools/native_pso_hashes.py
diff --git a/runtime/shims/d3d12_com.h b/runtime/shims/d3d12_com.h
index 63c615ec4..b2926aadf 100644
--- a/runtime/shims/d3d12_com.h
+++ b/runtime/shims/d3d12_com.h
@@ -428,6 +428,9 @@ bool page_mirror_gpu_read(ID3D12Device* device, std::uint64_t title_va, void* ou
428// The same at arena VA `va` (heap_base + va): what a shader reads there, a console heap read in place among it. False 428// The same at arena VA `va` (heap_base + va): what a shader reads there, a console heap read in place among it. False
429// when the mirror is off. For tests. 429// when the mirror is off. For tests.
430bool arena_gpu_read(ID3D12Device* device, std::uint64_t va, void* out, std::size_t bytes); 430bool arena_gpu_read(ID3D12Device* device, std::uint64_t va, void* out, std::size_t bytes);
431// Whether the layer writes the T# index word (gfx10_descriptors.h, tsharp_index_word) into the heaps shaders read, as a
432// loaded library of modules that read it turns on. Returns what it was. For tests, which load no library.
433bool set_tsharp_index_words_for_test(ID3D12Device* device, bool on);
431// Whether a draw's or copy's binding of title memory [va, va + size) would be served by the page mirror (VulkanContext's 434// Whether a draw's or copy's binding of title memory [va, va + size) would be served by the page mirror (VulkanContext's
432// mirror lookup): it must have been named before. `size` comes back cut at the chunk's end. For tests. 435// mirror lookup): it must have been named before. `size` comes back cut at the chunk's end. For tests.
433bool page_mirror_buffer_at(ID3D12Device* device, std::uint64_t va, std::uint64_t& size); 436bool page_mirror_buffer_at(ID3D12Device* device, std::uint64_t va, std::uint64_t& size);
@@ -464,7 +467,8 @@ struct BindlessStats {
464BindlessStats bindless_stats(ID3D12Device* device); 467BindlessStats bindless_stats(ID3D12Device* device);
465VkDescriptorSetLayout bindless_set_layout(ID3D12Device* device); 468VkDescriptorSetLayout bindless_set_layout(ID3D12Device* device);
466// The bindless index the descriptor hash table holds for the 8 key dwords of a T# (or the 4 of an S# followed by 469// The bindless index the descriptor hash table holds for the 8 key dwords of a T# (or the 4 of an S# followed by
467// 0xFFFFFFFF x4), 0 (the fallback) when it has none or `device` has no such set. For tests. 470// 0xFFFFFFFF x4), 0 (the fallback) when it has none or `device` has no such set. A T# read from one of the layer's
471// heaps is looked up without its index word (dword 6), and gives 0 unless that word names the same index. For tests.
468std::uint32_t bindless_hash_lookup(ID3D12Device* device, const std::uint32_t (&key)[8]); 472std::uint32_t bindless_hash_lookup(ID3D12Device* device, const std::uint32_t (&key)[8]);
469// The free indices of that set's 2D image and sampler arrays: how many more distinct 2D T#s and S#s 473// The free indices of that set's 2D image and sampler arrays: how many more distinct 2D T#s and S#s
470// CreateShaderResourceView and CreateSampler can register before they log that the array is full. Zeros when 474// CreateShaderResourceView and CreateSampler can register before they log that the array is full. Zeros when
diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp
index 71fccacb8..5bf4c6e44 100644
--- a/runtime/shims/d3d12_vulkan_device.cpp
+++ b/runtime/shims/d3d12_vulkan_device.cpp
@@ -253,24 +253,6 @@ bool copy_guarded_host(std::uint8_t* to, const std::uint8_t* from, std::size_t b
253 } 253 }
254} 254}
255 255
256// Whether two byte ranges differ, one of them title memory that may go away meanwhile: false when a page faults. No
257// C++ objects here: it is a __try frame, and the compare is a loop of its own (a fault inside the CRT's memcmp never
258// reaches the __except under Wine, src/guarded_copy.h).
259__declspec(noinline) LEONIDA_GUARDED_NO_BUILTIN bool bytes_differ(const std::uint8_t* a, const std::uint8_t* b,
260 std::size_t n) {
261 for (std::size_t i = 0; i < n; ++i)
262 if (a[i] != b[i]) return true;
263 return false;
264}
265bool differ_guarded(const std::uint8_t* a, const std::uint8_t* b, std::size_t n, bool& differs) {
266 __try {
267 differs = bytes_differ(a, b, n);
268 return true;
269 } __except (EXCEPTION_EXECUTE_HANDLER) {
270 return false;
271 }
272}
273
274// The same, reading the title's pages that xmem's frame table holds through their frames: a stream pool's GPU-only 256// The same, reading the title's pages that xmem's frame table holds through their frames: a stream pool's GPU-only
275// pages and their CPU twins after queue slot 31's copies have no host view (src/title_frames.h). A frame is a section's 257// pages and their CPU twins after queue slot 31's copies have no host view (src/title_frames.h). A frame is a section's
276// scratch view, cached memory, so it is not read streaming. 258// scratch view, cached memory, so it is not read streaming.
@@ -4033,6 +4015,22 @@ struct DeviceState {
4033 --it; 4015 --it;
4034 return addr < it->second && (addr-it->first) % kDescriptorSize == 0; 4016 return addr < it->second && (addr-it->first) % kDescriptorSize == 0;
4035 } 4017 }
4018 // The T#s of a bound table in one of the layer's heaps get the index word their entry has now (tsharp_index_word):
4019 // Create*View wrote it, but a T# whose view came later (a stream published, a texture made at the address) or went
4020 // since, and one the title wrote raw or copied from where no index was, would otherwise keep the word of then.
4021 void refresh_tsharp_index_words(std::uint8_t* table, VkDeviceSize bytes) {
4022 namespace g = leonida::gfx10;
4023 std::lock_guard lock(descriptor_mutex);
4024 for (VkDeviceSize at = 0; at + kDescriptorSize <= bytes; at += kDescriptorSize) {
4025 g::ImageWords words;
4026 std::memcpy(words.data(), table + at, sizeof(words));
4027 if (!g::is_image(words)) continue;
4028 const std::uint32_t word = tsharp_index_word_locked(g::tsharp_key(words));
4029 if (word != words[g::kTsharpIndexDword])
4030 std::memcpy(table + at + 4 * g::kTsharpIndexDword, &word, sizeof(word));
4031 }
4032 }
4033
4036 // The buffer V#s of the table at `table_va` whose base is in the title's own memory get the address of a copy, 4034 // The buffer V#s of the table at `table_va` whose base is in the title's own memory get the address of a copy,
4037 // written in place: the title wrote them itself (or copied them), so no Create*View saw them. Images (T#s) and 4035 // written in place: the title wrote them itself (or copied them), so no Create*View saw them. Images (T#s) and
4038 // null slots are skipped; so is a V# already in the arena, so a rewritten one is left alone next time. 4036 // null slots are skipped; so is a V# already in the arena, so a rewritten one is left alone next time.
@@ -4058,6 +4056,7 @@ struct DeviceState {
4058 // Slots the title wrote in its own backing of this heap, if it gave the heap one. 4056 // Slots the title wrote in its own backing of this heap, if it gave the heap one.
4059 aliases.pull_descriptors(table, std::size_t(end - table_va)); 4057 aliases.pull_descriptors(table, std::size_t(end - table_va));
4060 if (sampler) return; // S# words describe sampling state. They have no buffer address to translate. 4058 if (sampler) return; // S# words describe sampling state. They have no buffer address to translate.
4059 if (tsharp_index_words) refresh_tsharp_index_words(table, end - table_va);
4061 for (VkDeviceSize at = table_va; at + 16 <= end; at += kDescriptorSize) { 4060 for (VkDeviceSize at = table_va; at + 16 <= end; at += kDescriptorSize) {
4062 auto* words = reinterpret_cast<std::uint32_t*>(table + (at - table_va)); 4061 auto* words = reinterpret_cast<std::uint32_t*>(table + (at - table_va));
4063 if (words[3] >> 30) continue; 4062 if (words[3] >> 30) continue;
@@ -4589,6 +4588,7 @@ struct DeviceState {
4589 bool last_local = true; 4588 bool last_local = true;
4590 std::uint64_t presents = 0; // present serial at the last log line 4589 std::uint64_t presents = 0; // present serial at the last log line
4591 std::uint64_t faults_seen = 0, hot_seen = 0, cold_seen = 0; // the tracking's counters at the last log line 4590 std::uint64_t faults_seen = 0, hot_seen = 0, cold_seen = 0; // the tracking's counters at the last log line
4591 std::uint64_t uploaded_seen = 0, conflicts_seen = 0; // the mirror's, likewise
4592 double ms = 0; 4592 double ms = 0;
4593 std::chrono::steady_clock::time_point since = std::chrono::steady_clock::now(); 4593 std::chrono::steady_clock::time_point since = std::chrono::steady_clock::now();
4594 // The console heaps read in place (add_heap_in_place): their filter state is under this mutex too. 4594 // The console heaps read in place (add_heap_in_place): their filter state is under this mutex too.
@@ -4879,38 +4879,20 @@ struct DeviceState {
4879 } 4879 }
4880 return true; 4880 return true;
4881 } 4881 }
4882 // What the GPU wrote into the homes of mirrored pages of [begin, end) goes back to the title's pages, as 4882 // What the GPU wrote into the homes of mirrored pages of [begin, end) goes back to the title's pages
4883 // ShadowPages::write_back does for a shadow: after the submissions that could write them have retired 4883 // (TitleMirror::write_back: merged at the 256-byte piece, a piece only the GPU changed goes back, one both changed
4884 // (write_back_titles), only the 256-byte pieces whose home differs from the title's page, and only on a page nothing 4884 // keeps the title's bytes), once the submissions that could write them have retired (write_back_titles). Written
4885 // wrote since it was last watched (a page written on both sides keeps the title's bytes, which are uploaded over 4885 // through kernel_writes, which opens and pins the page and every other address of its physical page, so the
4886 // the home before the next submission). Written through kernel_writes, which opens and pins the page and every 4886 // readers over them take the bytes. Returns the bytes written.
4887 // other address of its physical page, so the readers over them take the bytes. Returns the bytes written.
4888 std::uint64_t page_mirror_write_back(std::uint64_t begin, std::uint64_t end) { 4887 std::uint64_t page_mirror_write_back(std::uint64_t begin, std::uint64_t end) {
4889 auto& m = page_mirror; 4888 auto& m = page_mirror;
4890 if (!m.mirror || begin >= end) return 0; 4889 if (!m.mirror || begin >= end) return 0;
4891 constexpr std::uint64_t kPage = leonida::TitleMirror::kPage, kPiece = 256;
4892 std::lock_guard lock(m.mutex); 4890 std::lock_guard lock(m.mutex);
4893 std::uint64_t written = 0; 4891 // A console heap read in place is skipped there: its home holds the filtered slots.
4894 for (std::uint64_t page = begin & ~(kPage - 1); page < end; page += kPage) { 4892 const std::uint64_t written = m.mirror->write_back(begin, end, [](std::uint64_t at, const std::uint8_t* bytes,
4895 VkDeviceMemory memory = VK_NULL_HANDLE; 4893 std::size_t n) {
4896 VkDeviceSize offset = 0; 4894 return leonida::kernel_writes::write(reinterpret_cast<void*>(static_cast<std::uintptr_t>(at)), bytes, n);
4897 std::uint8_t* home = nullptr; 4895 });
4898 const std::uint8_t* frame = m.mirror->frame_at(page);
4899 if (!frame || !m.mirror->home_at(page, memory, offset, &home) || !m.tracking->unwritten(page)) continue;
4900 // A console heap read in place: its home holds the filtered slots, never to be copied over the title's.
4901 if (m.mirror->filtered_at(page)) continue;
4902 const std::uint64_t from = std::max(begin, page), to = std::min(end, page + kPage);
4903 for (std::uint64_t at = from & ~(kPiece - 1); at < to; at += kPiece) {
4904 const std::uint64_t a = std::max(at, from), b = std::min(at + kPiece, to);
4905 const std::uint8_t* gpu = home + (a - page);
4906 const std::uint8_t* title = frame + (a - page);
4907 bool differs = false;
4908 // A title page gone since (decommitted, unmapped) has nothing to write back into.
4909 if (!differ_guarded(gpu, title, std::size_t(b - a), differs) || !differs) continue;
4910 if (leonida::kernel_writes::write(reinterpret_cast<void*>(static_cast<std::uintptr_t>(a)), gpu, b - a))
4911 written += b - a;
4912 }
4913 }
4914 m.written_back += written; 4896 m.written_back += written;
4915 return written; 4897 return written;
4916 } 4898 }
@@ -4971,16 +4953,19 @@ struct DeviceState {
4971 m.taken.clear(); 4953 m.taken.clear();
4972 // Ordinary memory released or decommitted: its mirrored pages leave (named again, they are mirrored again). 4954 // Ordinary memory released or decommitted: its mirrored pages leave (named again, they are mirrored again).
4973 leonida::geometry_writes::take_released(m.released, m.released_ranges); 4955 leonida::geometry_writes::take_released(m.released, m.released_ranges);
4956 // Only pages the range holds whole: a freed heap block leaves the rest of its page to the blocks around it.
4974 for (const auto& [from, to] : m.released_ranges) { 4957 for (const auto& [from, to] : m.released_ranges) {
4975 for (auto page = m.identity.lower_bound(from & ~(leonida::TitleMirror::kPage - 1)); 4958 constexpr std::uint64_t kPage = leonida::TitleMirror::kPage;
4976 page != m.identity.end() && *page < to;) { 4959 for (auto page = m.identity.lower_bound((from + kPage - 1) & ~(kPage - 1));
4960 page != m.identity.end() && *page + kPage <= to;) {
4977 m.tracking->unwatch(*page); 4961 m.tracking->unwatch(*page);
4978 m.mirror->map(*page, nullptr, nullptr, ticket); 4962 m.mirror->map(*page, nullptr, nullptr, ticket);
4979 ++m.identity_released; 4963 ++m.identity_released;
4980 page = m.identity.erase(page); 4964 page = m.identity.erase(page);
4981 } 4965 }
4982 for (auto run = m.ensured.begin(); run != m.ensured.end();) 4966 if (to - from >= kPage) // a run that lost a page is named again (pages still there map to themselves)
4983 run = run->first < to && from < run->second ? m.ensured.erase(run) : std::next(run); 4967 for (auto run = m.ensured.begin(); run != m.ensured.end();)
4968 run = run->first < to && from < run->second ? m.ensured.erase(run) : std::next(run);
4984 } 4969 }
4985 m.tracking->collect(m.written); // re-watched before the copies below 4970 m.tracking->collect(m.written); // re-watched before the copies below
4986 for (const std::uint64_t page : m.written) 4971 for (const std::uint64_t page : m.written)
@@ -5008,7 +4993,8 @@ struct DeviceState {
5008 "mirrored and %llu released, %llu buffer bindings cut at a chunk's end; %llu slot-133 buffers " 4993 "mirrored and %llu released, %llu buffer bindings cut at a chunk's end; %llu slot-133 buffers "
5009 "made on it, %llu KiB of GPU writes copied back; homes in device-local memory %llu units, in " 4994 "made on it, %llu KiB of GPU writes copied back; homes in device-local memory %llu units, in "
5010 "host memory %llu; tracking: %zu pages hot, %zu cold, %llu write faults, %llu hot and %llu " 4995 "host memory %llu; tracking: %zu pages hot, %zu cold, %llu write faults, %llu hot and %llu "
5011 "cold copies; %.1f KiB uploaded a submission, %.1f KiB a frame\n", 4996 "cold copies; uploaded %.1f KiB a submission and %.1f KiB a frame; written back %.1f KiB a "
4997 "submission and %.1f KiB a frame; %llu pieces written on both sides (the title's kept)\n",
5012 static_cast<unsigned long long>(c.pages), static_cast<unsigned long long>(c.homes), 4998 static_cast<unsigned long long>(c.pages), static_cast<unsigned long long>(c.homes),
5013 static_cast<unsigned long long>(c.units), 4999 static_cast<unsigned long long>(c.units),
5014 static_cast<unsigned long long>(c.units * (leonida::TitleMirror::kUnitBytes >> 20)), 5000 static_cast<unsigned long long>(c.units * (leonida::TitleMirror::kUnitBytes >> 20)),
@@ -5027,8 +5013,13 @@ struct DeviceState {
5027 policy.hot, policy.cold, static_cast<unsigned long long>(policy.faults - m.faults_seen), 5013 policy.hot, policy.cold, static_cast<unsigned long long>(policy.faults - m.faults_seen),
5028 static_cast<unsigned long long>(policy.hot_copies - m.hot_seen), 5014 static_cast<unsigned long long>(policy.hot_copies - m.hot_seen),
5029 static_cast<unsigned long long>(policy.cold_copies - m.cold_seen), 5015 static_cast<unsigned long long>(policy.cold_copies - m.cold_seen),
5030 m.refreshes ? double(m.uploads) * 64.0 / double(m.refreshes) : 0.0, 5016 m.refreshes ? double(c.uploaded_bytes - m.uploaded_seen) / 1024.0 / double(m.refreshes) : 0.0,
5031 frames ? double(m.uploads) * 64.0 / double(frames) : 0.0); 5017 frames ? double(c.uploaded_bytes - m.uploaded_seen) / 1024.0 / double(frames) : 0.0,
5018 m.refreshes ? double(m.written_back) / 1024.0 / double(m.refreshes) : 0.0,
5019 frames ? double(m.written_back) / 1024.0 / double(frames) : 0.0,
5020 static_cast<unsigned long long>(c.conflicts - m.conflicts_seen));
5021 m.uploaded_seen = c.uploaded_bytes;
5022 m.conflicts_seen = c.conflicts;
5032 m.faults_seen = policy.faults; 5023 m.faults_seen = policy.faults;
5033 m.hot_seen = policy.hot_copies; 5024 m.hot_seen = policy.hot_copies;
5034 m.cold_seen = policy.cold_copies; 5025 m.cold_seen = policy.cold_copies;
@@ -5529,6 +5520,11 @@ struct DeviceState {
5529 else if (Records::is_waiting(heap.records.state(slot, 0)) && 5520 else if (Records::is_waiting(heap.records.state(slot, 0)) &&
5530 heap.records.base(slot, 0) == texture_address) 5521 heap.records.base(slot, 0) == texture_address)
5531 ++heap.texture_refills; // the T# waited for this address and is bound now 5522 ++heap.texture_refills; // the T# waited for this address and is bound now
5523 // The copy's dword 6 is the index shaders take (gfx10_descriptors.h, tsharp_index_word), or 0 while
5524 // the T# waits: a texture coming, going or being replaced at its address fixes the slot again
5525 // (apply_slot_changes), so the word follows the texture the T# names. The title's bytes and the
5526 // T#'s key keep the title's dword 6.
5527 if (tsharp_index_words) w[leonida::gfx10::kTsharpIndexDword] = unbound ? 0u : tsharp_index_word(words);
5532 } 5528 }
5533 } else { 5529 } else {
5534 // Neither a buffer V# (TYPE is not 0) nor a T# the layer can decode: data the title keeps in the slot. 5530 // Neither a buffer V# (TYPE is not 0) nor a T# the layer can decode: data the title keeps in the slot.
@@ -5719,7 +5715,11 @@ struct DeviceState {
5719 std::memcpy(words.data(), w, sizeof(words)); 5715 std::memcpy(words.data(), w, sizeof(words));
5720 leonida::gfx10::Image image{}; 5716 leonida::gfx10::Image image{};
5721 if (leonida::gfx10::is_image(words) && leonida::gfx10::decode(words, image)) { 5717 if (leonida::gfx10::is_image(words) && leonida::gfx10::decode(words, image)) {
5722 // As the title wrote it; bound by finish_in_place [TSHARP-INDEX: where its bindless index goes in]. 5718 // As the title wrote it, bound by finish_in_place, which writes its bindless index into dword 6
5719 // (gfx10_descriptors.h, tsharp_index_word; the entry's index needs descriptor_mutex, not taken under
5720 // the mirror's lock). Until then dword 6 is 0, the fallback: the title's own dword 6 (compression
5721 // metadata) is never read as an index. The title's bytes keep it.
5722 if (tsharp_index_words) w[leonida::gfx10::kTsharpIndexDword] = 0;
5723 defer = true; 5723 defer = true;
5724 } else { 5724 } else {
5725 heap.records.clear(slot); 5725 heap.records.clear(slot);
@@ -5869,6 +5869,11 @@ struct DeviceState {
5869 done[i].texture = !unbound ? Records::texture_bound 5869 done[i].texture = !unbound ? Records::texture_bound
5870 : why == kTsharpArrayFull || why == kTsharpStorageFull ? Records::texture_waiting_room 5870 : why == kTsharpArrayFull || why == kTsharpStorageFull ? Records::texture_waiting_room
5871 : Records::texture_waiting; 5871 : Records::texture_waiting;
5872 // The home's dword 6 is the index shaders take (tsharp_index_word), 0 while the T# waits; a texture
5873 // coming, going or replaced at its address touches the slot (apply_in_place_changes), which is filtered
5874 // and finished again, so the word follows the texture the T# names. The heap copy's write
5875 // (fix_console_slot) is for heaps not read in place.
5876 if (tsharp_index_words) w[leonida::gfx10::kTsharpIndexDword] = unbound ? 0u : tsharp_index_word(words);
5872 } 5877 }
5873 } 5878 }
5874 std::lock_guard lock(page_mirror.mutex); 5879 std::lock_guard lock(page_mirror.mutex);
@@ -6487,8 +6492,16 @@ struct DeviceState {
6487 const bool imported = heap->imported; 6492 const bool imported = heap->imported;
6488 const VkDeviceSize guarded = heap->guard; 6493 const VkDeviceSize guarded = heap->guard;
6489 arena_guard_bytes.fetch_add(guarded, std::memory_order_relaxed); 6494 arena_guard_bytes.fetch_add(guarded, std::memory_order_relaxed);
6490 if (heap_gpu && console_heap_gpu_enabled() && heap->scratch && resource_heap && !imported) 6495 // The pass copies a T#'s words as the title wrote them; it does not write the index word the library's modules
6491 attach_console_heap_gpu(*heap); 6496 // read (tsharp_index_words), so such a library's heaps are fixed on the CPU, which writes it.
6497 if (heap_gpu && console_heap_gpu_enabled() && heap->scratch && resource_heap && !imported) {
6498 if (!tsharp_index_words)
6499 attach_console_heap_gpu(*heap);
6500 else
6501 log_once("LEONIDA_CONSOLE_HEAP_GPU: the pass does not write the T# index word the shaders read; console "
6502 "descriptor heaps are fixed on the CPU; slots",
6503 int(std::min<VkDeviceSize>(bytes / kDescriptorSize, INT_MAX)));
6504 }
6492 { 6505 {
6493 std::lock_guard lock(console_heap_mutex); 6506 std::lock_guard lock(console_heap_mutex);
6494 if (heap->gpu >= 0) gpu_heaps[std::size_t(heap->gpu)] = heap.get(); 6507 if (heap->gpu >= 0) gpu_heaps[std::size_t(heap->gpu)] = heap.get();
@@ -7970,7 +7983,7 @@ struct DeviceState {
7970 char what[96] = "no texture at that address"; 7983 char what[96] = "no texture at that address";
7971 { 7984 {
7972 std::lock_guard lock(descriptor_mutex); 7985 std::lock_guard lock(descriptor_mutex);
7973 if (image_entries.count(words)) { 7986 if (image_entries.count(words) || image_entries.count(g::tsharp_key(words))) {
7974 kind = 3; 7987 kind = 3;
7975 std::snprintf(what, sizeof(what), "key registered"); 7988 std::snprintf(what, sizeof(what), "key registered");
7976 } else if (const auto it = images_by_address.find(image.address); it != images_by_address.end()) { 7989 } else if (const auto it = images_by_address.find(image.address); it != images_by_address.end()) {
@@ -8510,6 +8523,10 @@ struct DeviceState {
8510 // True when the loaded library's modules read the table's kind word (create_bindless, descriptor_table.h): the 8523 // True when the loaded library's modules read the table's kind word (create_bindless, descriptor_table.h): the
8511 // image inserts then record which arrays each index is bound in. 8524 // image inserts then record which arrays each index is bound in.
8512 bool descriptor_table_tagged = false; 8525 bool descriptor_table_tagged = false;
8526 // True when the loaded library's modules read a T#'s bindless index from its dword 6 (create_bindless,
8527 // gfx10_descriptors.h tsharp_index_word): every T# the layer writes into a heap shaders read then carries it, in
8528 // the console heaps' copies (fix_console_slot) and in its own heaps (write_image_descriptor, scan_title_table).
8529 bool tsharp_index_words = false;
8513 std::mutex descriptor_mutex; // the set and the containers below 8530 std::mutex descriptor_mutex; // the set and the containers below
8514 // vkDeviceWaitIdle calls made for the bindless set (none, unless LEONIDA_BINDLESS_IDLE_WAIT restores the old wait). 8531 // vkDeviceWaitIdle calls made for the bindless set (none, unless LEONIDA_BINDLESS_IDLE_WAIT restores the old wait).
8515 std::atomic<std::uint64_t> bindless_idle_waits{0}; 8532 std::atomic<std::uint64_t> bindless_idle_waits{0};
@@ -8612,6 +8629,7 @@ struct DeviceState {
8612 std::atomic<unsigned> pending_sample_count{}; 8629 std::atomic<unsigned> pending_sample_count{};
8613 bool materialize_sample(const leonida::DescriptorKey& key); 8630 bool materialize_sample(const leonida::DescriptorKey& key);
8614 bool materialize_table(std::uint64_t address,std::uint32_t slots); 8631 bool materialize_table(std::uint64_t address,std::uint32_t slots);
8632 void write_tsharp_index_words(const std::vector<leonida::DescriptorKey>& keys);
8615 void remember_sample(const leonida::DescriptorKey& key, const PendingSample& sample) { 8633 void remember_sample(const leonida::DescriptorKey& key, const PendingSample& sample) {
8616 std::lock_guard lock(pending_view_mutex); 8634 std::lock_guard lock(pending_view_mutex);
8617 if (pending_samples.try_emplace(key,sample).second) { 8635 if (pending_samples.try_emplace(key,sample).second) {
@@ -8897,6 +8915,11 @@ struct DeviceState {
8897 if (existing != image_entries.end()) { 8915 if (existing != image_entries.end()) {
8898 replaced_images.push_back(existing->second); // the read-only entry of the same bytes 8916 replaced_images.push_back(existing->second); // the read-only entry of the same bytes
8899 existing->second = entry; 8917 existing->second = entry;
8918 // The console heap slots holding these words carry the read-only entry's index in their dword 6
8919 // (tsharp_index_words): fixed again at the next submission (a texture_gone change re-fixes bound T#s,
8920 // under the address their records keep, tsharp_texture_key), they take this one, with its storage views.
8921 if (tsharp_index_words)
8922 note_texture_change(leonida::SlotChange::texture_gone, tsharp_texture_key(image.address));
8900 } else { 8923 } else {
8901 image_entries.emplace(words, entry); 8924 image_entries.emplace(words, entry);
8902 image_keys.emplace(image.address, words); 8925 image_keys.emplace(image.address, words);
@@ -8909,6 +8932,22 @@ struct DeviceState {
8909 return true; 8932 return true;
8910 } 8933 }
8911 8934
8935 // The dword 6 that the T# `words` (its key: the descriptor as the title or Create*View wrote it) gets in a heap
8936 // shaders read (gfx10_descriptors.h, tsharp_index_word): its entry's index and the arrays that index is bound in,
8937 // which the set derives from what it bound there (image_kind_at); 0, the fallback, while the T# has no entry (no
8938 // texture yet, a stream still pending, no room). descriptor_mutex held.
8939 std::uint32_t tsharp_index_word_locked(const leonida::gfx10::ImageWords& words) const {
8940 if (!bindless) return 0;
8941 const auto it = image_entries.find(words);
8942 if (it == image_entries.end()) return 0;
8943 return leonida::gfx10::tsharp_index_word(it->second.index,
8944 bindless->image_kind_at(it->second.dimension, it->second.index));
8945 }
8946 std::uint32_t tsharp_index_word(const leonida::gfx10::ImageWords& words) {
8947 std::lock_guard lock(descriptor_mutex);
8948 return tsharp_index_word_locked(words);
8949 }
8950
8912 // Textures by the address their T#s name them by (Resource::image_address), for the T#s a title writes into a 8951 // Textures by the address their T#s name them by (Resource::image_address), for the T#s a title writes into a
8913 // console descriptor heap itself (bind_title_image). Under descriptor_mutex: a texture leaves it in forget_image, 8952 // console descriptor heap itself (bind_title_image). Under descriptor_mutex: a texture leaves it in forget_image,
8914 // before its image goes. 8953 // before its image goes.
@@ -11780,6 +11819,7 @@ bool DeviceState::materialize_table(std::uint64_t address, std::uint32_t slots)
11780 for (const auto& [key,view]:pending_samples) 11819 for (const auto& [key,view]:pending_samples)
11781 if (view.owner->id() == address) keys.push_back(key); } 11820 if (view.owner->id() == address) keys.push_back(key); }
11782 for (const auto& key:keys) if (!materialize_sample(key)) return false; 11821 for (const auto& key:keys) if (!materialize_sample(key)) return false;
11822 write_tsharp_index_words(keys);
11783 return true; 11823 return true;
11784 } 11824 }
11785 std::uint64_t end = 0; 11825 std::uint64_t end = 0;
@@ -11799,6 +11839,7 @@ bool DeviceState::materialize_table(std::uint64_t address, std::uint32_t slots)
11799 std::vector<leonida::DescriptorKey> all; 11839 std::vector<leonida::DescriptorKey> all;
11800 {std::lock_guard lock(pending_view_mutex);for(const auto& [key,v]:pending_samples) all.push_back(key);} 11840 {std::lock_guard lock(pending_view_mutex);for(const auto& [key,v]:pending_samples) all.push_back(key);}
11801 for(const auto& key:all) if(!materialize_sample(key)) return false; 11841 for(const auto& key:all) if(!materialize_sample(key)) return false;
11842 write_tsharp_index_words(all);
11802 return true; 11843 return true;
11803 } 11844 }
11804 const auto refreshed = std::min<std::uint64_t>(end-address, std::uint64_t(kViewScanLimit)*kDescriptorSize); 11845 const auto refreshed = std::min<std::uint64_t>(end-address, std::uint64_t(kViewScanLimit)*kDescriptorSize);
@@ -11809,11 +11850,49 @@ bool DeviceState::materialize_table(std::uint64_t address, std::uint32_t slots)
11809 for (auto at=address; at<end; at+=kDescriptorSize) { 11850 for (auto at=address; at<end; at+=kDescriptorSize) {
11810 leonida::DescriptorKey key{}; 11851 leonida::DescriptorKey key{};
11811 std::memcpy(key.data(),table+(at-address),sizeof(key)); 11852 std::memcpy(key.data(),table+(at-address),sizeof(key));
11812 if (leonida::gfx10::is_image(key) && !materialize_sample(key)) return false; 11853 if (!leonida::gfx10::is_image(key)) continue;
11854 // A deferred view's slot was written without its index word (it had no index): its key is the slot without
11855 // the word, and once made the slot gets it.
11856 key = leonida::gfx10::tsharp_key(key);
11857 if (!materialize_sample(key)) return false;
11858 if (tsharp_index_words) {
11859 const std::uint32_t word = tsharp_index_word(key);
11860 std::memcpy(table + (at - address) + 4 * leonida::gfx10::kTsharpIndexDword, &word, sizeof(word));
11861 }
11813 } 11862 }
11814 return true; 11863 return true;
11815} 11864}
11816 11865
11866// The views of `keys` made at last (materialize_sample, LEONIDA_PIPELINE_COMPILE=on-demand) without a table extent to
11867// name their slots: every T# of them in the layer's heaps (shader-visible, and the CPU-only ones a later
11868// CopyDescriptors copies from) gets its index word (tsharp_index_word). Only while views are pending, once per batch.
11869void DeviceState::write_tsharp_index_words(const std::vector<leonida::DescriptorKey>& keys) {
11870 if (!tsharp_index_words || keys.empty()) return;
11871 namespace g = leonida::gfx10;
11872 const std::set<leonida::DescriptorKey> wanted(keys.begin(), keys.end());
11873 std::vector<std::pair<std::uint8_t*, std::size_t>> ranges;
11874 {
11875 std::lock_guard lock(visible_heap_mutex);
11876 for (const auto& [offset, heap] : visible_heaps)
11877 if (heap.type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV)
11878 if (std::uint8_t* host = arena_host(offset, heap.end - offset))
11879 ranges.emplace_back(host, std::size_t(heap.end - offset));
11880 for (const auto& [begin, end] : cpu_view_heaps)
11881 ranges.emplace_back(reinterpret_cast<std::uint8_t*>(begin), std::size_t(end - begin));
11882 }
11883 std::lock_guard lock(descriptor_mutex);
11884 for (const auto& [base, bytes] : ranges)
11885 for (std::size_t at = 0; at + kDescriptorSize <= bytes; at += kDescriptorSize) {
11886 g::ImageWords words;
11887 std::memcpy(words.data(), base + at, sizeof(words));
11888 if (!g::is_image(words)) continue;
11889 const g::ImageWords key = g::tsharp_key(words);
11890 if (!wanted.count(key)) continue;
11891 const std::uint32_t word = tsharp_index_word_locked(key);
11892 std::memcpy(base + at + 4 * g::kTsharpIndexDword, &word, sizeof(word));
11893 }
11894}
11895
11817class Heap final 11896class Heap final
11818 : public Child<Heap, ID3D12HeapStubs, ID3D12Object, ID3D12DeviceChild, ID3D12Pageable, ID3D12Heap> { 11897 : public Child<Heap, ID3D12HeapStubs, ID3D12Object, ID3D12DeviceChild, ID3D12Pageable, ID3D12Heap> {
11819public: 11898public:
@@ -16426,6 +16505,21 @@ public:
16426 leonida::descriptor_table_layout_name(descriptor_table), table_modules.total()); 16505 leonida::descriptor_table_layout_name(descriptor_table), table_modules.total());
16427 } 16506 }
16428 state_.descriptor_table_tagged = descriptor_table == leonida::DescriptorTableLayout::tagged; 16507 state_.descriptor_table_tagged = descriptor_table == leonida::DescriptorTableLayout::tagged;
16508 // Whether the loaded modules read a T#'s index from its dword 6 (shader_library.h, TsharpIndexCensus): one such
16509 // module needs the word in every heap. Older modules find heap T#s by their words in the hash table, which the
16510 // word changes, so a library with both kinds is reported: its older modules read the fallback for those T#s.
16511 if (const leonida::ShaderLibrary* library = state_.library()) {
16512 const leonida::TsharpIndexCensus& census = library->tsharp_index_census();
16513 state_.tsharp_index_words = census.dword6 > 0;
16514 if (census.dword6 && census.none)
16515 std::fprintf(stderr,
16516 "[rt] d3d12: T# index word: %zu modules read it, %zu older ones look heap T#s up in the "
16517 "hash table and miss them (the heaps carry the word); translate the library again\n",
16518 census.dword6, census.none);
16519 else
16520 std::fprintf(stderr, "[rt] d3d12: T# index word: %s (all %zu modules)\n",
16521 census.dword6 ? "written into the heaps' T#s" : "not read", census.total());
16522 }
16429 const auto get_properties = reinterpret_cast<PFN_vkGetPhysicalDeviceProperties2>( 16523 const auto get_properties = reinterpret_cast<PFN_vkGetPhysicalDeviceProperties2>(
16430 state_.info.get_instance_proc(state_.info.instance, "vkGetPhysicalDeviceProperties2")); 16524 state_.info.get_instance_proc(state_.info.instance, "vkGetPhysicalDeviceProperties2"));
16431 if (get_properties) { 16525 if (get_properties) {
@@ -17239,7 +17333,7 @@ public:
17239 if (!leonida::gfx10::is_image(result)) return false; 17333 if (!leonida::gfx10::is_image(result)) return false;
17240 std::lock_guard descriptors(state_.descriptor_mutex); 17334 std::lock_guard descriptors(state_.descriptor_mutex);
17241 if (!state_.bindless) return true; 17335 if (!state_.bindless) return true;
17242 const auto entry = state_.image_entries.find(result); 17336 const auto entry = state_.image_entries.find(leonida::gfx10::tsharp_key(result));
17243 if (entry != state_.image_entries.end() && entry->second.storage) return true; 17337 if (entry != state_.image_entries.end() && entry->second.storage) return true;
17244 std::memset(reinterpret_cast<void*>(dest.ptr), 0, kDescriptorSize); 17338 std::memset(reinterpret_cast<void*>(dest.ptr), 0, kDescriptorSize);
17245 return false; 17339 return false;
@@ -22226,6 +22320,8 @@ private:
22226 log_once("shader access to 1D and 3D UAVs requires robustImageAccess; type", int(view.type)); 22320 log_once("shader access to 1D and 3D UAVs requires robustImageAccess; type", int(view.type));
22227 } else { 22321 } else {
22228 const bool known_heap = state_.known_view_heap(destination.ptr); 22322 const bool known_heap = state_.known_view_heap(destination.ptr);
22323 // A deferred view has no index yet: its slot gets the index word when the view is made
22324 // (materialize_table, write_tsharp_index_words).
22229 if (!storage && resource.deferrable_sample() && state_.info.prepare_on_bind && known_heap && 22325 if (!storage && resource.deferrable_sample() && state_.info.prepare_on_bind && known_heap &&
22230 !g::multisampled(image.type)) { 22326 !g::multisampled(image.type)) {
22231 state_.remember_sample(words,{const_cast<Resource*>(&resource),image,view_format,channels_format}); 22327 state_.remember_sample(words,{const_cast<Resource*>(&resource),image,view_format,channels_format});
@@ -22239,6 +22335,11 @@ private:
22239 sampled, storage, slices); 22335 sampled, storage, slices);
22240 if (registered && (resource.sparse_image() || storage_plane)) state_.context->note_shader_image(resource.id()); 22336 if (registered && (resource.sparse_image() || storage_plane)) state_.context->note_shader_image(resource.id());
22241 if (!registered && (g::multisampled(image.type) || storage_plane)) return; 22337 if (!registered && (g::multisampled(image.type) || storage_plane)) return;
22338 // In the layer's own heaps the bytes written here are what shaders load: dword 6 carries the index
22339 // (gfx10_descriptors.h, tsharp_index_word; 0 while the T# has none). A console heap (the title's memory)
22340 // is left as the title's own write would be: its copy gets the word when the slot is fixed.
22341 if (state_.tsharp_index_words && known_heap)
22342 words[g::kTsharpIndexDword] = state_.tsharp_index_word(words);
22242 } 22343 }
22243 // The CPU UAV used by ClearUnorderedAccessView is independent of set 0. 22344 // The CPU UAV used by ClearUnorderedAccessView is independent of set 0.
22244 std::memcpy(reinterpret_cast<void*>(destination.ptr), words.data(), sizeof(words)); 22345 std::memcpy(reinterpret_cast<void*>(destination.ptr), words.data(), sizeof(words));
@@ -23243,6 +23344,14 @@ bool arena_gpu_read(ID3D12Device* device, std::uint64_t va, void* out, std::size
23243 return gpu_buffer_read(*state, state->arena.buffer, va, wait, out, bytes); 23344 return gpu_buffer_read(*state, state->arena.buffer, va, wait, out, bytes);
23244} 23345}
23245 23346
23347bool set_tsharp_index_words_for_test(ID3D12Device* device, bool on) {
23348 DeviceState* state = mirror_state(device);
23349 if (!state) return false;
23350 const bool was = state->tsharp_index_words;
23351 state->tsharp_index_words = on;
23352 return was;
23353}
23354
23246bool page_mirror_buffer_at(ID3D12Device* device, std::uint64_t va, std::uint64_t& size) { 23355bool page_mirror_buffer_at(ID3D12Device* device, std::uint64_t va, std::uint64_t& size) {
23247 ID3D12Device* real = device ? rt::d3d12_xs::device_proxy_real_device(device) : nullptr; 23356 ID3D12Device* real = device ? rt::d3d12_xs::device_proxy_real_device(device) : nullptr;
23248 if (!real) real = device; 23357 if (!real) real = device;
@@ -23389,7 +23498,16 @@ VkDescriptorSetLayout bindless_set_layout(ID3D12Device* device) {
23389 23498
23390std::uint32_t bindless_hash_lookup(ID3D12Device* device, const std::uint32_t (&key)[8]) { 23499std::uint32_t bindless_hash_lookup(ID3D12Device* device, const std::uint32_t (&key)[8]) {
23391 const leonida::BindlessSet* set = bindless_of(device); 23500 const leonida::BindlessSet* set = bindless_of(device);
23392 return set ? set->table().lookup(key) : 0; 23501 if (!set) return 0;
23502 // A T# read back from one of the layer's heaps carries its index in dword 6 (tsharp_index_word): its key is the
23503 // descriptor without it, and the word must name the index the table holds, which is what a shader reads.
23504 namespace g = leonida::gfx10;
23505 g::ImageWords words;
23506 std::memcpy(words.data(), key, sizeof(words));
23507 if (!g::is_image(words) || !g::has_tsharp_index(words)) return set->table().lookup(key);
23508 const g::ImageWords stripped = g::tsharp_key(words);
23509 const std::uint32_t index = set->table().lookup(stripped.data());
23510 return index == g::tsharp_index_of(words) ? index : 0;
23393} 23511}
23394 23512
23395BindlessRoom bindless_room(ID3D12Device* device) { 23513BindlessRoom bindless_room(ID3D12Device* device) {
diff --git a/runtime/shims/xmem.cpp b/runtime/shims/xmem.cpp
index 69a0b9b44..6a0f36e15 100644
--- a/runtime/shims/xmem.cpp
+++ b/runtime/shims/xmem.cpp
@@ -46,6 +46,7 @@
46#include "../src/dstorage_trace.h" 46#include "../src/dstorage_trace.h"
47#include "../src/gpu_label_memory.h" 47#include "../src/gpu_label_memory.h"
48#include "../src/title_frames.h" 48#include "../src/title_frames.h"
49#include "../src/title_heap.h"
49#include "../src/title_mirror_space.h" 50#include "../src/title_mirror_space.h"
50#include "../src/title_page_watch.h" 51#include "../src/title_page_watch.h"
51#include "../src/title_geometry_watch.h" 52#include "../src/title_geometry_watch.h"
@@ -83,12 +84,57 @@ void note_attributes(const char* api, uint64_t attributes, size_t size, const vo
83// The title's XMemAlloc blocks come from a heap of their own instead of the CRT heap (LEONIDA_TITLE_HEAP=0: not). Slot-133 84// The title's XMemAlloc blocks come from a heap of their own instead of the CRT heap (LEONIDA_TITLE_HEAP=0: not). Slot-133
84// imports pin title memory page by page for the GPU, and on the CRT heap a pinned page also holds the runtime's own 85// imports pin title memory page by page for the GPU, and on the CRT heap a pinned page also holds the runtime's own
85// objects (g_pages' nodes among them): a GPU store past a buffer's end, or into a block freed while its import still 86// objects (g_pages' nodes among them): a GPU store past a buffer's end, or into a block freed while its import still
86// lived, then corrupted the runtime (speed-30/41/49-52: g_pages found corrupt under g_phys_mutex). Each block keeps its 87// lived, then corrupted the runtime (speed-30/41/49-52: g_pages found corrupt under g_phys_mutex).
87// size and the heap allocation it sits in just below it. 88//
89// The heap is the runtime's own (src/title_heap.h) over a reservation in the page mirror's range
90// (src/title_mirror_space.h), so a V# or pointer the title writes into a block reaches the mirror at heap_base + the
91// block's address, and its committed pages are fed to the mirror as they are committed (they read the title's bytes
92// there, not zeros). RtlCreateHeap over a given base faults under Wine. Where the range cannot take the reservation, a
93// heap the host places, as before (each block keeps its size and the heap allocation it sits in just below it).
88struct TitleHeapHeader { 94struct TitleHeapHeader {
89 void* raw; 95 void* raw;
90 size_t size; 96 size_t size;
91}; 97};
98constexpr size_t kTitleHeapBytes = size_t(32) << 30; // address range only: pages are committed as blocks need them
99
100// Tells the page mirror that the pages of [at, at + bytes) of the heap are committed (each shows itself) or not any
101// more (defined with the feed, below).
102void feed_heap_pages(uintptr_t at, size_t bytes, bool committed);
103
104leonida::TitleHeap& mirror_heap() {
105 static leonida::TitleHeap heap;
106 return heap;
107}
108bool mirror_heap_ready() {
109 static const bool ready = [] {
110 const char* v = std::getenv("LEONIDA_TITLE_HEAP");
111 if (v && std::strcmp(v, "0") == 0) return false;
112 uintptr_t base = 0;
113 // Not "plain": every committed page is fed to the mirror as it is committed, so a pointer the title wrote reads
114 // its bytes without anything naming the range first.
115 leonida::title_mirror_space::take(kTitleHeapBytes, 0x10000, false, [&](std::uint64_t at) {
116 void* const made = VirtualAlloc(reinterpret_cast<void*>(static_cast<uintptr_t>(at)), kTitleHeapBytes,
117 MEM_RESERVE, PAGE_READWRITE);
118 base = reinterpret_cast<uintptr_t>(made);
119 return made != nullptr;
120 });
121 leonida::TitleHeap::Hooks hooks;
122 hooks.commit = [](uintptr_t at, size_t bytes) {
123 if (!VirtualAlloc(reinterpret_cast<void*>(at), bytes, MEM_COMMIT, PAGE_READWRITE)) return false;
124 feed_heap_pages(at, bytes, true);
125 return true;
126 };
127 hooks.decommit = [](uintptr_t at, size_t bytes) {
128 feed_heap_pages(at, bytes, false);
129 VirtualFree(reinterpret_cast<void*>(at), bytes, MEM_DECOMMIT);
130 };
131 const bool ok = base && mirror_heap().init(base, kTitleHeapBytes, std::move(hooks));
132 std::fprintf(stderr, "[rt] xmem: XMemAlloc blocks come from %s\n",
133 ok ? "the runtime's heap in the page mirror's range" : "a heap the host places");
134 return ok;
135 }();
136 return ready;
137}
92HANDLE title_heap() { 138HANDLE title_heap() {
93 static const HANDLE heap = [] { 139 static const HANDLE heap = [] {
94 // Set LEONIDA_TITLE_HEAP=0 to use the CRT heap. 140 // Set LEONIDA_TITLE_HEAP=0 to use the CRT heap.
@@ -102,8 +148,10 @@ HANDLE title_heap() {
102} 148}
103void* allocate_block(size_t size) { 149void* allocate_block(size_t size) {
104 size = size ? size : 1; 150 size = size ? size : 1;
151 if (mirror_heap_ready())
152 if (void* p = mirror_heap().allocate(size)) return p; // full: the host's heap, as before
105 const HANDLE heap = title_heap(); 153 const HANDLE heap = title_heap();
106 if (!heap) return _aligned_malloc(size, kAlign); 154 if (!heap) return _aligned_malloc(size, kAlign); // LEONIDA_TITLE_HEAP=0
107 const size_t extra = kAlign + sizeof(TitleHeapHeader); 155 const size_t extra = kAlign + sizeof(TitleHeapHeader);
108 if (size > SIZE_MAX - extra) return nullptr; 156 if (size > SIZE_MAX - extra) return nullptr;
109 void* raw = HeapAlloc(heap, 0, size + extra); 157 void* raw = HeapAlloc(heap, 0, size + extra);
@@ -116,11 +164,16 @@ void* allocate_block(size_t size) {
116} 164}
117size_t block_size(void* p) { 165size_t block_size(void* p) {
118 if (!p) return 0; 166 if (!p) return 0;
167 if (mirror_heap_ready() && mirror_heap().owns(p)) return mirror_heap().size_of(p);
119 if (!title_heap()) return _aligned_msize(p, kAlign, 0); 168 if (!title_heap()) return _aligned_msize(p, kAlign, 0);
120 return (reinterpret_cast<TitleHeapHeader*>(p) - 1)->size; 169 return (reinterpret_cast<TitleHeapHeader*>(p) - 1)->size;
121} 170}
122void free_block(void* p) { 171void free_block(void* p) {
123 if (!p) return; 172 if (!p) return;
173 if (mirror_heap_ready() && mirror_heap().owns(p)) {
174 mirror_heap().release(p);
175 return;
176 }
124 const HANDLE heap = title_heap(); 177 const HANDLE heap = title_heap();
125 if (!heap) return _aligned_free(p); 178 if (!heap) return _aligned_free(p);
126 HeapFree(heap, 0, (reinterpret_cast<TitleHeapHeader*>(p) - 1)->raw); 179 HeapFree(heap, 0, (reinterpret_cast<TitleHeapHeader*>(p) - 1)->raw);
@@ -581,6 +634,16 @@ HostUnorderedMap<uintptr_t, TableFrame> g_table_frames;
581leonida::title_frames::Feed g_mirror_feed = nullptr; 634leonida::title_frames::Feed g_mirror_feed = nullptr;
582void* g_mirror_context = nullptr; 635void* g_mirror_context = nullptr;
583 636
637// The heap's committed pages show themselves (title_heap): fed to the page mirror as they are committed and
638// decommitted, under g_phys_mutex like every other change of the feed. Called with the heap's lock held (heap, then
639// g_phys_mutex; attach_mirror takes the heap's lock only after releasing g_phys_mutex).
640void feed_heap_pages(uintptr_t at, size_t bytes, bool committed) {
641 const std::lock_guard lock(g_phys_mutex);
642 if (!g_mirror_feed) return;
643 for (uintptr_t page = at & ~uintptr_t(kPhysicalPageSize - 1); page < at + bytes; page += kPhysicalPageSize)
644 g_mirror_feed(g_mirror_context, page, committed ? reinterpret_cast<uint8_t*>(page) : nullptr, {});
645}
646
584// With g_phys_mutex held: the page at `address` shows physical page `page` now (0: nothing), for the page mirror. 647// With g_phys_mutex held: the page at `address` shows physical page `page` now (0: nothing), for the page mirror.
585void feed_mirror(uintptr_t address, uint64_t page) { 648void feed_mirror(uintptr_t address, uint64_t page) {
586 if (!g_mirror_feed || !leonida::title_mirror_space::contains(address)) return; 649 if (!g_mirror_feed || !leonida::title_mirror_space::contains(address)) return;
@@ -2922,7 +2985,17 @@ void slot31_mapping_counts(Slot31Counts& out) {
2922// their physical pages' host addresses. 2985// their physical pages' host addresses.
2923// title_frames' Attach (src/title_frames.h): the page mirror's feed from now on, after every page of the mirror's range 2986// title_frames' Attach (src/title_frames.h): the page mirror's feed from now on, after every page of the mirror's range
2924// mapped now (the views, then the table pages), all under g_phys_mutex. 2987// mapped now (the views, then the table pages), all under g_phys_mutex.
2988void attach_mirror_locked(void* context, leonida::title_frames::Feed feed);
2925void attach_mirror(void* context, leonida::title_frames::Feed feed) { 2989void attach_mirror(void* context, leonida::title_frames::Feed feed) {
2990 attach_mirror_locked(context, feed);
2991 if (!feed || !mirror_heap_ready()) return;
2992 // The heap's committed pages, after g_phys_mutex (the heap takes it under its own lock). A page committed or
2993 // decommitted meanwhile was fed by the heap itself; one fed twice is mapped twice to the same bytes.
2994 std::vector<std::pair<uintptr_t, size_t>> committed;
2995 mirror_heap().for_each_committed([&](uintptr_t at, size_t bytes) { committed.emplace_back(at, bytes); });
2996 for (const auto& [at, bytes] : committed) feed_heap_pages(at, bytes, true);
2997}
2998void attach_mirror_locked(void* context, leonida::title_frames::Feed feed) {
2926 const std::lock_guard lock(g_phys_mutex); 2999 const std::lock_guard lock(g_phys_mutex);
2927 g_mirror_feed = feed; 3000 g_mirror_feed = feed;
2928 g_mirror_context = context; 3001 g_mirror_context = context;
diff --git a/runtime/src/gfx10_descriptors.h b/runtime/src/gfx10_descriptors.h
index acfa590f8..5773c8734 100644
--- a/runtime/src/gfx10_descriptors.h
+++ b/runtime/src/gfx10_descriptors.h
@@ -179,6 +179,45 @@ inline constexpr bool partial_volume_uav(const ImageWords& words, const Image& i
179 return range.first_w != 0 || range.w_size != (mip_depth ? mip_depth : 1u); 179 return range.first_w != 0 || range.w_size != (mip_depth ? mip_depth : 1u);
180} 180}
181 181
182// The bindless index in the T# (docs/design.md, "Bindless index in the T#"). In the heaps shaders read (the copies of
183// the console resource heaps and the layer's own shader-visible heaps) the layer writes dword 6 of every T# as
184// TAG [31:28] | storage kind [27:23] | sampled kind [22:16] | index [15:0]
185// where the kinds are descriptor_table.h's kind bits 8..12 and 0..6 for that index. A translated shader that loaded
186// the T# from such a heap takes the index from this word and no hash-table lookup (tools/rdna2spirv.py,
187// tsharp_index_word), and reads index 0 (the fallback) unless the word has the tag and dword 3 names an image (TYPE
188// 8..15, bit 31). Dword 6 is the hardware's compression metadata (META_DATA_ADDRESS, COMPRESSION_EN and friends),
189// which no Vulkan view uses; over the 1.0.2.1 corpus no shader reads dword 6 or 7 of a heap T# with a scalar
190// instruction (tools/descriptor_source_census.py). The title's own bytes keep their dword 6, and a T#'s table key
191// stays the descriptor as the title or Create*View wrote it (tsharp_key strips the word from the layer's heaps).
192inline constexpr unsigned kTsharpIndexDword = 6;
193inline constexpr std::uint32_t kTsharpIndexTag = 0xA;
194inline constexpr std::uint32_t kTsharpIndexLimit = 0x10000; // an index past 16 bits gets no word (the fallback)
195
196// The word for `index` bound in the arrays `kind` names (descriptor_table.h's kind bits); 0 for index 0 or one that
197// does not fit, which every shader reads as the fallback.
198inline constexpr std::uint32_t tsharp_index_word(std::uint32_t index, std::uint32_t kind) {
199 if (!index || index >= kTsharpIndexLimit) return 0;
200 return (kTsharpIndexTag << 28) | (((kind >> 8) & 0x1Fu) << 23) | ((kind & 0x7Fu) << 16) | index;
201}
202inline constexpr bool has_tsharp_index(const ImageWords& words) {
203 return (words[kTsharpIndexDword] >> 28) == kTsharpIndexTag;
204}
205// The index and kind a shader reads from `words` (0 and 0 without the tag or when dword 3 names no image).
206inline constexpr std::uint32_t tsharp_index_of(const ImageWords& words) {
207 return has_tsharp_index(words) && (words[3] >> 31) ? words[kTsharpIndexDword] & 0xFFFFu : 0u;
208}
209inline constexpr std::uint32_t tsharp_kind_of(const ImageWords& words) {
210 if (!has_tsharp_index(words) || !(words[3] >> 31)) return 0;
211 const std::uint32_t w = words[kTsharpIndexDword];
212 return ((w >> 16) & 0x7Fu) | (((w >> 23) & 0x1Fu) << 8);
213}
214// The key of a T# the layer wrote into one of its own heaps: dword 6 as encode() writes it (0) when it carries the
215// index. Only for words read back from the layer's heaps; a title's T# keeps whatever its dword 6 holds.
216inline constexpr ImageWords tsharp_key(ImageWords words) {
217 if (has_tsharp_index(words)) words[kTsharpIndexDword] = 0;
218 return words;
219}
220
182inline constexpr float image_min_lod(const ImageWords& words) { 221inline constexpr float image_min_lod(const ImageWords& words) {
183 return float(detail::get(words[1], 8, 12)) / 256.0f; 222 return float(detail::get(words[1], 8, 12)) / 256.0f;
184} 223}
diff --git a/runtime/src/shader_library.h b/runtime/src/shader_library.h
index 87fd5058e..16cdff14d 100644
--- a/runtime/src/shader_library.h
+++ b/runtime/src/shader_library.h
@@ -923,6 +923,19 @@ inline DescriptorTableLayout majority_descriptor_table_layout(const DescriptorTa
923 return census.tagged > 0 ? DescriptorTableLayout::tagged : DescriptorTableLayout::plain; 923 return census.tagged > 0 ? DescriptorTableLayout::tagged : DescriptorTableLayout::plain;
924} 924}
925 925
926// Which modules read a T#'s bindless index from its dword 6 (gfx10_descriptors.h, tsharp_index_word; tools/rdna2spirv.py
927// TSHARP_INDEX): index.json meta `"tsharp_index": "dword6"`. Such a module takes the index of a T# it loaded from a
928// heap from that word and nothing else, so the layer must write it into every heap it keeps; a module translated
929// before has no key and finds its T#s by their words in the hash table, which the written word changes (the copy's
930// dword 6 is no longer the title's). The device writes the word when any module reads it, and says so when modules
931// of both kinds are loaded: the older ones then miss the T#s of the heaps and read the fallback, so a library is to be
932// translated by one translator.
933struct TsharpIndexCensus {
934 std::size_t dword6 = 0;
935 std::size_t none = 0;
936 std::size_t total() const { return dword6 + none; }
937};
938
926// LEONIDA_DESCRIPTOR_TABLE=plain|tagged overrides the modules' vote. False when `value` is null, empty or not one 939// LEONIDA_DESCRIPTOR_TABLE=plain|tagged overrides the modules' vote. False when `value` is null, empty or not one
927// of the two layouts (an unrecognised value is ignored rather than failing startup). 940// of the two layouts (an unrecognised value is ignored rather than failing startup).
928inline bool descriptor_table_layout_from_env(const char* value, DescriptorTableLayout* layout) { 941inline bool descriptor_table_layout_from_env(const char* value, DescriptorTableLayout* layout) {
@@ -1028,6 +1041,7 @@ public:
1028 exe_count_ = 0; 1041 exe_count_ = 0;
1029 descriptor_hash_census_ = {}; 1042 descriptor_hash_census_ = {};
1030 descriptor_table_census_ = {}; 1043 descriptor_table_census_ = {};
1044 tsharp_index_census_ = {};
1031 vsharp_base_census_ = {}; 1045 vsharp_base_census_ = {};
1032 for (const char* folder : {"fspx", "fspx_gfx"}) { 1046 for (const char* folder : {"fspx", "fspx_gfx"}) {
1033 try { 1047 try {
@@ -1057,6 +1071,8 @@ public:
1057 DescriptorTableLayout descriptor_table_layout() const { 1071 DescriptorTableLayout descriptor_table_layout() const {
1058 return majority_descriptor_table_layout(descriptor_table_census_); 1072 return majority_descriptor_table_layout(descriptor_table_census_);
1059 } 1073 }
1074 // The modules that read a T#'s index from its dword 6 (TsharpIndexCensus) and those that do not.
1075 const TsharpIndexCensus& tsharp_index_census() const { return tsharp_index_census_; }
1060 // How the loaded modules read a V#'s 48-bit base: the device names buffers below heap_base (negative offsets) only 1076 // How the loaded modules read a V#'s 48-bit base: the device names buffers below heap_base (negative offsets) only
1061 // when every one of them sign-extends it. 1077 // when every one of them sign-extends it.
1062 const VsharpBaseCensus& vsharp_base_census() const { return vsharp_base_census_; } 1078 const VsharpBaseCensus& vsharp_base_census() const { return vsharp_base_census_; }
@@ -1240,6 +1256,7 @@ private:
1240 exe_count_ = 0; 1256 exe_count_ = 0;
1241 descriptor_hash_census_ = {}; 1257 descriptor_hash_census_ = {};
1242 descriptor_table_census_ = {}; 1258 descriptor_table_census_ = {};
1259 tsharp_index_census_ = {};
1243 vsharp_base_census_ = {}; 1260 vsharp_base_census_ = {};
1244 } 1261 }
1245 for (const auto& [name, meta] : root.object) { 1262 for (const auto& [name, meta] : root.object) {
@@ -1343,6 +1360,11 @@ private:
1343 ++descriptor_table_census_.tagged; 1360 ++descriptor_table_census_.tagged;
1344 else 1361 else
1345 ++descriptor_table_census_.plain; 1362 ++descriptor_table_census_.plain;
1363 // Whether this module reads a T#'s index from its dword 6 (TsharpIndexCensus). Absent is the hash lookup.
1364 if (const Json* ti = meta.find("tsharp_index"); ti && ti->kind == Json::Kind::string && ti->string == "dword6")
1365 ++tsharp_index_census_.dword6;
1366 else
1367 ++tsharp_index_census_.none;
1346 // How this module reads a V#'s 48-bit base (VsharpBaseCensus). Absent is the old zero extension. 1368 // How this module reads a V#'s 48-bit base (VsharpBaseCensus). Absent is the old zero extension.
1347 if (const Json* sx = meta.find("vsharp_base_sign_extended"); sx && sx->kind == Json::Kind::boolean && sx->boolean) 1369 if (const Json* sx = meta.find("vsharp_base_sign_extended"); sx && sx->kind == Json::Kind::boolean && sx->boolean)
1348 ++vsharp_base_census_.sign_extended; 1370 ++vsharp_base_census_.sign_extended;
@@ -1372,6 +1394,7 @@ private:
1372 Entries fspx_entries_; 1394 Entries fspx_entries_;
1373 DescriptorHashCensus descriptor_hash_census_; 1395 DescriptorHashCensus descriptor_hash_census_;
1374 DescriptorTableCensus descriptor_table_census_; 1396 DescriptorTableCensus descriptor_table_census_;
1397 TsharpIndexCensus tsharp_index_census_;
1375 VsharpBaseCensus vsharp_base_census_; 1398 VsharpBaseCensus vsharp_base_census_;
1376}; 1399};
1377 1400
diff --git a/runtime/src/title_heap.h b/runtime/src/title_heap.h
new file mode 100644
index 000000000..92f7856f5
--- /dev/null
+++ b/runtime/src/title_heap.h
@@ -0,0 +1,207 @@
1#pragma once
2// The XMemAlloc heap (title_heap): the title's XMemAlloc / XMemAllocDefault blocks, carved from one reservation that
3// xmem places in the page mirror's range (src/title_mirror_space.h), so a V# or pointer the title writes into a block
4// reaches the mirror at heap_base + the block's address. Windows' RtlCreateHeap over a given base faults under Wine
5// (it writes into the reserved base), so the heap is the runtime's own.
6//
7// What the title sees, as before: every block 64-byte aligned, a size of zero one byte, blocks that never overlap,
8// XMemFree of a block from either entry point. There is no realloc and no size query in the title's ABI; size_of
9// answers xmem's own bookkeeping (the bytes a free tells the readers about).
10//
11// The layout:
12// - the reservation is handed out in 64 KiB pages by a first-fit list of free runs, coalesced on free;
13// - blocks up to kSmallMax come from spans of kSpan bytes, one size class a span (multiples of 64 bytes up to 1 KiB,
14// then powers of two), each class with a stack of free blocks kept outside the title's memory (a freed block's
15// bytes are never written by the heap);
16// - larger blocks are runs of whole pages, committed when handed out and decommitted when freed (they read zero when
17// handed out again, as HeapAlloc's large blocks do).
18// Pages are committed through the hooks (xmem: VirtualAlloc, then the page mirror's feed). One lock, taken for every
19// call; nothing the title's memory holds is read or written under it. Portable: the hooks do the system calls.
20#include <algorithm>
21#include <cstddef>
22#include <cstdint>
23#include <functional>
24#include <map>
25#include <mutex>
26#include <vector>
27
28namespace leonida {
29
30class TitleHeap {
31public:
32 static constexpr std::size_t kAlign = 64;
33 static constexpr std::size_t kPage = 0x10000;
34 static constexpr std::size_t kSpan = std::size_t(1) << 20;
35 static constexpr std::size_t kSmallMax = 32768;
36
37 struct Hooks {
38 std::function<bool(std::uintptr_t, std::size_t)> commit; // [at, at + bytes) usable from now on
39 std::function<void(std::uintptr_t, std::size_t)> decommit; // [at, at + bytes) given back (reads zero later)
40 };
41 struct Stats {
42 std::size_t committed = 0, spans = 0, large = 0, live = 0;
43 };
44
45 bool init(std::uintptr_t base, std::size_t bytes, Hooks hooks) {
46 std::lock_guard lock(mutex_);
47 if (!base || bytes < kSpan || (base % kPage)) return false;
48 base_ = base;
49 bytes_ = bytes - bytes % kPage;
50 hooks_ = std::move(hooks);
51 free_runs_.clear();
52 free_runs_[base_] = bytes_;
53 span_class_.assign(bytes_ / kSpan, kNoClass);
54 return true;
55 }
56 bool owns(const void* p) const {
57 const auto at = reinterpret_cast<std::uintptr_t>(p);
58 return base_ && at >= base_ && at - base_ < bytes_;
59 }
60
61 void* allocate(std::size_t size) {
62 if (!size) size = 1;
63 std::lock_guard lock(mutex_);
64 if (!base_) return nullptr;
65 if (size <= kSmallMax) {
66 const unsigned c = class_of(size);
67 Class& cls = classes_[c];
68 if (cls.free.empty() && !grow(c)) return nullptr;
69 const std::uintptr_t at = cls.free.back();
70 cls.free.pop_back();
71 ++stats_.live;
72 return reinterpret_cast<void*>(at);
73 }
74 const std::size_t bytes = (size + kPage - 1) & ~(kPage - 1);
75 if (bytes < size) return nullptr;
76 const std::uintptr_t at = take_run(bytes);
77 if (!at) return nullptr;
78 if (hooks_.commit && !hooks_.commit(at, bytes)) {
79 give_run(at, bytes);
80 return nullptr;
81 }
82 large_[at] = bytes;
83 stats_.committed += bytes;
84 ++stats_.large;
85 ++stats_.live;
86 return reinterpret_cast<void*>(at);
87 }
88
89 // The bytes the block at `p` holds (its class's size, or its pages): 0 for a pointer that is not a live block's.
90 std::size_t size_of(const void* p) const {
91 const auto at = reinterpret_cast<std::uintptr_t>(p);
92 std::lock_guard lock(mutex_);
93 if (!owns(p)) return 0;
94 if (const auto it = large_.find(at); it != large_.end()) return it->second;
95 const unsigned c = span_class_[(at - base_) / kSpan];
96 return c == kNoClass ? 0 : class_size(c);
97 }
98
99 // Frees a block allocate() returned. False (nothing done) for any other pointer.
100 bool release(void* p) {
101 const auto at = reinterpret_cast<std::uintptr_t>(p);
102 std::lock_guard lock(mutex_);
103 if (!owns(p)) return false;
104 if (const auto it = large_.find(at); it != large_.end()) {
105 const std::size_t bytes = it->second;
106 large_.erase(it);
107 if (hooks_.decommit) hooks_.decommit(at, bytes);
108 stats_.committed -= bytes;
109 --stats_.large;
110 --stats_.live;
111 give_run(at, bytes);
112 return true;
113 }
114 const unsigned c = span_class_[(at - base_) / kSpan];
115 if (c == kNoClass || (at - base_) % kSpan % class_size(c)) return false;
116 classes_[c].free.push_back(at);
117 --stats_.live;
118 return true;
119 }
120
121 // f(at, bytes) for each committed range (a span or a large block), for a reader that starts late.
122 template <class F>
123 void for_each_committed(F&& f) const {
124 std::lock_guard lock(mutex_);
125 for (std::size_t s = 0; s < span_class_.size(); ++s)
126 if (span_class_[s] != kNoClass) f(base_ + s * kSpan, kSpan);
127 for (const auto& [at, bytes] : large_) f(at, bytes);
128 }
129
130 Stats stats() const {
131 std::lock_guard lock(mutex_);
132 return stats_;
133 }
134
135 static constexpr unsigned kClasses = 16 + 5; // 64..1024 by 64, then 2, 4, 8, 16, 32 KiB
136 static std::size_t class_size(unsigned c) { return c < 16 ? (c + 1) * 64 : std::size_t(1024) << (c - 15); }
137 static unsigned class_of(std::size_t size) {
138 if (size <= 1024) return unsigned((size + 63) / 64 - 1);
139 unsigned c = 16;
140 while (class_size(c) < size) ++c;
141 return c;
142 }
143
144private:
145 static constexpr unsigned kNoClass = 0xff;
146 struct Class {
147 std::vector<std::uintptr_t> free;
148 };
149
150 // A new span for class `c`: committed, cut into blocks pushed on its stack (in address order: the lowest first).
151 bool grow(unsigned c) {
152 const std::uintptr_t at = take_run(kSpan, kSpan);
153 if (!at) return false;
154 if (hooks_.commit && !hooks_.commit(at, kSpan)) {
155 give_run(at, kSpan);
156 return false;
157 }
158 span_class_[(at - base_) / kSpan] = std::uint8_t(c);
159 stats_.committed += kSpan;
160 ++stats_.spans;
161 const std::size_t size = class_size(c);
162 for (std::size_t off = kSpan / size * size; off >= size; off -= size) classes_[c].free.push_back(at + off - size);
163 return true;
164 }
165 // The first free run that holds `bytes` at an offset from the base aligned to `align` (spans are numbered from the
166 // base, which is only page-aligned).
167 std::uintptr_t take_run(std::size_t bytes, std::size_t align = kPage) {
168 for (auto it = free_runs_.begin(); it != free_runs_.end(); ++it) {
169 const std::uintptr_t start = base_ + ((it->first - base_ + align - 1) & ~(std::uintptr_t(align) - 1));
170 const std::uintptr_t end = it->first + it->second;
171 if (start >= end || end - start < bytes) continue;
172 const std::uintptr_t run = it->first, run_end = end;
173 free_runs_.erase(it);
174 if (start > run) free_runs_[run] = start - run;
175 if (start + bytes < run_end) free_runs_[start + bytes] = run_end - (start + bytes);
176 return start;
177 }
178 return 0;
179 }
180 void give_run(std::uintptr_t at, std::size_t bytes) {
181 auto next = free_runs_.lower_bound(at);
182 if (next != free_runs_.end() && at + bytes == next->first) {
183 bytes += next->second;
184 next = free_runs_.erase(next);
185 }
186 if (next != free_runs_.begin()) {
187 const auto previous = std::prev(next);
188 if (previous->first + previous->second == at) {
189 previous->second += bytes;
190 return;
191 }
192 }
193 free_runs_[at] = bytes;
194 }
195
196 mutable std::mutex mutex_;
197 std::uintptr_t base_ = 0;
198 std::size_t bytes_ = 0;
199 Hooks hooks_;
200 std::map<std::uintptr_t, std::size_t> free_runs_; // start -> bytes
201 std::map<std::uintptr_t, std::size_t> large_; // a large block -> its bytes
202 std::vector<std::uint8_t> span_class_; // per span: its class, or kNoClass
203 Class classes_[kClasses];
204 Stats stats_;
205};
206
207} // namespace leonida
diff --git a/runtime/src/title_mirror.h b/runtime/src/title_mirror.h
index bac0fdc89..90ebd3205 100644
--- a/runtime/src/title_mirror.h
+++ b/runtime/src/title_mirror.h
@@ -23,6 +23,8 @@
23// serialises (the device under its mirror mutex). 23// serialises (the device under its mirror mutex).
24#include <vulkan/vulkan.h> 24#include <vulkan/vulkan.h>
25 25
26#include "shadow_keep.h"
27
26#include <cstdint> 28#include <cstdint>
27#include <cstring> 29#include <cstring>
28#include <deque> 30#include <deque>
@@ -63,6 +65,9 @@ public:
63 std::uint64_t binds = 0, unbinds = 0, batches = 0, uploads = 0, upload_failures = 0, homes_freed = 0; // so far 65 std::uint64_t binds = 0, unbinds = 0, batches = 0, uploads = 0, upload_failures = 0, homes_freed = 0; // so far
64 std::uint64_t unmirrored_changes = 0; // feed entries outside every chunk 66 std::uint64_t unmirrored_changes = 0; // feed entries outside every chunk
65 std::uint64_t filtered = 0; // fills through hooks.filter (filter_range), of the uploads 67 std::uint64_t filtered = 0; // fills through hooks.filter (filter_range), of the uploads
68 // Bytes the uploads copied into homes, bytes write_back() copied to the title's pages, and 256-byte pieces
69 // both sides had changed (the title's bytes kept), so far.
70 std::uint64_t uploaded_bytes = 0, written_back_bytes = 0, conflicts = 0;
66 }; 71 };
67 72
68 explicit TitleMirror(TitleMirrorHooks hooks) : hooks_(std::move(hooks)) {} 73 explicit TitleMirror(TitleMirrorHooks hooks) : hooks_(std::move(hooks)) {}
@@ -211,13 +216,53 @@ public:
211 const auto home = homes_.find(frame); 216 const auto home = homes_.find(frame);
212 if (home == homes_.end() || !home->second.dirty) continue; 217 if (home == homes_.end() || !home->second.dirty) continue;
213 home->second.dirty = false; 218 home->second.dirty = false;
214 fill(home->second, frame); 219 fill(home->second, frame, false);
215 ++n; 220 ++n;
216 } 221 }
217 dirty_.clear(); 222 dirty_.clear();
218 return n; 223 return n;
219 } 224 }
220 225
226 // What the GPU wrote into the homes of the mirrored pages of [begin, end) goes to the title's pages, merged at the
227 // 256-byte piece against the sums both sides last agreed on: a piece only the GPU changed is written back with
228 // `write(va, bytes, n)` (and agreed on again); a piece only the title changed waits for the upload; a piece both
229 // changed keeps the title's bytes and is counted. Call it once the submissions that could write the range have
230 // completed. Returns the bytes written back.
231 template <class Write>
232 std::uint64_t write_back(std::uint64_t begin, std::uint64_t end, Write&& write) {
233 std::uint64_t written = 0;
234 alignas(64) std::uint8_t title[kPiece];
235 for (std::uint64_t page = begin & ~(kPage - 1); page < end; page += kPage) {
236 const auto mapped = pages_.find(page);
237 if (mapped == pages_.end()) continue;
238 const auto found = homes_.find(mapped->second);
239 if (found == homes_.end()) continue;
240 Home& home = found->second;
241 // A filtered home holds the filter's bytes, not the title's: nothing of it is ever written back.
242 if (home.filter_va) continue;
243 const std::uint8_t* gpu = units_[home.unit].host + std::size_t(home.slot) * kPage;
244 const std::size_t k0 = std::size_t((std::max(begin, page) - page) / kPiece);
245 const std::size_t k1 = std::size_t((std::min(end, page + kPage) - page + kPiece - 1) / kPiece);
246 for (std::size_t k = k0; k < k1; ++k) {
247 const std::uint64_t agreed = home.sums[k];
248 const std::uint64_t now = shadow_keep::sum_of(gpu + k * kPiece, kPiece);
249 if (now == agreed) continue; // the GPU did not change it
250 const std::uint8_t* from = mapped->second + k * kPiece;
251 if (!(hooks_.copy ? hooks_.copy(title, from, kPiece) : (std::memcpy(title, from, kPiece), true)))
252 continue; // the title's page went away
253 if (shadow_keep::sum_of(title, kPiece) != agreed) {
254 ++counters_.conflicts; // both changed it: the title's bytes win at the next upload
255 continue;
256 }
257 if (!write(page + k * kPiece, gpu + k * kPiece, kPiece)) continue;
258 home.sums[k] = now;
259 written += kPiece;
260 }
261 }
262 counters_.written_back_bytes += written;
263 return written;
264 }
265
221 // The binds noted since the last flush, as one batch signalling `value`. False when there were none (nothing to 266 // The binds noted since the last flush, as one batch signalling `value`. False when there were none (nothing to
222 // wait for) or the bind failed (counted; the caller logs). 267 // wait for) or the bind failed (counted; the caller logs).
223 bool flush(std::uint64_t value) { 268 bool flush(std::uint64_t value) {
@@ -296,10 +341,15 @@ public:
296 } 341 }
297 342
298private: 343private:
344 // A home and the sum of each of its 256-byte pieces as both sides last agreed on it (src/shadow_keep.h): what was
345 // filled from the title's page, or written back to it. A piece whose home differs from its sum was written by the
346 // GPU, one whose title page differs by the title.
347 static constexpr std::size_t kPiece = shadow_keep::kPiece, kPieces = kPage / kPiece;
299 struct Home { 348 struct Home {
300 std::uint32_t unit = 0, slot = 0, refs = 0; 349 std::uint32_t unit = 0, slot = 0, refs = 0;
301 std::shared_ptr<void> keep; 350 std::shared_ptr<void> keep;
302 bool dirty = false; 351 bool dirty = false;
352 std::unique_ptr<std::uint64_t[]> sums = std::make_unique<std::uint64_t[]>(kPieces);
303 std::uint64_t filter_va = 0; // a filtered page that shows it (filter_range), 0: filled by copy 353 std::uint64_t filter_va = 0; // a filtered page that shows it (filter_range), 0: filled by copy
304 bool fresh = true; // the next fill writes every byte (hooks.filter's `fresh`) 354 bool fresh = true; // the next fill writes every byte (hooks.filter's `fresh`)
305 }; 355 };
@@ -318,20 +368,58 @@ private:
318 std::uint64_t ticket; 368 std::uint64_t ticket;
319 }; 369 };
320 370
321 void fill(Home& home, const std::uint8_t* frame) { 371 // Brings the home up to date with the title's page, piece by piece: `whole` (a new home) copies every piece, and
372 // otherwise only a piece the title changed since both sides last agreed, so a piece only the GPU wrote keeps the
373 // GPU's bytes (and goes back with write_back). A piece both changed takes the title's bytes.
374 void fill(Home& home, const std::uint8_t* frame, bool whole) {
322 std::uint8_t* to = units_[home.unit].host + std::size_t(home.slot) * kPage; 375 std::uint8_t* to = units_[home.unit].host + std::size_t(home.slot) * kPage;
323 const bool fresh = home.fresh; 376 alignas(64) std::uint8_t title[kPiece];
324 home.fresh = false; 377 bool failed = false;
325 const bool ok = home.filter_va && hooks_.filter ? hooks_.filter(home.filter_va, to, frame, kPage, fresh) 378 if (home.filter_va && hooks_.filter) {
326 : hooks_.copy ? hooks_.copy(to, frame, kPage) 379 // A filtered page (a console heap read in place): its sums are of the title's bytes the filter last read,
327 : (std::memcpy(to, frame, kPage), true); 380 // so the compare below is the title's bytes against the title's bytes; the filter, after it, writes the
328 if (!ok) { 381 // home - every byte when fresh, else the slots that changed - whenever a piece of the title's page did.
329 std::memset(to, 0, kPage); 382 // The home's bytes are the filter's, never compared with a sum (write_back skips it).
330 home.fresh = true; // zeros now: the next fill writes all again 383 const bool fresh = whole || home.fresh;
331 ++counters_.upload_failures; 384 std::size_t changed = 0;
385 for (std::size_t k = 0; k < kPieces; ++k) {
386 const std::uint8_t* from = frame + k * kPiece;
387 if (!(hooks_.copy ? hooks_.copy(title, from, kPiece) : (std::memcpy(title, from, kPiece), true)))
388 std::memset(title, 0, kPiece);
389 const std::uint64_t sum = shadow_keep::sum_of(title, kPiece);
390 if (sum == home.sums[k]) continue;
391 home.sums[k] = sum;
392 ++changed;
393 }
394 if (fresh || changed) {
395 home.fresh = false;
396 if (!hooks_.filter(home.filter_va, to, frame, kPage, fresh)) {
397 std::memset(to, 0, kPage);
398 home.fresh = true; // zeros now: the next fill writes all again
399 failed = true;
400 }
401 counters_.uploaded_bytes += (fresh ? kPieces : changed) * kPiece;
402 ++counters_.filtered;
403 }
404 } else {
405 // A home filtered until now (or zeroed by a failed fill) is copied whole once.
406 const bool all = whole || home.fresh;
407 home.fresh = false;
408 for (std::size_t k = 0; k < kPieces; ++k) {
409 const std::uint8_t* from = frame + k * kPiece;
410 if (!(hooks_.copy ? hooks_.copy(title, from, kPiece) : (std::memcpy(title, from, kPiece), true))) {
411 std::memset(title, 0, kPiece);
412 failed = true;
413 }
414 const std::uint64_t sum = shadow_keep::sum_of(title, kPiece);
415 if (!all && sum == home.sums[k]) continue;
416 std::memcpy(to + k * kPiece, title, kPiece);
417 home.sums[k] = sum;
418 counters_.uploaded_bytes += kPiece;
419 }
332 } 420 }
421 if (failed) ++counters_.upload_failures;
333 ++counters_.uploads; 422 ++counters_.uploads;
334 if (home.filter_va) ++counters_.filtered;
335 } 423 }
336 424
337 Home* home_of(std::uint8_t* frame, std::shared_ptr<void> keep, std::uint64_t va) { 425 Home* home_of(std::uint8_t* frame, std::shared_ptr<void> keep, std::uint64_t va) {
@@ -346,7 +434,7 @@ private:
346 home.slot = slot; 434 home.slot = slot;
347 home.keep = std::move(keep); 435 home.keep = std::move(keep);
348 home.filter_va = filtered(va) ? va : 0; 436 home.filter_va = filtered(va) ? va : 0;
349 fill(home, frame); 437 fill(home, frame, true);
350 return &home; 438 return &home;
351 } 439 }
352 440
diff --git a/runtime/test/d3d12_heap_in_place_test.cpp b/runtime/test/d3d12_heap_in_place_test.cpp
index 910857242..af171a9eb 100644
--- a/runtime/test/d3d12_heap_in_place_test.cpp
+++ b/runtime/test/d3d12_heap_in_place_test.cpp
@@ -8,7 +8,10 @@
8// 2. a slot the title rewrites (through its own view: a guard fault) reaches the GPU at the next refresh, filtered; 8// 2. a slot the title rewrites (through its own view: a guard fault) reaches the GPU at the next refresh, filtered;
9// the title's bytes are again as written; 9// the title's bytes are again as written;
10// 3. the null slots after the heap read zero, and the heap's address is below 4 GiB; 10// 3. the null slots after the heap read zero, and the heap's address is below 4 GiB;
11// 4. no copy: the device names it "read in place". 11// 4. no copy: the device names it "read in place";
12// 5. a T# in the heap (the words CreateShaderResourceView wrote for a texture of ours) reads with the bindless index
13// in its dword 6 (gfx10_descriptors.h, tsharp_index_word: the tag and the texture's index) once the filter and its
14// finishing have run, while the title's bytes keep the dword 6 the title wrote.
12// Exit 77 when the device makes no page mirror (llvmpipe). No shaders, no game data. 15// Exit 77 when the device makes no page mirror (llvmpipe). No shaders, no game data.
13#include "../shims/d3d12_com.h" 16#include "../shims/d3d12_com.h"
14#include "../shims/d3d12_xs_device.h" 17#include "../shims/d3d12_xs_device.h"
@@ -102,11 +105,40 @@ int test() {
102 const auto put = [&](unsigned slot, const leonida::gfx10::BufferWords& w) { 105 const auto put = [&](unsigned slot, const leonida::gfx10::BufferWords& w) {
103 std::memcpy(title + slot * kDescriptor, w.data(), sizeof(w)); 106 std::memcpy(title + slot * kDescriptor, w.data(), sizeof(w));
104 }; 107 };
108 // A texture of ours and its T#, as CreateShaderResourceView writes it into a CPU heap (before the index word is on:
109 // dword 6 as encode() writes it). The index word is then on, as a library of modules that read it turns it on.
110 D3D12_RESOURCE_DESC tex_desc{};
111 tex_desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
112 tex_desc.Width = 64;
113 tex_desc.Height = 64;
114 tex_desc.DepthOrArraySize = 1;
115 tex_desc.MipLevels = 1;
116 tex_desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
117 tex_desc.SampleDesc.Count = 1;
118 Ref<ID3D12Resource> texture;
119 EXPECT(SUCCEEDED(device.p->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &tex_desc,
120 D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, nullptr,
121 IID_PPV_ARGS(&texture.p))));
122 const D3D12_DESCRIPTOR_HEAP_DESC cpu_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE,
123 0};
124 Ref<ID3D12DescriptorHeap> cpu_heap;
125 EXPECT(SUCCEEDED(device.p->CreateDescriptorHeap(&cpu_desc, IID_PPV_ARGS(&cpu_heap.p))));
126 const D3D12_CPU_DESCRIPTOR_HANDLE cpu = cpu_heap.p->GetCPUDescriptorHandleForHeapStart();
127 device.p->CreateShaderResourceView(texture.p, nullptr, cpu);
128 std::uint32_t tsharp[8];
129 std::memcpy(tsharp, reinterpret_cast<const void*>(cpu.ptr), sizeof(tsharp));
130 leonida::gfx10::ImageWords tsharp_words{};
131 std::memcpy(tsharp_words.data(), tsharp, sizeof(tsharp_words));
132 EXPECT(leonida::gfx10::is_image(tsharp_words) && !leonida::gfx10::has_tsharp_index(tsharp_words));
133 tsharp[leonida::gfx10::kTsharpIndexDword] = 0x00C0FFEEu; // the title's own dword 6 (compression metadata)
134 rt::d3d12::set_tsharp_index_words_for_test(device.p, true);
135
105 put(0, raw_vsharp(arena_va, 256)); 136 put(0, raw_vsharp(arena_va, 256));
106 put(1, raw_vsharp(nobody, 256)); 137 put(1, raw_vsharp(nobody, 256));
107 put(2, raw_vsharp(mirrored, 256)); 138 put(2, raw_vsharp(mirrored, 256));
108 const std::uint32_t data[8] = {0x12345000u, 0x00007777u, 0x00000400u, 0x40000000u, 1, 2, 3, 4}; 139 const std::uint32_t data[8] = {0x12345000u, 0x00007777u, 0x00000400u, 0x40000000u, 1, 2, 3, 4};
109 std::memcpy(title + 3 * kDescriptor, data, sizeof(data)); 140 std::memcpy(title + 3 * kDescriptor, data, sizeof(data));
141 std::memcpy(title + 6 * kDescriptor, tsharp, sizeof(tsharp));
110 std::uint8_t written[5 * kDescriptor]; 142 std::uint8_t written[5 * kDescriptor];
111 std::memcpy(written, title, sizeof(written)); 143 std::memcpy(written, title, sizeof(written));
112 144
@@ -155,6 +187,18 @@ int test() {
155 EXPECT(rt::d3d12::page_mirror_write_back(device.p, std::uintptr_t(title), kPages * kPage64k) == 0); 187 EXPECT(rt::d3d12::page_mirror_write_back(device.p, std::uintptr_t(title), kPages * kPage64k) == 0);
156 for (unsigned i = 0; i < kDescriptor; ++i) EXPECT(title[5 * kDescriptor + i] == 0); 188 for (unsigned i = 0; i < kDescriptor; ++i) EXPECT(title[5 * kDescriptor + i] == 0);
157 189
190 // 5. The T#: dword 6 carries the tag and the texture's index, the other words as written; the title's dword 6 is
191 // its own.
192 std::uint32_t gpu_tsharp[8]{};
193 EXPECT(rt::d3d12::arena_gpu_read(device.p, shader_va + 6 * kDescriptor, gpu_tsharp, sizeof(gpu_tsharp)));
194 const std::uint32_t word = gpu_tsharp[leonida::gfx10::kTsharpIndexDword];
195 EXPECT((word >> 28) == leonida::gfx10::kTsharpIndexTag && (word & 0xFFFFu) != 0);
196 for (unsigned i = 0; i < 8; ++i)
197 if (i != leonida::gfx10::kTsharpIndexDword) EXPECT(gpu_tsharp[i] == tsharp[i]);
198 EXPECT(!std::memcmp(title + 6 * kDescriptor, tsharp, sizeof(tsharp)));
199 EXPECT(reinterpret_cast<const std::uint32_t*>(title + 6 * kDescriptor)[leonida::gfx10::kTsharpIndexDword] ==
200 0x00C0FFEEu);
201
158 // 3. The null slots after the heap. 202 // 3. The null slots after the heap.
159 std::uint32_t tail[64]{}; 203 std::uint32_t tail[64]{};
160 std::memset(tail, 0xff, sizeof(tail)); 204 std::memset(tail, 0xff, sizeof(tail));
@@ -162,8 +206,8 @@ int test() {
162 for (const std::uint32_t word : tail) EXPECT(word == 0); 206 for (const std::uint32_t word : tail) EXPECT(word == 0);
163 207
164 std::printf("heap in place: at heap_base + 0x%llx; the GPU reads a nobody's V# and a data word null and the others " 208 std::printf("heap in place: at heap_base + 0x%llx; the GPU reads a nobody's V# and a data word null and the others "
165 "as written, a rewrite at the next refresh, zeros after the heap; the title's bytes never change\n", 209 "as written, a rewrite at the next refresh, zeros after the heap, a T# with its index word (0x%08x); the title's bytes never change\n",
166 static_cast<unsigned long long>(shader_va)); 210 static_cast<unsigned long long>(shader_va), word);
167 heap.reset(); 211 heap.reset();
168 EXPECT(map(title, kPages, nullptr) == title && free_pages(kPages, pages)); 212 EXPECT(map(title, kPages, nullptr) == title && free_pages(kPages, pages));
169 return 0; 213 return 0;
diff --git a/runtime/test/d3d12_page_mirror_test.cpp b/runtime/test/d3d12_page_mirror_test.cpp
index 276528c4c..39a3461c9 100644
--- a/runtime/test/d3d12_page_mirror_test.cpp
+++ b/runtime/test/d3d12_page_mirror_test.cpp
@@ -12,7 +12,11 @@
12// keeps the title's address as its base, the GPU reads the bytes and a later title write there, and a binding of 12// keeps the title's address as its base, the GPU reads the bytes and a later title write there, and a binding of
13// it is served by the mirror's chunk; 13// it is served by the mirror's chunk;
14// 6. a slot-133 buffer over mirrored memory is the mirror's chunk (no shadow); the GPU's writes into it go back to 14// 6. a slot-133 buffer over mirrored memory is the mirror's chunk (no shadow); the GPU's writes into it go back to
15// the title's page, and a page written on both sides keeps the title's bytes. 15// the title's page, and a 256-byte piece written on both sides keeps the title's bytes;
16// 7. one page, the GPU writes piece A and the title piece B in the same submission window (the title's write is
17// uploaded before the GPU's goes back): both survive, on both sides;
18// 8. XMemAlloc blocks lie in the mirror's range and are mirrored as the heap commits them: the GPU reads a small and
19// a large block's bytes through a pointer into them that nothing named.
16// Exit 77 when the device makes no page mirror (no sparse aliased strict buffers or capture-replay addresses: llvmpipe). 20// Exit 77 when the device makes no page mirror (no sparse aliased strict buffers or capture-replay addresses: llvmpipe).
17// No shaders, no game data. 21// No shaders, no game data.
18#include "../shims/d3d12_com.h" 22#include "../shims/d3d12_com.h"
@@ -34,6 +38,8 @@
34namespace { 38namespace {
35 39
36using XMemVirtualAllocFn = void*(WINAPI*)(void*, SIZE_T, DWORD, ULONGLONG, DWORD); 40using XMemVirtualAllocFn = void*(WINAPI*)(void*, SIZE_T, DWORD, ULONGLONG, DWORD);
41using XMemAllocFn = void*(__stdcall*)(size_t, std::uint64_t);
42using XMemFreeFn = void(__stdcall*)(void*, std::uint64_t);
37using XMemAllocatePhysicalPagesFn = BOOL(WINAPI*)(std::uint64_t, std::uint64_t*, std::uint64_t*); 43using XMemAllocatePhysicalPagesFn = BOOL(WINAPI*)(std::uint64_t, std::uint64_t*, std::uint64_t*);
38using XMemFreePhysicalPagesFn = BOOL(WINAPI*)(std::uint64_t, const std::uint64_t*); 44using XMemFreePhysicalPagesFn = BOOL(WINAPI*)(std::uint64_t, const std::uint64_t*);
39using XMemMapPhysicalPagesFn = void*(WINAPI*)(void*, std::uint64_t, const std::uint64_t*); 45using XMemMapPhysicalPagesFn = void*(WINAPI*)(void*, std::uint64_t, const std::uint64_t*);
@@ -179,6 +185,38 @@ int test() {
179 EXPECT(placed_words[0x100] == 0x7171u); 185 EXPECT(placed_words[0x100] == 0x7171u);
180 EXPECT(gpu_word(device.p, std::uintptr_t(placed) + 0x400) == 0x7171u); 186 EXPECT(gpu_word(device.p, std::uintptr_t(placed) + 0x400) == 0x7171u);
181 187
188 // 7. Pieces A (0x800) and B (0xc00) of one page: the GPU writes A, the title B; a GPU read refreshes the mirror
189 // first (B is uploaded, A's home bytes stay), then A goes back to the title's page.
190 const std::uint32_t gpu_a[4] = {0xA0A00001u, 0xA0A00002u, 0xA0A00003u, 0xA0A00004u};
191 EXPECT(rt::d3d12::page_mirror_gpu_write(device.p, std::uintptr_t(placed) + 0x800, gpu_a, sizeof(gpu_a)));
192 std::thread([&] { placed_words[0x300] = 0xB0B00001u; }).join();
193 EXPECT(gpu_word(device.p, std::uintptr_t(placed) + 0xc00) == 0xB0B00001u);
194 EXPECT(gpu_word(device.p, std::uintptr_t(placed) + 0x800) == 0xA0A00001u);
195 EXPECT(rt::d3d12::page_mirror_write_back(device.p, std::uintptr_t(placed), kPage64k) == 256);
196 EXPECT(placed_words[0x200] == 0xA0A00001u && placed_words[0x203] == 0xA0A00004u);
197 EXPECT(placed_words[0x300] == 0xB0B00001u);
198 EXPECT(gpu_word(device.p, std::uintptr_t(placed) + 0x800) == 0xA0A00001u);
199 EXPECT(gpu_word(device.p, std::uintptr_t(placed) + 0xc00) == 0xB0B00001u);
200
201 // 8. XMemAlloc blocks.
202 auto xmem_alloc = reinterpret_cast<XMemAllocFn>(rt::shims::find("xmem.dll", "XMemAlloc"));
203 auto xmem_free = reinterpret_cast<XMemFreeFn>(rt::shims::find("xmem.dll", "XMemFree"));
204 EXPECT(xmem_alloc && xmem_free);
205 auto* heap_small = static_cast<volatile std::uint32_t*>(xmem_alloc(3000, 0x5e50000));
206 auto* heap_large = static_cast<volatile std::uint32_t*>(xmem_alloc(200000, 0));
207 EXPECT(heap_small && heap_large && std::uintptr_t(heap_small) % 64 == 0);
208 EXPECT(leonida::title_mirror_space::contains(std::uintptr_t(heap_small)) &&
209 leonida::title_mirror_space::contains(std::uintptr_t(heap_large)));
210 heap_small[700] = 0x81000700u;
211 heap_large[40000] = 0x82040000u;
212 EXPECT(gpu_word(device.p, std::uintptr_t(heap_small) + 2800) == 0x81000700u);
213 EXPECT(gpu_word(device.p, std::uintptr_t(heap_large) + 160000) == 0x82040000u);
214 std::thread([&] { heap_small[700] = 0x81000701u; }).join();
215 EXPECT(gpu_word(device.p, std::uintptr_t(heap_small) + 2800) == 0x81000701u);
216 xmem_free(const_cast<std::uint32_t*>(heap_small), 0);
217 xmem_free(const_cast<std::uint32_t*>(heap_large), 0);
218 EXPECT(gpu_word(device.p, std::uintptr_t(heap_large) + 160000) == 0); // decommitted: unmapped, reads zero
219
182 const auto end = rt::d3d12::page_mirror_state(device.p); 220 const auto end = rt::d3d12::page_mirror_state(device.p);
183 std::printf("page mirror: heap_base 0x%llx, %llu pages in %llu homes over %llu chunk(s); slot-31 copies, a title " 221 std::printf("page mirror: heap_base 0x%llx, %llu pages in %llu homes over %llu chunk(s); slot-31 copies, a title "
184 "write through its own view and a remap reach heap_base + the GPU-only address; an unmapped page reads " 222 "write through its own view and a remap reach heap_base + the GPU-only address; an unmapped page reads "
diff --git a/runtime/test/gfx10_descriptors_test.cpp b/runtime/test/gfx10_descriptors_test.cpp
index f30d7f026..b5278de8c 100644
--- a/runtime/test/gfx10_descriptors_test.cpp
+++ b/runtime/test/gfx10_descriptors_test.cpp
@@ -25,6 +25,26 @@ int main() {
25 // and TYPE (SQ_RSRC_IMG_2D = 9 at bits 31:28). 25 // and TYPE (SQ_RSRC_IMG_2D = 9 at bits 31:28).
26 const ImageWords plain = encode(Image{}); 26 const ImageWords plain = encode(Image{});
27 CHECK((plain == ImageWords{0, 0, 0, 0x90000FAC, 0, 0, 0, 0})); 27 CHECK((plain == ImageWords{0, 0, 0, 0x90000FAC, 0, 0, 0, 0}));
28
29 // The bindless index in dword 6 (tsharp_index_word): TAG 0xA [31:28], the storage kind bits 8..12 at [27:23], the
30 // sampled kind bits 0..6 at [22:16], the index at [15:0]; decoded back as the translator does, and stripped from the
31 // key. Index 0 and an index past 16 bits get no word, which every shader reads as the fallback.
32 {
33 const std::uint32_t kind = 0x1Fu << 8 | 0x7Fu; // every array
34 CHECK(tsharp_index_word(0x1234, kind) == 0xAFFF1234u);
35 CHECK(tsharp_index_word(7, 1u | 1u << 8) == 0xA0810007u);
36 CHECK(tsharp_index_word(0, kind) == 0 && tsharp_index_word(0x10000, kind) == 0);
37 ImageWords words = plain;
38 words[kTsharpIndexDword] = tsharp_index_word(9, 1u << 2 | 1u << 10);
39 CHECK(has_tsharp_index(words) && tsharp_index_of(words) == 9 && tsharp_kind_of(words) == (1u << 2 | 1u << 10));
40 CHECK(tsharp_key(words) == plain);
41 ImageWords no_image = words;
42 no_image[3] = 0x30000FAC; // TYPE 3: not an image, whatever dword 6 holds
43 CHECK(tsharp_index_of(no_image) == 0 && tsharp_kind_of(no_image) == 0);
44 ImageWords title = plain;
45 title[kTsharpIndexDword] = 0x1234; // a title's own dword 6 (no tag) stays in its key
46 CHECK(!has_tsharp_index(title) && tsharp_key(title) == title && tsharp_index_of(title) == 0);
47 }
28 // One field at a time: the bits that change, word by word. 48 // One field at a time: the bits that change, word by word.
29 const auto changed = [&](const Image& image) { 49 const auto changed = [&](const Image& image) {
30 ImageWords words = encode(image); 50 ImageWords words = encode(image);
diff --git a/runtime/test/shader_library_test.cpp b/runtime/test/shader_library_test.cpp
index f34c50024..06f105123 100644
--- a/runtime/test/shader_library_test.cpp
+++ b/runtime/test/shader_library_test.cpp
@@ -864,6 +864,32 @@ int main() {
864 std::filesystem::remove_all(dir); 864 std::filesystem::remove_all(dir);
865 } 865 }
866 866
867 // The T# index-word marker (`"tsharp_index": "dword6"`, TsharpIndexCensus): the modules that take a heap T#'s
868 // bindless index from its dword 6, which the device then writes into every heap, and the older ones (no key, or
869 // a value this runtime does not know), which look such T#s up in the hash table.
870 {
871 const auto root = dir / "tsharp_index";
872 const auto write_index = [](const std::filesystem::path& folder, const std::string& modules) {
873 std::filesystem::create_directories(folder);
874 std::ofstream index(folder / "index.json", std::ios::binary);
875 index << "{" << modules << "}";
876 };
877 const auto module = [](const char* name, const char* marker) {
878 std::string out = "{\"stage\": \"ps\", \"fssm_sha256\": \"" + std::string(name) + "\"";
879 if (marker) out += ", \"tsharp_index\": \"" + std::string(marker) + "\"";
880 return out + "}";
881 };
882 write_index(root, "\"a\": " + module("aa", "dword6") + ", \"b\": " + module("bb", nullptr) + ", \"c\": " +
883 module("cc", "dword7") + ", \"d\": " + module("dd", "dword6"));
884 ShaderLibrary mixed;
885 CHECK(mixed.load(root.string(), &error));
886 CHECK(mixed.tsharp_index_census().dword6 == 2 && mixed.tsharp_index_census().none == 2);
887 write_index(root, "\"a\": " + module("aa", nullptr));
888 CHECK(mixed.load(root.string(), &error)); // a reload replaces the census
889 CHECK(mixed.tsharp_index_census().dword6 == 0 && mixed.tsharp_index_census().none == 1);
890 std::filesystem::remove_all(root);
891 }
892
867 // The descriptor-table layout marker (`descriptor_table` in each module's meta, descriptor_table.h): absent is 893 // The descriptor-table layout marker (`descriptor_table` in each module's meta, descriptor_table.h): absent is
868 // the old plain layout. The kind word is additive - a tagged module reads it, a plain one ignores it and reads 894 // the old plain layout. The kind word is additive - a tagged module reads it, a plain one ignores it and reads
869 // the index at the same place - so one tagged module needs the tagged layout however many plain ones a merged or 895 // the index at the same place - so one tagged module needs the tagged layout however many plain ones a merged or
diff --git a/runtime/test/shaders/ps_table_fetch.asm b/runtime/test/shaders/ps_table_fetch.asm
index fad9cb9ee..c118c6fd9 100644
--- a/runtime/test/shaders/ps_table_fetch.asm
+++ b/runtime/test/shaders/ps_table_fetch.asm
@@ -1,6 +1,9 @@
1; vk_texture_test fetch-sint / fetch-uint / fetch-miss. Texel (0,0) holds bytes 1; vk_texture_test fetch-sint / fetch-uint / fetch-miss. Texel (0,0) holds bytes
2; 82 22 f8 4d: expect (-126,34,-8,77) or (130,34,248,77). A key mismatch 2; 82 22 f8 4d: expect (-126,34,-8,77) or (130,34,248,77). A key mismatch
3; fetches magenta UNORM at index zero. Convert raw integer words for RGBA32F output. 3; fetches magenta UNORM at index zero. Convert raw integer words for RGBA32F output.
4; s0 is a descriptor-table pointer (s1 = 0): the index comes from the T#'s dword 6 (docs/design.md, "Bindless index in
5; the T#"), and fetch-miss writes a dword 6 without the index tag, which must read index zero.
6s_mov_b32 s1, 0
4s_load_dwordx8 s[8:15], s[0:1], 0 7s_load_dwordx8 s[8:15], s[0:1], 0
5s_waitcnt lgkmcnt(0) 8s_waitcnt lgkmcnt(0)
6v_mov_b32_e32 v0, 0 9v_mov_b32_e32 v0, 0
diff --git a/runtime/test/shaders/ps_texture_sample.asm b/runtime/test/shaders/ps_texture_sample.asm
index 35e3c6ddb..e3851fde3 100644
--- a/runtime/test/shaders/ps_texture_sample.asm
+++ b/runtime/test/shaders/ps_texture_sample.asm
@@ -2,10 +2,13 @@
2; using normalized UV coordinates from attr0, outputs sampled color to mrt0. 2; using normalized UV coordinates from attr0, outputs sampled color to mrt0.
3; Run: vk_texture_test (autonomously, or with vs.spv fs.spv out.raw ptr_sgpr s0 s1 s2 s3) 3; Run: vk_texture_test (autonomously, or with vs.spv fs.spv out.raw ptr_sgpr s0 s1 s2 s3)
4; -> verifies center pixel = gradient color (0.5, 0.5, 0.5, 1.0) sampled via descriptor table 4; -> verifies center pixel = gradient color (0.5, 0.5, 0.5, 1.0) sampled via descriptor table
5; s[0:1] = 64-bit pointer to T# in GPU heap 5; s0 = descriptor-table pointer to the T# in the GPU heap, made a 32-bit pointer (s1 = 0) as the title's shaders do:
6; the shader takes the T#'s bindless index from its dword 6, with no hash-table lookup (docs/design.md, "Bindless
7; index in the T#"); vk_texture_test writes the index word there.
6; s[8:15] = 8-dword T# (image descriptor) 8; s[8:15] = 8-dword T# (image descriptor)
7; s[16:19] = 4-dword S# (sampler descriptor) 9; s[16:19] = 4-dword S# (sampler descriptor)
8; v[0:1] = barycentric UV coordinates 10; v[0:1] = barycentric UV coordinates
11s_mov_b32 s1, 0
9v_interp_p1_f32_e32 v2, v0, attr0.x 12v_interp_p1_f32_e32 v2, v0, attr0.x
10v_interp_p2_f32_e32 v2, v1, attr0.x 13v_interp_p2_f32_e32 v2, v1, attr0.x
11v_interp_p1_f32_e32 v3, v0, attr0.y 14v_interp_p1_f32_e32 v3, v0, attr0.y
diff --git a/runtime/test/title_heap_test.cpp b/runtime/test/title_heap_test.cpp
new file mode 100644
index 000000000..4eb9a08c7
--- /dev/null
+++ b/runtime/test/title_heap_test.cpp
@@ -0,0 +1,130 @@
1// src/title_heap.h: the XMemAlloc heap the runtime keeps in the page mirror's range. No Windows headers, no GPU, no
2// game data: the "reservation" is host memory here, and commit and decommit are counted.
3// 1. blocks are 64-byte aligned, a size of zero is one byte, sizes fall in their class, large blocks are whole pages;
4// 2. a randomised run of allocations and frees against a reference (a map of live blocks with their bytes): no two
5// live blocks overlap, every block keeps what was written into it until it is freed, frees give space back;
6// 3. a large block is committed when handed out and decommitted when freed; pointers the heap did not hand out are
7// refused.
8#include "../src/title_heap.h"
9
10#include <cstdio>
11#include <cstdlib>
12#include <cstring>
13#include <map>
14#include <random>
15#include <vector>
16
17namespace {
18
19int failures = 0;
20#define EXPECT(condition) \
21 do { \
22 if (!(condition)) { \
23 std::fprintf(stderr, "FAIL line %d: %s\n", __LINE__, #condition); \
24 ++failures; \
25 } \
26 } while (0)
27
28using leonida::TitleHeap;
29
30} // namespace
31
32int main() {
33 constexpr std::size_t kBytes = std::size_t(256) << 20;
34 std::vector<std::uint8_t> memory(kBytes + TitleHeap::kPage);
35 const std::uintptr_t base =
36 (reinterpret_cast<std::uintptr_t>(memory.data()) + TitleHeap::kPage - 1) & ~std::uintptr_t(TitleHeap::kPage - 1);
37 std::size_t committed = 0, decommitted = 0;
38 TitleHeap heap;
39 TitleHeap::Hooks hooks;
40 hooks.commit = [&](std::uintptr_t, std::size_t bytes) {
41 committed += bytes;
42 return true;
43 };
44 hooks.decommit = [&](std::uintptr_t at, std::size_t bytes) {
45 decommitted += bytes;
46 std::memset(reinterpret_cast<void*>(at), 0, bytes); // as a decommit reads back
47 };
48 EXPECT(heap.init(base, kBytes, hooks));
49
50 // 1.
51 void* zero = heap.allocate(0);
52 EXPECT(zero && reinterpret_cast<std::uintptr_t>(zero) % 64 == 0 && heap.size_of(zero) == 64);
53 for (std::size_t size : {1u, 63u, 64u, 65u, 1000u, 1024u, 1025u, 4096u, 30000u, 32768u}) {
54 void* p = heap.allocate(size);
55 EXPECT(p && reinterpret_cast<std::uintptr_t>(p) % 64 == 0 && heap.size_of(p) >= size && heap.owns(p));
56 EXPECT(heap.release(p));
57 }
58 void* large = heap.allocate(100000);
59 EXPECT(large && reinterpret_cast<std::uintptr_t>(large) % TitleHeap::kPage == 0 &&
60 heap.size_of(large) == 2 * TitleHeap::kPage);
61 // 3.
62 const std::size_t before = decommitted;
63 std::memset(large, 0x5a, 100000);
64 EXPECT(heap.release(large) && decommitted == before + 2 * TitleHeap::kPage);
65 void* again = heap.allocate(100000);
66 EXPECT(again && static_cast<std::uint8_t*>(again)[0] == 0); // reads zero handed out again
67 EXPECT(heap.release(again));
68 int outside = 0;
69 EXPECT(!heap.release(&outside) && !heap.owns(&outside));
70 EXPECT(!heap.release(static_cast<std::uint8_t*>(zero) + 8)); // not a block's start
71 EXPECT(heap.release(zero));
72
73 // 2.
74 std::mt19937 random(2026);
75 struct Live {
76 std::size_t size;
77 std::uint8_t tag;
78 };
79 std::map<std::uintptr_t, Live> live;
80 const auto check_block = [&](std::uintptr_t at, const Live& b) {
81 const auto* bytes = reinterpret_cast<const std::uint8_t*>(at);
82 for (std::size_t i = 0; i < b.size; i += 97)
83 if (bytes[i] != std::uint8_t(b.tag + i)) return false;
84 return true;
85 };
86 for (int round = 0; round < 20000; ++round) {
87 const bool free_one = !live.empty() && (random() % 100 < 45 || live.size() > 3000);
88 if (free_one) {
89 auto it = live.begin();
90 std::advance(it, random() % live.size());
91 EXPECT(check_block(it->first, it->second));
92 EXPECT(heap.release(reinterpret_cast<void*>(it->first)));
93 live.erase(it);
94 continue;
95 }
96 const unsigned kind = random() % 100;
97 const std::size_t size = kind < 70 ? random() % 512 : kind < 95 ? random() % 32768 : 32769 + random() % 300000;
98 void* p = heap.allocate(size);
99 EXPECT(p != nullptr);
100 if (!p) break;
101 const auto at = reinterpret_cast<std::uintptr_t>(p);
102 EXPECT(at % 64 == 0 && heap.owns(p));
103 const std::size_t span = size ? size : 1;
104 // No live block overlaps it.
105 auto next = live.lower_bound(at);
106 if (next != live.end()) EXPECT(at + span <= next->first);
107 if (next != live.begin()) {
108 const auto previous = std::prev(next);
109 EXPECT(previous->first + previous->second.size <= at);
110 }
111 const Live b{span, std::uint8_t(random())};
112 auto* bytes = static_cast<std::uint8_t*>(p);
113 for (std::size_t i = 0; i < span; i += 97) bytes[i] = std::uint8_t(b.tag + i);
114 live[at] = b;
115 }
116 for (const auto& [at, b] : live) {
117 EXPECT(check_block(at, b));
118 EXPECT(heap.release(reinterpret_cast<void*>(at)));
119 }
120 EXPECT(heap.stats().live == 0 && committed > 0);
121
122 if (failures) {
123 std::fprintf(stderr, "title_heap_test: %d failure(s)\n", failures);
124 return 1;
125 }
126 std::printf("title_heap_test: alignment, classes, large blocks, 20000 random allocations and frees against a "
127 "reference (%zu KiB committed, %zu KiB decommitted)\n",
128 committed >> 10, decommitted >> 10);
129 return 0;
130}
diff --git a/runtime/test/title_mirror_hooks_test.cpp b/runtime/test/title_mirror_hooks_test.cpp
index e38bb49a3..c3a2238a1 100644
--- a/runtime/test/title_mirror_hooks_test.cpp
+++ b/runtime/test/title_mirror_hooks_test.cpp
@@ -139,10 +139,26 @@ int filters() {
139 EXPECT(f.filtered.size() == 1 && f.filtered[0].va == kBase && f.filtered[0].fresh); 139 EXPECT(f.filtered.size() == 1 && f.filtered[0].va == kBase && f.filtered[0].fresh);
140 EXPECT(mirror.home_bytes(kBase)[100] == 0x5A && mirror.home_bytes(kBase + 2 * kPage)[100] == 0xA5); 140 EXPECT(mirror.home_bytes(kBase)[100] == 0x5A && mirror.home_bytes(kBase + 2 * kPage)[100] == 0xA5);
141 EXPECT(mirror.counters().filtered == 1 && mirror.counters().uploads == 2); 141 EXPECT(mirror.counters().filtered == 1 && mirror.counters().uploads == 2);
142 // Write-back: a filtered home differs from the title's page by the filter's bytes and is never written back; a
143 // copied home the GPU wrote is.
144 std::size_t written = 0;
145 const auto count_writes = [&](std::uint64_t va, const std::uint8_t* bytes, std::uint64_t n) {
146 if (va < kBase + 2 * kPage) return false; // the copied page only (a write elsewhere fails the counts)
147 std::memcpy(&frames[std::size_t(va - kBase)], bytes, std::size_t(n));
148 written += std::size_t(n);
149 return true;
150 };
151 EXPECT(mirror.write_back(kBase, kBase + kPage, count_writes) == 0 && written == 0);
152 mirror.home_bytes(kBase + 2 * kPage)[300] = 0x77; // a GPU store into the copied page
153 EXPECT(mirror.write_back(kBase + 2 * kPage, kBase + 3 * kPage, count_writes) == 256 && written == 256);
154 mirror.home_bytes(kBase + 2 * kPage)[300] = 0xA5; // as it was, for the cases below
155 EXPECT(mirror.write_back(kBase + 2 * kPage, kBase + 3 * kPage, count_writes) == 256);
142 // A write and its refill: through the filter, not fresh. 156 // A write and its refill: through the filter, not fresh.
143 frames[200] = 0x11; 157 frames[200] = 0x11;
144 EXPECT(mirror.dirty(kBase) && mirror.upload() == 1); 158 EXPECT(mirror.dirty(kBase) && mirror.upload() == 1);
145 EXPECT(f.filtered.size() == 2 && !f.filtered[1].fresh && mirror.home_bytes(kBase)[200] == 0x11); 159 EXPECT(f.filtered.size() == 2 && !f.filtered[1].fresh && mirror.home_bytes(kBase)[200] == 0x11);
160 // The upload compares the title's bytes with the title's: the same title bytes again fill nothing.
161 EXPECT(mirror.dirty(kBase) && mirror.upload() == 1 && f.filtered.size() == 2);
146 // The same physical page shown at a second, unfiltered address: one home, still filtered. 162 // The same physical page shown at a second, unfiltered address: one home, still filtered.
147 mirror.map(kBase + 5 * kPage, &frames[0], nullptr, 2); 163 mirror.map(kBase + 5 * kPage, &frames[0], nullptr, 2);
148 EXPECT(mirror.home_bytes(kBase + 5 * kPage) == mirror.home_bytes(kBase) && mirror.home_bytes(kBase + 5 * kPage)[0] == 0x5A); 164 EXPECT(mirror.home_bytes(kBase + 5 * kPage) == mirror.home_bytes(kBase) && mirror.home_bytes(kBase + 5 * kPage)[0] == 0x5A);
diff --git a/runtime/test/vk_texture_test.cpp b/runtime/test/vk_texture_test.cpp
index 97e93cb04..df0177bb3 100644
--- a/runtime/test/vk_texture_test.cpp
+++ b/runtime/test/vk_texture_test.cpp
@@ -151,8 +151,14 @@ int main(int argc, char** argv) {
151 const VkFormat sampled_format = dref ? VK_FORMAT_D32_SFLOAT : 151 const VkFormat sampled_format = dref ? VK_FORMAT_D32_SFLOAT :
152 (uint_mips || fetch_uint) ? VK_FORMAT_R8G8B8A8_UINT : 152 (uint_mips || fetch_uint) ? VK_FORMAT_R8G8B8A8_UINT :
153 (signed_mips || fetch) ? VK_FORMAT_R8G8B8A8_SINT : VK_FORMAT_R8G8B8A8_UNORM; 153 (signed_mips || fetch) ? VK_FORMAT_R8G8B8A8_SINT : VK_FORMAT_R8G8B8A8_UNORM;
154 uint32_t tsharp[8] = {0x11111111, leonida::gfx10::format_from_vulkan(sampled_format) << 20, 0x33333333, 0x44440444, 154 // The shaders load the T# through a descriptor-table pointer (s[ptr_sgpr], high dword 0), so they take its index
155 0x55555555, 0x66666666, 0x77777777, 0x88888888}; 155 // from dword 6 as the layer writes it (gfx10_descriptors.h, tsharp_index_word; docs/design.md, "Bindless index in
156 // the T#"): index 1, bound in both sampled arrays they read (see the table insert below). Word 3's TYPE is 9 (2D):
157 // a word without the tag, or a dword 3 that names no image, reads the fallback.
158 const uint32_t index_word = leonida::gfx10::tsharp_index_word(1, leonida::kind_sampled_bit(0) |
159 leonida::kind_sampled_bit(1));
160 uint32_t tsharp[8] = {0x11111111, leonida::gfx10::format_from_vulkan(sampled_format) << 20, 0x33333333, 0x94440444,
161 0x55555555, 0x66666666, index_word, 0x88888888};
156 const uint32_t tsharp_va = 256; 162 const uint32_t tsharp_va = 256;
157 163
158 gipa = load_vulkan(); 164 gipa = load_vulkan();
@@ -318,7 +324,13 @@ int main(int argc, char** argv) {
318 const VkDeviceSize heap_bytes = heap_mb && std::atoi(heap_mb) > 0 ? VkDeviceSize(std::atoi(heap_mb)) << 20 : 65536; 324 const VkDeviceSize heap_bytes = heap_mb && std::atoi(heap_mb) > 0 ? VkDeviceSize(std::atoi(heap_mb)) << 20 : 65536;
319 CHECK(make_buffer(heap_bytes, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT, &heap, &heapm, &heapp)); 325 CHECK(make_buffer(heap_bytes, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT, &heap, &heapm, &heapp));
320 std::memset(heapp, 0, size_t(heap_bytes)); 326 std::memset(heapp, 0, size_t(heap_bytes));
321 std::memcpy(static_cast<char*>(heapp) + tsharp_va, tsharp, 32); 327 {
328 // The miss control: a T# whose dword 6 carries no index (the title's own word) reads the fallback.
329 uint32_t in_heap[8];
330 std::memcpy(in_heap, tsharp, sizeof(in_heap));
331 if (fetch_miss) in_heap[leonida::gfx10::kTsharpIndexDword] = 0x77777777;
332 std::memcpy(static_cast<char*>(heapp) + tsharp_va, in_heap, 32);
333 }
322 if (two_mip) // The gather test loads its S# from the four words just after the T#. 334 if (two_mip) // The gather test loads its S# from the four words just after the T#.
323 std::memcpy(static_cast<char*>(heapp) + tsharp_va + 32, ssharp, 16); 335 std::memcpy(static_cast<char*>(heapp) + tsharp_va + 32, ssharp, 16);
324 VkBufferDeviceAddressInfo bdai{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; bdai.buffer = heap; 336 VkBufferDeviceAddressInfo bdai{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; bdai.buffer = heap;
diff --git a/tests/semantic/fixtures/disasm/ps_tsharp_index_word.s b/tests/semantic/fixtures/disasm/ps_tsharp_index_word.s
new file mode 100644
index 000000000..f7424ce24
--- /dev/null
+++ b/tests/semantic/fixtures/disasm/ps_tsharp_index_word.s
@@ -0,0 +1,25 @@
1; ps_tsharp_index_word hand-written test program (llvm-mc -mcpu=gfx1030 -show-encoding; no game data)
2 s_mov_b32 s1, 0 ; encoding: [0x80,0x03,0x81,0xbe]
3 s_load_dwordx8 s[8:15], s[0:1], 0x20 ; encoding: [0x00,0x02,0x0c,0xf4,0x20,0x00,0x00,0xfa]
4 s_movk_i32 s16, 0x92 ; encoding: [0x92,0x00,0x10,0xb0]
5 s_mov_b32 s17, 0xc00000 ; encoding: [0xff,0x03,0x91,0xbe,0x00,0x00,0xc0,0x00]
6 s_mov_b32 s18, 0x14500000 ; encoding: [0xff,0x03,0x92,0xbe,0x00,0x00,0x50,0x14]
7 s_mov_b32 s19, 0 ; encoding: [0x80,0x03,0x93,0xbe]
8 s_cmp_eq_u32 s2, 0 ; encoding: [0x02,0x80,0x06,0xbf]
9 s_cbranch_scc1 3 ; encoding: [0x03,0x00,0x85,0xbf]
10 s_load_dwordx8 s[20:27], s[0:1], 0x40 ; encoding: [0x00,0x05,0x0c,0xf4,0x40,0x00,0x00,0xfa]
11 s_branch 2 ; encoding: [0x02,0x00,0x82,0xbf]
12 s_load_dwordx8 s[20:27], s[0:1], 0x60 ; encoding: [0x00,0x05,0x0c,0xf4,0x60,0x00,0x00,0xfa]
13 s_waitcnt lgkmcnt(0) ; encoding: [0x7f,0xc0,0x8c,0xbf]
14 v_mov_b32_e32 v8, 0.5 ; encoding: [0xf0,0x02,0x10,0x7e]
15 v_mov_b32_e32 v9, 0.5 ; encoding: [0xf0,0x02,0x12,0x7e]
16 image_sample_lz v[0:3], v[8:9], s[8:15], s[16:19] dmask:0xf dim:SQ_RSRC_IMG_2D ; encoding: [0x08,0x0f,0x9c,0xf0,0x08,0x00,0x82,0x00]
17 image_sample_lz v[4:7], v[8:9], s[20:27], s[16:19] dmask:0xf dim:SQ_RSRC_IMG_2D ; encoding: [0x08,0x0f,0x9c,0xf0,0x08,0x04,0x85,0x00]
18 s_load_dwordx8 s[28:35], s[4:5], 0x0 ; encoding: [0x02,0x07,0x0c,0xf4,0x00,0x00,0x00,0xfa]
19 s_waitcnt lgkmcnt(0) ; encoding: [0x7f,0xc0,0x8c,0xbf]
20 image_sample_lz v[10:13], v[8:9], s[28:35], s[16:19] dmask:0xf dim:SQ_RSRC_IMG_2D ; encoding: [0x08,0x0f,0x9c,0xf0,0x08,0x0a,0x87,0x00]
21 s_waitcnt vmcnt(0) ; encoding: [0x70,0x3f,0x8c,0xbf]
22 v_add_f32_e32 v0, v0, v4 ; encoding: [0x00,0x09,0x00,0x06]
23 v_add_f32_e32 v1, v1, v10 ; encoding: [0x01,0x15,0x02,0x06]
24 exp mrt0, v0, v1, v2, v3 done vm ; encoding: [0x0f,0x18,0x00,0xf8,0x00,0x01,0x02,0x03]
25 s_endpgm ; encoding: [0x00,0x00,0x81,0xbf]
diff --git a/tests/semantic/test_sampled_dynamic_index.py b/tests/semantic/test_sampled_dynamic_index.py
index afc796390..2d8ebf838 100644
--- a/tests/semantic/test_sampled_dynamic_index.py
+++ b/tests/semantic/test_sampled_dynamic_index.py
@@ -62,6 +62,11 @@ class SampledDynamicIndex(unittest.TestCase):
62 more |= {res for res, true_value, false_value in re.findall( 62 more |= {res for res, true_value, false_value in re.findall(
63 r"(%\w+) = OpSelect %uint %\w+ (%\w+) (%\w+)", asm) 63 r"(%\w+) = OpSelect %uint %\w+ (%\w+) (%\w+)", asm)
64 if true_value in lookup_indices and false_value == "%c0"} 64 if true_value in lookup_indices and false_value == "%c0"}
65 # These T#s come from user SGPRs, not a heap slot, so they are looked up, and the index word of their
66 # dword 6 wins where it carries the tag (docs/design.md, "Bindless index in the T#"): an OpPhi of the
67 # word and the lookup's index, which runs only without the word.
68 more |= {res for res, probed in re.findall(
69 r"(%\w+) = OpPhi %uint %\w+ %\w+ (%\w+) %\w+", asm) if probed in lookup_indices}
65 if more <= lookup_indices: 70 if more <= lookup_indices:
66 break 71 break
67 lookup_indices |= more 72 lookup_indices |= more
diff --git a/tests/semantic/test_tsharp_index_word.py b/tests/semantic/test_tsharp_index_word.py
new file mode 100644
index 000000000..412b54ed5
--- /dev/null
+++ b/tests/semantic/test_tsharp_index_word.py
@@ -0,0 +1,189 @@
1"""The bindless index in the T# (docs/design.md, "Bindless index in the T#").
2
3A T# whose dword 6 the dataflow (tools/descriptor_sources.py) traces to a heap slot takes its index from that word:
4TAG [31:28] | storage kind [27:23] | sampled kind [22:16] | index [15:0], which the layer writes into every heap
5shaders read (runtime/src/gfx10_descriptors.h, tsharp_index_word). No hash-table lookup is emitted for it. A T# from
6anywhere else keeps the lookup, and its dword-6 index wins when the word carries the tag. The fixture
7fixtures/disasm/ps_tsharp_index_word.s has both, and a T# loaded in either arm of a branch.
8"""
9import os
10import re
11import struct
12import sys
13import tempfile
14import unittest
15
16HERE = os.path.dirname(os.path.abspath(__file__))
17sys.dont_write_bytecode = True
18sys.path.insert(0, HERE)
19
20import support # noqa: E402
21import spirv_mini_interp as si # noqa: E402
22import rdna2spirv # noqa: E402
23import descriptor_sources # noqa: E402
24import shader_ir # noqa: E402
25
26HEADER = os.path.join(support.ROOT, "runtime", "src", "gfx10_descriptors.h")
27LOOKUP = re.compile(r"OpFunctionCall %\w+ %desc_lookup_fn ")
28SAMPLED_2D = 1 << 16 # kind bit 0 (the 2D sampled array) in the word
29SAMPLED_3D = 1 << (16 + 2) # kind bit 2 (the 3D sampled array)
30TEXELS = {0: (0.0, 0.0, 0.0, 0.0), 2: (0.25, 0.5, 0.75, 1.0), 5: (1.0, 0.75, 0.5, 0.25)}
31EPILOGUE = ["s_waitcnt vmcnt(0)", "exp mrt0 v4, v5, v6, v7 done vm", "s_endpgm"]
32
33
34def fbits(value):
35 return struct.unpack("<I", struct.pack("<f", value))[0]
36
37
38def word(index, kind=SAMPLED_2D, tag=0xA):
39 return (tag << 28) | kind | index
40
41
42def tsharp(index_word, word3=0x90000000):
43 """A 2D T# (TYPE 9 in dword 3, a float format in dword 1) with `index_word` in dword 6."""
44 return [0x11110000, 0, 0x22220000, word3, 0x33330000, 0x44440000, index_word, 0x55550000]
45
46
47def load_program(pointer_high):
48 """image_load through a T# loaded at s[0:1] + 0x20; `pointer_high` is how s1 is made."""
49 return support.translate_lines("ps_tsharp_index", [
50 *pointer_high,
51 "s_load_dwordx8 s[8:15], s[0:1], 0x20",
52 "s_waitcnt lgkmcnt(0)",
53 "v_mov_b32_e32 v2, 0",
54 "v_mov_b32_e32 v3, 0",
55 "image_load v[4:7], v[2:3], s[8:15] dmask:0xf dim:SQ_RSRC_IMG_2D unorm",
56 *EPILOGUE,
57 ])
58
59
60def run(spv, words, desc_map=None, base=0x1000):
61 memory = {base + 0x20 + 4 * i: w for i, w in enumerate(words)}
62 images = [(lambda coord, lod, t=TEXELS.get(k, (9.0,) * 4): t) for k in range(8)]
63 # The module declares the table either way; without `desc_map` it is empty, so a lookup would fail to read it.
64 resources = {"%images": images, "%desc_map": [] if desc_map is None else desc_map}
65 _, outputs = si.run_workgroup(spv, 32, 32, inputs_for=lambda i: {"%sg_lane": i}, return_outputs=True,
66 push_constants=[base, 0, 0, 0, 0x2000, 0], memory=memory, resources=resources)
67 return outputs[0]["%out_mrt0"]
68
69
70def expected(index):
71 return tuple(fbits(c) for c in TEXELS[index])
72
73
74class TsharpIndexWord(unittest.TestCase):
75 def test_constants_match_the_runtime(self):
76 text = open(HEADER, encoding="utf-8").read()
77 self.assertIn(f"kTsharpIndexDword = {rdna2spirv.TSHARP_INDEX_DWORD};", text)
78 self.assertIn(f"kTsharpIndexTag = 0x{rdna2spirv.TSHARP_INDEX_TAG:X};", text)
79 self.assertEqual(descriptor_sources.INDEX_DWORD, rdna2spirv.TSHARP_INDEX_DWORD)
80 # The bit layout the shader decodes, as tsharp_index_word writes it.
81 self.assertIn("(kTsharpIndexTag << 28) | (((kind >> 8) & 0x1Fu) << 23) | ((kind & 0x7Fu) << 16) | index",
82 text)
83
84 def test_heap_tsharp_reads_dword6_without_a_lookup(self):
85 spv = load_program(["s_mov_b32 s1, 0"])
86 self.assertIsNone(LOOKUP.search(spv))
87 # No %desc_map is bound: a lookup would raise. The word's index picks the image.
88 self.assertEqual(run(spv, tsharp(word(2))), expected(2))
89 self.assertEqual(run(spv, tsharp(word(5))), expected(5))
90
91 def test_untagged_word_wrong_array_or_no_image_read_the_fallback(self):
92 spv = load_program(["s_mov_b32 s1, 0"])
93 for name, words in (("no tag", tsharp(word(2, tag=0x1))),
94 ("3D index for a 2D load", tsharp(word(2, kind=SAMPLED_3D))),
95 ("dword 3 names no image", tsharp(word(2), word3=0x30000000)),
96 ("zero slot", [0] * 8)):
97 with self.subTest(name):
98 self.assertEqual(run(spv, words), expected(0))
99
100 def test_tsharp_of_unknown_source_keeps_the_lookup_and_prefers_the_word(self):
101 spv = load_program([]) # s[0:1] is a 64-bit pointer: not a descriptor-table pointer
102 self.assertIsNotNone(LOOKUP.search(spv))
103 untagged = tsharp(5)
104 desc_map = [0, *untagged, 5, 0x80000001] # mask 0: one slot, holding the T#'s words -> index 5, 2D
105 self.assertEqual(run(spv, untagged, desc_map), expected(5))
106 # Tagged: the word wins over the table (whose key no longer matches anyway).
107 self.assertEqual(run(spv, tsharp(word(2)), desc_map), expected(2))
108
109 def test_branches_and_the_module_meta(self):
110 spv = support.translate_fixture("ps_tsharp_index_word")
111 gen = rdna2spirv.translate.last_gen
112 self.assertEqual(gen.tsharp_index_reads, 2) # +0x20, and +0x40 / +0x60 joined after the branch
113 self.assertEqual(gen.tsharp_lookups, 1) # the T# from the 64-bit pointer s[4:5]
114 self.assertEqual(len(LOOKUP.findall(spv)), 2) # that T#, and the literal S# (all three samples share it)
115 meta = rdna2spirv.shader_meta(gen, spv)
116 self.assertEqual(meta["tsharp_index"], "dword6")
117 self.assertEqual((meta["tsharp_index_reads"], meta["tsharp_lookups"]), (2, 1))
118
119
120def verdicts(lines, user=32):
121 text = "; t hand-written\n" + "".join("\t" + ln + "\n" for ln in lines)
122 with tempfile.TemporaryDirectory() as tmp:
123 path = os.path.join(tmp, "t.s")
124 with open(path, "w", encoding="utf-8", newline="\n") as f:
125 f.write(text)
126 insns = shader_ir.parse_file(path)["insns"]
127 out = descriptor_sources.analyse([insns], [[]], user)
128 return [out[id(i)] for i in insns if i["op"].startswith("image_")]
129
130
131class DescriptorSources(unittest.TestCase):
132 SAMPLE = "image_load v[0:3], v[4:5], s[8:15] dmask:0xf dim:SQ_RSRC_IMG_2D unorm"
133
134 def test_table_pointer_static_and_dynamic_offsets(self):
135 self.assertEqual(verdicts(["s_mov_b32 s1, 0", "s_load_dwordx8 s[8:15], s[0:1], 0x40", self.SAMPLE]), [True])
136 self.assertEqual(verdicts(["s_mov_b32 s1, 0", "s_lshl_b32 s20, s3, 5",
137 "s_load_dwordx8 s[8:15], s[0:1], s20", self.SAMPLE]), [True])
138
139 def test_a_slot_read_in_two_halves(self):
140 # Dwords 4..7 from offset 0x10: dword 6 is the load's dword 2, at byte 24 of the slot.
141 self.assertEqual(verdicts(["s_mov_b32 s1, 0", "s_load_dwordx4 s[8:11], s[0:1], 0x0",
142 "s_load_dwordx4 s[12:15], s[0:1], 0x10", self.SAMPLE]), [True])
143 # The same registers from offset 0x20 and 0x30 + 8: dword 6 lands at byte 8 of a slot.
144 self.assertEqual(verdicts(["s_mov_b32 s1, 0", "s_load_dwordx4 s[8:11], s[0:1], 0x20",
145 "s_load_dwordx4 s[12:15], s[0:1], 0x38", self.SAMPLE]), [False])
146
147 def test_a_table_pointer_spilled_to_vgpr_lanes(self):
148 # A compiler parks SGPRs in VGPR lanes; the pointer read back is still the table pointer.
149 spill = ["s_mov_b32 s1, 0", "v_writelane_b32 v63, s0, 10", "v_writelane_b32 v63, s1, 11",
150 "v_writelane_b32 v63, vcc_hi, 12", "v_readlane_b32 vcc_lo, v63, 12"]
151 back = ["v_readlane_b32 s20, v63, 10", "v_readlane_b32 s21, v63, 11",
152 "s_load_dwordx8 s[8:15], s[20:21], 0x40", self.SAMPLE]
153 self.assertEqual(verdicts(spill + back), [True])
154 # Anything else that names the VGPR, or a lane written again, forgets what the lanes held.
155 self.assertEqual(verdicts(spill + ["v_mov_b32_e32 v63, 0"] + back), [False])
156 self.assertEqual(verdicts(spill + ["s_load_dword s40, s[2:3], 0x0", "v_writelane_b32 v63, s40, 10"] + back),
157 [False])
158
159 def test_a_tsharp_loaded_into_vcc(self):
160 # Short of SGPRs, a compiler loads a T#'s last two dwords into VCC; dword 6 is then vcc_lo.
161 load = ["s_mov_b32 s1, 0", "s_load_dwordx8 [s100,s101,s102,s103,s104,s105,vcc_lo,vcc_hi], s[0:1], 0x40",
162 "v_mov_b32_e32 v8, 1.0"]
163 use = "image_sample_lz v[0:3], v[4:5], [s100,s101,s102,s103,s104,s105,vcc_lo,vcc_hi], s[16:19] " \
164 "dmask:0xf dim:SQ_RSRC_IMG_2D"
165 self.assertEqual(verdicts(load + [use]), [True])
166 # An instruction that writes VCC (printed: VOPC and carry instructions name it) forgets what it held.
167 self.assertEqual(verdicts(load + ["v_cmp_lt_f32_e32 vcc_lo, v0, v1", use]), [False])
168 # A pointer parked in VCC and copied back is still the table pointer.
169 self.assertEqual(verdicts(["s_mov_b32 s1, 0", "v_writelane_b32 v63, s0, 10", "v_writelane_b32 v63, s1, 11",
170 "v_readlane_b32 vcc_lo, v63, 10", "v_readlane_b32 vcc_hi, v63, 11",
171 "s_mov_b64 s[20:21], vcc", "s_load_dwordx8 s[8:15], s[20:21], 0x40", self.SAMPLE]),
172 [True])
173
174 def test_other_sources_keep_the_lookup(self):
175 for name, lines in (
176 ("64-bit pointer", ["s_load_dwordx8 s[8:15], s[0:1], 0x0"]),
177 ("system SGPR", ["s_mov_b32 s41, 0", "s_load_dwordx8 s[8:15], s[40:41], 0x0"]),
178 ("loaded pointer", ["s_mov_b32 s1, 0", "s_load_dword s20, s[0:1], 0x0", "s_mov_b32 s21, 0",
179 "s_load_dwordx8 s[8:15], s[20:21], 0x0"]),
180 ("constant buffer", ["s_buffer_load_dwordx8 s[8:15], s[0:3], 0x0"]),
181 ("edited dword 6", ["s_mov_b32 s1, 0", "s_load_dwordx8 s[8:15], s[0:1], 0x0",
182 "s_or_b32 s14, s14, 1"]),
183 ("literal", [f"s_mov_b32 s{r}, 0" for r in range(8, 16)])):
184 with self.subTest(name):
185 self.assertEqual(verdicts(lines + [self.SAMPLE], user=40 if name == "system SGPR" else 32), [False])
186
187
188if __name__ == "__main__":
189 unittest.main()
diff --git a/tests/test_desc_cache.py b/tests/test_desc_cache.py
index 584d9a94c..c0b5cb88c 100644
--- a/tests/test_desc_cache.py
+++ b/tests/test_desc_cache.py
@@ -235,11 +235,16 @@ def test_lookup_result_is_broadcast_before_use():
235 bcast[ln.split()[0]] = ln.split()[-2] 235 bcast[ln.split()[0]] = ln.split()[-2]
236 extracts = {ln.split()[0]: ln.split()[-2] for ln in lines 236 extracts = {ln.split()[0]: ln.split()[-2] for ln in lines
237 if "OpCompositeExtract %uint" in ln and ln.split()[-2] in results} 237 if "OpCompositeExtract %uint" in ln and ln.split()[-2] in results}
238 # The T# here is in user SGPRs, no heap slot, so it is looked up, and the index word in its dword 6 is preferred
239 # where it carries the tag (docs/design.md, "Bindless index in the T#"): an OpPhi of the word and the extract,
240 # the lookup running only without the word (OpPhi %uint word pre lookup probe).
241 selects = {ln.split()[0]: ln.split()[-2] for ln in lines
242 if "OpPhi %uint" in ln and ln.split()[-2] in extracts}
238 # A tagged entry returns (index, kind): each component is broadcast before use, so a broadcast reads the 243 # A tagged entry returns (index, kind): each component is broadcast before use, so a broadcast reads the
239 # call or an extract of it. 244 # call, an extract of it, or that phi.
240 assert results and bcast, (results, bcast) 245 assert results and bcast, (results, bcast)
241 assert all(src in results or extracts.get(src) in results for src in bcast.values()), \ 246 assert all(src in results or extracts.get(src) in results or extracts.get(selects.get(src)) in results
242 (results, extracts, bcast) 247 for src in bcast.values()), (results, extracts, selects, bcast)
243 assert "OpCapability GroupNonUniform" in lines 248 assert "OpCapability GroupNonUniform" in lines
244 assert "OpCapability GroupNonUniformBallot" in lines or "OpCapability GroupNonUniformShuffle" in lines 249 assert "OpCapability GroupNonUniformBallot" in lines or "OpCapability GroupNonUniformShuffle" in lines
245 for ln in lines: 250 for ln in lines:
diff --git a/tests/test_image_load_typed.py b/tests/test_image_load_typed.py
index a57eaa8e6..fb1843834 100644
--- a/tests/test_image_load_typed.py
+++ b/tests/test_image_load_typed.py
@@ -127,12 +127,20 @@ class Module:
127 return regs[p[1], r] 127 return regs[p[1], r]
128 if p[1] == "%vgpr" and self.vgprs is not None: 128 if p[1] == "%vgpr" and self.vgprs is not None:
129 return self.vgprs[r] 129 return self.vgprs[r]
130 assert (p[1], r) == ("%sgpr", 1), "only T# word 1 is read" 130 if (p[1], r) == ("%sgpr", 1):
131 return word1 131 return word1
132 # The T# (s[0:7]) is not from a heap slot, so it is looked up, and its dword 6 wins where it carries
133 # the index tag (dword 3 says it names an image): 0 in both here, so the lookup's index is used.
134 assert (p[1], r) in (("%sgpr", 3), ("%sgpr", 6)), "only T# words 1, 3 and 6 are read"
135 return 0
132 var_op, v = self.defs[p[1]] 136 var_op, v = self.defs[p[1]]
133 assert var_op == "OpVariable" and v[1] == "Private", (var_op, v) 137 assert var_op == "OpVariable" and v[1] == "Private", (var_op, v)
134 words = self.defs[v[2]][1][1:] # OpConstantComposite %fmt_mask_arr <words> 138 words = self.defs[v[2]][1][1:] # OpConstantComposite %fmt_mask_arr <words>
135 return get(words[get(p[2])]) 139 return get(words[get(p[2])])
140 if op == "OpPhi":
141 # The T#'s index: the dword-6 word or the lookup, which runs only without the word. The T# words read
142 # 0 here (below), so the word has no tag and the lookup's side (the second pair) is the value.
143 return get(a[3])
136 if op == "OpGroupNonUniformBroadcastFirst": # One invocation: return the value (a[1] is the scope). 144 if op == "OpGroupNonUniformBroadcastFirst": # One invocation: return the value (a[1] is the scope).
137 return get(a[2]) 145 return get(a[2])
138 if op == "OpGroupNonUniformShuffle": # One invocation; subgroup shuffle returns its input. 146 if op == "OpGroupNonUniformShuffle": # One invocation; subgroup shuffle returns its input.
@@ -152,8 +160,12 @@ class Module:
152 return (u[0] >> u[1]) & ((1 << u[2]) - 1) 160 return (u[0] >> u[1]) & ((1 << u[2]) - 1)
153 if op == "OpShiftRightLogical": 161 if op == "OpShiftRightLogical":
154 return u[0] >> u[1] 162 return u[0] >> u[1]
163 if op == "OpShiftLeftLogical":
164 return (u[0] << u[1]) & 0xffffffff
155 if op == "OpBitwiseAnd": 165 if op == "OpBitwiseAnd":
156 return u[0] & u[1] 166 return u[0] & u[1]
167 if op == "OpBitwiseOr":
168 return u[0] | u[1]
157 if op == "OpINotEqual": 169 if op == "OpINotEqual":
158 return u[0] != u[1] 170 return u[0] != u[1]
159 if op == "OpIEqual": 171 if op == "OpIEqual":
diff --git a/tools/descriptor_source_census.py b/tools/descriptor_source_census.py
new file mode 100644
index 000000000..9264e2d82
--- /dev/null
+++ b/tools/descriptor_source_census.py
@@ -0,0 +1,326 @@
1r"""Where do the T#s and S#s of image instructions come from? (stdlib only; counts, no shader bytes)
2
3A translated shader turns the T# (8 SGPRs) and S# (4 SGPRs) of every image instruction into a bindless index.
4Whether that index can travel inside the descriptor (docs/design.md, "Bindless index in the T#") depends on where
5the descriptor words were loaded from: the layer rewrites the console resource heaps' copies and its own heaps, but
6not the title's other memory, and not the S#s of console sampler heaps, which shaders read in place.
7
8This census follows the forward SGPR dataflow of tools/heap_index_census.py over every listing and classifies the
9descriptor operand of each image instruction:
10
11 * heap32 all words are one aligned descriptor of an s_load_dwordx8/x16 whose base is a 32-bit pointer in
12 an entry SGPR (a descriptor table or a directly indexed heap), static or dynamic offset;
13 * heap32-partial the word that carries the index (T#: word 6, S#: word 3) is such a load's, other words are not
14 (the shader edited the descriptor);
15 * ptr64 / loaded / system / other-base an s_load from a 64-bit entry pointer, a loaded pointer, a system SGPR,
16 anything else;
17 * vsharp an s_buffer_load through a V# (a constant or structured buffer of the title's);
18 * literal every word a translate-time constant;
19 * unknown the dataflow lost the words (a join of different loads, a v_readfirstlane, an ALU result).
20
21It also counts, per descriptor word, scalar instructions that read a word of a heap32 T# or S# for anything but the
22image instruction itself (a shader doing its own maths on a field).
23
24Usage:
25 python -I tools/descriptor_source_census.py <work>/shaders/dxbc/disasm [--json OUT] [--limit N]
26"""
27import argparse
28import json
29import os
30import sys
31from collections import Counter, defaultdict
32
33sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
34import descriptor_sources # noqa: E402
35import heap_index_census as hic # noqa: E402
36import shader_ir # noqa: E402
37import shader_meta # noqa: E402
38from report_paths import same_report_path # noqa: E402
39
40LOADS = {"s_load_dwordx4": 4, "s_load_dwordx8": 8, "s_load_dwordx16": 16,
41 "s_buffer_load_dwordx4": 4, "s_buffer_load_dwordx8": 8, "s_buffer_load_dwordx16": 16}
42INDEX_WORD = {"T#": 6, "S#": 3}
43WIDTH = {"T#": 8, "S#": 4}
44
45
46def _regs(a, n):
47 if a["k"] == "sgpr" and a.get("n", 1) >= n:
48 return [a["r"] + i for i in range(n)]
49 if a["k"] == "slist" and len(a["r"]) >= n and all(isinstance(r, int) for r in a["r"][:n]):
50 return list(a["r"][:n])
51 return None
52
53
54def descriptor_operands(ins):
55 """[(role, [sgpr numbers])] of an image instruction."""
56 op = shader_meta.base_op(ins["op"])
57 a = ins["args"]
58 out = []
59 if not op.startswith("image_") or len(a) < 3:
60 return out
61 t = _regs(a[2], 8)
62 out.append(("T#", t))
63 if op.startswith(shader_meta.SAMPLER_IMAGE_OPS) and len(a) >= 4:
64 out.append(("S#", _regs(a[3], 4)))
65 return out
66
67
68def analyse(insns, stage, user_count):
69 blocks, succ = hic.blocks_of(insns)
70 system = set(hic.SYSTEM_SGPRS.get(stage, ()))
71 entry = [None] * len(blocks)
72 entry[0] = {r: ("in", r) for r in range(106)}
73 work = [0]
74 while work:
75 b = work.pop()
76 sym = dict(entry[b])
77 for ins in blocks[b]:
78 if shader_meta.base_op(ins["op"]) == "s_endpgm":
79 break
80 hic.step(sym, ins)
81 for s in succ[b]:
82 merged = sym if entry[s] is None else {k: v for k, v in entry[s].items() if sym.get(k) == v}
83 if merged != entry[s]:
84 entry[s] = dict(merged)
85 work.append(s)
86
87 loads = {} # pc -> (base class, offset kind, static offset)
88
89 def load_class(ins, sym):
90 op = shader_meta.base_op(ins["op"])
91 a = ins["args"]
92 if op.startswith("s_buffer_"):
93 return ("vsharp", None, None)
94 if len(a) < 2 or a[1]["k"] != "sgpr" or a[1].get("n") != 2:
95 return ("other-base", None, None)
96 b = a[1]["r"]
97 lo, hi = sym.get(b), sym.get(b + 1)
98 rlo, dyn = hic.root(lo)
99 off = hic._src(sym, a[2]) if len(a) >= 3 else ("const", 0)
100 static = off[1] if off is not None and off[0] == "const" and not dyn else None
101 kind = "static" if static is not None else "dynamic"
102 if rlo is not None and rlo[0] == "in":
103 n = rlo[1]
104 if n in system or n >= user_count:
105 return ("system", kind, static)
106 if hi == ("const", 0):
107 return ("heap32", kind, static)
108 return ("ptr64", kind, static)
109 if rlo is not None and rlo[0] == "ld":
110 return ("loaded", kind, static)
111 return ("other-base", kind, static)
112
113 uses = [] # (pc, role, class)
114 heap_loads = defaultdict(set) # load pc -> roles of heap32 descriptors taken from it whole or in part
115 pending_reads = [] # (load pc, dword) read by a scalar instruction that is not an image instruction
116 for b in range(len(blocks)):
117 if entry[b] is None:
118 continue
119 sym = dict(entry[b])
120 for ins in blocks[b]:
121 op = shader_meta.base_op(ins["op"])
122 if op == "s_endpgm":
123 break
124 if op in LOADS and ins["args"] and ins["args"][0]["k"] == "sgpr":
125 loads[ins["pc"]] = load_class(ins, sym)
126 if op.startswith("image_"):
127 for role, regs in descriptor_operands(ins):
128 uses.append((ins["pc"], role, classify(role, regs, sym, loads, heap_loads)))
129 elif not op.startswith(("s_load_", "s_buffer_load_", "s_mov_b", "s_waitcnt")):
130 reads, _ = shader_meta._split_operands(ins)
131 for r in reads:
132 t = sym.get(r)
133 if t is not None and t[0] == "ld":
134 pending_reads.append((t[1], t[2], op))
135 hic.step(sym, ins)
136 verdict = descriptor_sources.analyse(blocks, succ, user_count, system)
137 embedded = sum(1 for v in verdict.values() if v)
138 reads = Counter()
139 for pc, dword, op in pending_reads:
140 for role in heap_loads.get(pc, ()):
141 reads[(role, dword % WIDTH[role], op)] += 1
142 return uses, reads, (embedded, len(verdict))
143
144
145def classify(role, regs, sym, loads, heap_loads):
146 if regs is None:
147 return "unknown"
148 tags = [sym.get(r) for r in regs]
149 if all(t is not None and t[0] == "const" for t in tags):
150 return "literal"
151 w = WIDTH[role]
152 first = tags[0]
153 whole = (first is not None and first[0] == "ld" and first[2] % w == 0 and
154 all(t == ("ld", first[1], first[2] + i) for i, t in enumerate(tags)))
155 idx = tags[INDEX_WORD[role]]
156 if whole:
157 cls, kind, static = loads.get(first[1], ("other-base", None, None))
158 if cls == "heap32":
159 heap_loads[first[1]].add(role)
160 if kind == "static" and static % 16:
161 return "heap32-misaligned"
162 return f"heap32-{kind}"
163 return cls
164 if idx is not None and idx[0] == "ld" and idx[2] % w == INDEX_WORD[role]:
165 cls, kind, static = loads.get(idx[1], ("other-base", None, None))
166 if cls == "heap32":
167 heap_loads[idx[1]].add(role)
168 return "heap32-partial"
169 return cls + "-partial"
170 return "unknown"
171
172
173def fspx_user_count(disasm_dir, name):
174 """USER_SGPR [5:1] of an FSPX program's COMPUTE_PGM_RSRC2 (<disasm>/../fspx/<name>.json, tools/fspx_unpack.py;
175 the pipeline library's programs have no FSSM header), or None."""
176 path = os.path.join(os.path.dirname(os.path.abspath(disasm_dir)), "fspx", name + ".json")
177 try:
178 with open(path, encoding="utf-8") as f:
179 return (int(json.load(f)["rsrc2"]) >> 1) & 31
180 except (OSError, ValueError, KeyError, TypeError):
181 return None
182
183
184def census(disasm_dir, limit=None, progress=None):
185 stages = hic.stage_index(disasm_dir)
186 names = sorted(n[:-2] for n in os.listdir(disasm_dir) if n.endswith(".s"))
187 if limit:
188 names = names[:limit]
189 skipped = Counter()
190 accesses = defaultdict(Counter) # role -> class -> image instructions
191 modules = defaultdict(Counter) # role -> class -> modules with at least one
192 only_heap = Counter() # role -> modules whose every operand of that role is heap32-*
193 with_role = Counter()
194 word_reads = Counter()
195 per_stage = defaultdict(Counter) # stage -> class (T#) -> accesses
196 index_word = Counter() # descriptor_sources.analyse, as the translator decides
197 shaders = 0
198 for k, name in enumerate(names):
199 if progress and k % 2000 == 0:
200 progress(k, len(names))
201 stage = stages.get(name)
202 if stage is None:
203 skipped["no stage"] += 1
204 continue
205 info = shader_ir.parse_file(os.path.join(disasm_dir, name + ".s"))
206 if not info["insns"]:
207 skipped["no instructions"] += 1
208 continue
209 if info["invalid"]:
210 skipped["embedded data words"] += 1
211 continue
212 user = hic.USER_SGPRS
213 if stage == "cs":
214 user = hic.cs_user_count(disasm_dir, name)
215 if user is None:
216 user = fspx_user_count(disasm_dir, name)
217 if user is None:
218 skipped["no FSSM header"] += 1
219 continue
220 try:
221 uses, reads, (emb, images) = analyse(info["insns"], stage, user)
222 except hic.Skip as e:
223 skipped[str(e)] += 1
224 continue
225 shaders += 1
226 index_word["image instructions"] += images
227 index_word["T# index from dword 6"] += emb
228 if images:
229 index_word["modules with images"] += 1
230 if emb == images:
231 index_word["modules with no T# lookup"] += 1
232 seen = defaultdict(set)
233 for _, role, cls in uses:
234 accesses[role][cls] += 1
235 seen[role].add(cls)
236 if role == "T#":
237 per_stage[stage][cls] += 1
238 for role, classes in seen.items():
239 with_role[role] += 1
240 for c in classes:
241 modules[role][c] += 1
242 if all(c.startswith("heap32-") and c != "heap32-misaligned" for c in classes):
243 only_heap[role] += 1
244 for (role, dword, op), n in reads.items():
245 word_reads[(role, dword, op)] += n
246 return {
247 "shaders_read": len(names), "shaders_followed": shaders, "skipped": dict(skipped),
248 "accesses": {r: dict(c.most_common()) for r, c in accesses.items()},
249 "modules": {r: dict(c.most_common()) for r, c in modules.items()},
250 "modules_with_role": dict(with_role),
251 "modules_all_heap32": dict(only_heap),
252 "t_sharp_accesses_per_stage": {s: dict(c.most_common()) for s, c in sorted(per_stage.items())},
253 "tsharp_index_word": dict(index_word),
254 "heap32_word_reads": [{"role": r, "word": d, "op": o, "count": n}
255 for (r, d, o), n in sorted(word_reads.items())],
256 }
257
258
259def print_report(out):
260 print(f"shaders read: {out['shaders_read']}, followed: {out['shaders_followed']}; "
261 f"skipped: {out['skipped'] or 'none'}")
262 for role in ("T#", "S#"):
263 acc = out["accesses"].get(role, {})
264 total = sum(acc.values())
265 print(f"\n{role}: {total} image instructions in {out['modules_with_role'].get(role, 0)} modules; "
266 f"{out['modules_all_heap32'].get(role, 0)} modules take every {role} whole from a heap32 load")
267 for cls, n in acc.items():
268 print(f" {cls:<24} {n:>9} accesses {out['modules'][role][cls]:>7} modules")
269 print("\nT# accesses per stage:")
270 for s, c in out["t_sharp_accesses_per_stage"].items():
271 print(f" {s}: " + ", ".join(f"{k} {v}" for k, v in c.items()))
272 print("\nthe translator's verdict (tools/descriptor_sources.py): " +
273 ", ".join(f"{k} {v}" for k, v in out["tsharp_index_word"].items()))
274 words = Counter()
275 for row in out["heap32_word_reads"]:
276 words[(row["role"], row["word"])] += row["count"]
277 print("\nscalar reads of heap32 descriptor words (not by the image instruction):")
278 for (role, word), n in sorted(words.items()):
279 print(f" {role} word {word}: {n}")
280
281
282def main(argv=None):
283 ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
284 ap.add_argument("disasm", help="<work>/shaders/dxbc/disasm")
285 ap.add_argument("--json", help="write the full census here (outside the disasm folder)")
286 ap.add_argument("--limit", type=shader_ir.positive_int, help="only the first N listings (sorted by name)")
287 args = ap.parse_args(argv)
288 if not os.path.isdir(args.disasm):
289 print(f"ERROR: {args.disasm} is not a folder", file=sys.stderr)
290 return 2
291 if args.json:
292 disasm = os.path.realpath(args.disasm)
293 target = os.path.realpath(os.path.abspath(args.json))
294 try:
295 inside = os.path.commonpath([disasm, target]) == disasm
296 except ValueError:
297 inside = False
298 index_path = os.path.join(os.path.dirname(os.path.abspath(args.disasm)), "index.json")
299 if inside or same_report_path(args.json, index_path):
300 print(f"ERROR: --json must not write inside or next to the folder it reads: {args.json}",
301 file=sys.stderr)
302 return 2
303 try:
304 out = census(args.disasm, args.limit,
305 progress=lambda k, n: print(f" {k}/{n}", file=sys.stderr, flush=True))
306 except (OSError, ValueError, KeyError, TypeError) as e:
307 print(f"ERROR: {e}", file=sys.stderr)
308 return 2
309 print_report(out)
310 if args.json:
311 try:
312 with open(args.json, "w", encoding="utf-8", newline="\n") as f:
313 json.dump(out, f, indent=1, sort_keys=True)
314 f.write("\n")
315 except OSError as e:
316 print(f"ERROR: cannot write {args.json}: {e}", file=sys.stderr)
317 return 2
318 return 0
319
320
321if __name__ == "__main__":
322 try:
323 sys.stdout.reconfigure(errors="replace")
324 except (AttributeError, ValueError, OSError):
325 pass
326 sys.exit(main())
diff --git a/tools/descriptor_sources.py b/tools/descriptor_sources.py
new file mode 100644
index 000000000..5a2b41e51
--- /dev/null
+++ b/tools/descriptor_sources.py
@@ -0,0 +1,269 @@
1r"""Which image instructions read a T# whose index word the layer wrote (docs/design.md, "Bindless index in the T#").
2
3The layer writes the bindless index of every T# into dword 6 of the descriptor slot shaders load it from: the
4copies of the console resource heaps it keeps (fix_console_slot) and its own shader-visible heaps (Create*View).
5Shaders reach those heaps only through a descriptor-table or heap pointer, which arrives as a 32-bit pointer in an
6entry SGPR (user data) with the high dword a constant 0 (docs/d3d12_vulkan.md section 3.4, D3D-329: 99.86% of the
7corpus's descriptor loads). A T# loaded through anything else (a 64-bit pointer, a pointer read from memory, a
8constant or structured buffer of the title's) or built from constants keeps the title's dword 6, so for those the
9translator keeps the hash-table lookup.
10
11`analyse` follows a forward dataflow over the basic blocks, as tools/heap_index_census.py does, tagging each SGPR
12with where its value came from, and answers, for every image instruction, whether the SGPR that holds its T#'s
13dword 6 holds dword 6 of a heap slot: a dword of an s_load from such a pointer whose byte position in its 32-byte
14slot is 24 (a static offset is known; a run-time offset, the heap index times the slot size, is taken as slot
15aligned, which the shader's tag check guards). Where two paths join with loads of different instructions, the value
16keeps its slot position when both are heap dwords at the same position, so a T# loaded in either arm of a branch
17still counts. Any other write, and anything the dataflow cannot follow, gives the lookup.
18
19Standard library only; tools/rdna2spirv.py and tools/descriptor_source_census.py share it.
20"""
21import os
22import sys
23
24sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
25import heap_index_census as _hic # noqa: E402
26import shader_meta as _meta # noqa: E402
27
28SLOT_BYTES = 32 # kDescriptorSize: one T# per slot, at its start
29INDEX_DWORD = 6 # the T# dword that carries the index (gfx10_descriptors.h, tsharp_index_word)
30ENTRY_SGPRS = 106
31SCALAR_LOADS = ("s_load_dword", "s_buffer_load_dword")
32
33
34def _load_slot_base(ins, sym, user_count, system):
35 """For an s_load whose base is a 32-bit heap pointer in a user SGPR: the byte position in its slot of the load's
36 first dword (a static offset mod 32; 0 for a run-time one, the heap index times 32). None for any other load."""
37 op = _meta.base_op(ins["op"])
38 a = ins["args"]
39 if not op.startswith("s_load_dword") or len(a) < 2 or a[1]["k"] != "sgpr" or a[1].get("n") != 2:
40 return None
41 b = a[1]["r"]
42 lo, hi = sym.get(b), sym.get(b + 1)
43 t = lo
44 while t is not None and t[0] == "off":
45 if not t[2]:
46 return None # a constant added to the pointer whose value the tag does not keep: position unknown
47 t = t[1]
48 if t is None or t[0] != "in" or hi != ("const", 0):
49 return None
50 n = t[1]
51 if n in system or n >= user_count:
52 return None
53 off = _hic._src(sym, a[2]) if len(a) >= 3 else ("const", 0)
54 if off is not None and off[0] == "const":
55 return off[1] % SLOT_BYTES
56 return 0 # a run-time offset (the heap index times the slot size) on top of the table pointer
57
58
59def _slot_pos(tag, heap_loads):
60 """The dword position in a heap slot of the value `tag` names, or None."""
61 if tag is None:
62 return None
63 if tag[0] == "hw":
64 return tag[1]
65 if tag[0] == "ld" and tag[1] in heap_loads:
66 byte = heap_loads[tag[1]] + 4 * tag[2]
67 return (byte % SLOT_BYTES) // 4 if byte % 4 == 0 else None
68 return None
69
70
71def _merge(old, new, heap_loads):
72 out = {}
73 for k, v in old.items():
74 w = new.get(k)
75 if w == v:
76 out[k] = v
77 continue
78 p, q = _slot_pos(v, heap_loads), _slot_pos(w, heap_loads)
79 if p is not None and p == q:
80 out[k] = ("hw", p)
81 return out
82
83
84def _vgprs(ins):
85 """Every VGPR an instruction names, read or written."""
86 out = set()
87 for a in ins["args"]:
88 if a["k"] == "vgpr":
89 out.update(range(a["r"], a["r"] + a.get("n", 1)))
90 elif a["k"] == "vlist":
91 out.update(r for r in a["r"] if isinstance(r, int))
92 return out
93
94
95def _lane(sym, a):
96 """The constant lane of a v_readlane/v_writelane lane operand, or None."""
97 t = _hic._src(sym, a)
98 return t[1] & 63 if t is not None and t[0] == "const" else None
99
100
101def _spill_step(sym, ins, spill_vgprs):
102 """SGPR values parked in VGPR lanes (v_writelane_b32 / v_readlane_b32, a compiler's SGPR spill): the lane keeps the
103 tag of the SGPR written into it, as ("v", vgpr, lane), and a v_readlane of a constant lane gives it back. Any other
104 instruction naming the VGPR forgets its lanes. Run after heap_index_census.step, which has forgotten the
105 v_readlane's destination."""
106 op = _meta.base_op(ins["op"])
107 a = ins["args"]
108 if op == "v_readlane_b32": # reads the VGPR and leaves it as it is, whatever it writes (an SGPR, VCC)
109 if len(a) >= 3 and a[0]["k"] == "sgpr" and a[0].get("n", 1) == 1 and a[1]["k"] == "vgpr":
110 lane = _lane(sym, a[2])
111 tag = sym.get(("v", a[1]["r"], lane)) if lane is not None else None
112 if tag is not None:
113 sym[a[0]["r"]] = tag
114 return
115 touched = _vgprs(ins) & spill_vgprs
116 if not touched:
117 return
118 before = None
119 if op == "v_writelane_b32" and len(a) >= 3 and a[0]["k"] == "vgpr":
120 lane = _lane(sym, a[2])
121 if lane is not None: # only that lane changes; a source other than an SGPR (VCC, a constant) is unknown
122 src = sym.get(a[1]["t"]) if a[1]["k"] == "special" and a[1].get("t") in VCC_HALVES else \
123 _hic._src(sym, a[1])
124 before = (a[0]["r"], lane, src)
125 for k in [k for k in sym if isinstance(k, tuple) and k[1] in touched]:
126 if before is None or k[1] != before[0] or k[2] == before[1]:
127 del sym[k]
128 if before is not None and before[2] is not None:
129 sym[("v", before[0], before[1])] = before[2]
130
131
132VCC_HALVES = ("vcc_lo", "vcc_hi")
133
134
135def _vcc_names(a):
136 if a["k"] == "special" and a.get("t") in ("vcc", "vcc_lo", "vcc_hi"):
137 return {"vcc_lo", "vcc_hi"} if a["t"] == "vcc" else {a["t"]}
138 if a["k"] == "slist":
139 return {r for r in a["r"] if r in VCC_HALVES}
140 return set()
141
142
143def _vcc_step(sym, ins):
144 """VCC used as two more SGPRs: a compiler short of SGPRs loads a T#'s last two dwords into vcc_lo and vcc_hi
145 (s_load_dwordx8 [s100, ..., s105, vcc_lo, vcc_hi]) or parks a pointer there. Their tags live under "vcc_lo" and
146 "vcc_hi". LLVM prints every VCC operand, the implicit ones of VOPC and carry instructions included, so any other
147 instruction naming VCC forgets them (a reader as well, which only loses precision). Run after
148 heap_index_census.step, which follows neither VCC nor a load into a register list."""
149 op = _meta.base_op(ins["op"])
150 a = ins["args"]
151 if not a:
152 return
153 if op.startswith(SCALAR_LOADS) and a[0]["k"] == "slist":
154 for i, r in enumerate(a[0]["r"]):
155 sym[r] = ("ld", ins["pc"], i)
156 return
157 if op.startswith("image_"):
158 return # reads its descriptor operands
159 names = set().union(*(_vcc_names(x) for x in a))
160 if not names:
161 return
162 if op == "v_readlane_b32" and len(a) >= 3 and a[0]["k"] == "special" and a[0].get("t") in VCC_HALVES \
163 and a[1]["k"] == "vgpr":
164 lane = _lane(sym, a[2])
165 tag = sym.get(("v", a[1]["r"], lane)) if lane is not None else None
166 sym.pop(a[0]["t"], None)
167 if tag is not None:
168 sym[a[0]["t"]] = tag
169 return
170 if op in ("s_mov_b64", "s_mov_b32") and len(a) >= 2 and a[0]["k"] == "sgpr" and not _vcc_names(a[0]):
171 src = ["vcc_lo", "vcc_hi"] if op == "s_mov_b64" and a[1].get("t") == "vcc" else \
172 [a[1]["t"]] if op == "s_mov_b32" and a[1].get("t") in VCC_HALVES else None
173 if src is not None:
174 for i, name in enumerate(src):
175 tag = sym.get(name)
176 if tag is not None:
177 sym[a[0]["r"] + i] = tag
178 return
179 for name in VCC_HALVES:
180 sym.pop(name, None)
181
182
183def tsharp_operand(ins):
184 """The registers of an image instruction's T# (SGPR numbers, or "vcc_lo" / "vcc_hi" in a register list), or
185 None."""
186 a = ins["args"]
187 if not _meta.base_op(ins["op"]).startswith("image_") or len(a) < 3:
188 return None
189 t = a[2]
190 if t["k"] == "sgpr" and t.get("n", 1) >= 8:
191 return [t["r"] + i for i in range(8)]
192 if t["k"] == "slist" and len(t["r"]) >= 8 and all(isinstance(r, int) or r in VCC_HALVES for r in t["r"][:8]):
193 return list(t["r"][:8])
194 return None
195
196
197def analyse(blocks, succ, user_count=32, system=()):
198 """{id(ins): bool} for every image instruction of `blocks` (the translator's basic blocks, `succ` their
199 successors): True when its T#'s dword 6 is dword 6 of a heap slot. Raises heap_index_census.Skip never; an
200 instruction the analysis cannot place is simply absent (the caller keeps the lookup)."""
201 system = set(system)
202 if not blocks:
203 return {}
204 # The tags name a load by its pc. A listing without encodings (a hand-written test program) gives every
205 # instruction the same pc, so the analysis then runs on copies numbered in order and maps its answers back.
206 flat = [ins for blk in blocks for ins in blk]
207 if len({ins["pc"] for ins in flat}) < len(flat):
208 copies, k = [], 0
209 for blk in blocks:
210 copies.append([dict(ins, pc=4 * (k + n)) for n, ins in enumerate(blk)])
211 k += len(blk)
212 answers = analyse(copies, succ, user_count, system)
213 return {id(ins): answers.get(id(copy), False)
214 for ins, copy in zip(flat, (c for blk in copies for c in blk))}
215 spill_vgprs = {ins["args"][0]["r"] for ins in flat if _meta.base_op(ins["op"]) == "v_writelane_b32" and
216 ins["args"] and ins["args"][0]["k"] == "vgpr"}
217 # A load is a heap load when every path reaching it brings a heap pointer. The fixpoint below decides that as it
218 # goes; a load first seen as one and later not (a join lost its pointer) is banned and the dataflow run again
219 # without it, so no slot position stays derived from a load that is not a heap load in the end.
220 banned = set()
221 while True:
222 heap_loads = {} # load pc -> byte position of its first dword in its slot
223 lost = set()
224 entry = [None] * len(blocks)
225 entry[0] = {r: ("in", r) for r in range(ENTRY_SGPRS)}
226
227 def run(b, sym, out=None):
228 for ins in blocks[b]:
229 op = _meta.base_op(ins["op"])
230 if op == "s_endpgm":
231 break
232 if op.startswith(SCALAR_LOADS):
233 pc = ins["pc"]
234 pos = None if pc in banned else _load_slot_base(ins, sym, user_count, system)
235 if pos is None or heap_loads.get(pc, pos) != pos:
236 if pc in heap_loads:
237 lost.add(pc)
238 heap_loads.pop(pc, None)
239 banned.add(pc)
240 else:
241 heap_loads[pc] = pos
242 if out is not None and op.startswith("image_"):
243 regs = tsharp_operand(ins)
244 out[id(ins)] = (regs is not None and
245 _slot_pos(sym.get(regs[INDEX_DWORD]), heap_loads) == INDEX_DWORD)
246 _hic.step(sym, ins)
247 if spill_vgprs:
248 _spill_step(sym, ins, spill_vgprs)
249 _vcc_step(sym, ins)
250 return sym
251
252 work = [0]
253 while work:
254 b = work.pop()
255 sym = run(b, dict(entry[b]))
256 for s in succ[b]:
257 merged = dict(sym) if entry[s] is None else _merge(entry[s], sym, heap_loads)
258 if merged != entry[s]:
259 entry[s] = merged
260 work.append(s)
261 if lost:
262 continue
263 out = {}
264 for b in range(len(blocks)):
265 if entry[b] is not None:
266 run(b, dict(entry[b]), out)
267 if lost:
268 continue
269 return out
diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py
index 9fcc90988..cc6abe0e1 100644
--- a/tools/rdna2spirv.py
+++ b/tools/rdna2spirv.py
@@ -35,6 +35,7 @@ from shader_ir import HDR, parse_file # noqa: E402
35from replace_retry import replace as replace_retry # noqa: E402 35from replace_retry import replace as replace_retry # noqa: E402
36from file_mode import published_mode # noqa: E402 36from file_mode import published_mode # noqa: E402
37import cfg_structure # noqa: E402 37import cfg_structure # noqa: E402
38import descriptor_sources # noqa: E402
38import fssm_header # noqa: E402 39import fssm_header # noqa: E402
39import fssm_unpack # noqa: E402 40import fssm_unpack # noqa: E402
40import lane_masks # noqa: E402 41import lane_masks # noqa: E402
@@ -65,6 +66,14 @@ DESCRIPTOR_TABLE = "tagged"
65# The kind word's bit positions, shared with runtime/src/descriptor_table.h. 66# The kind word's bit positions, shared with runtime/src/descriptor_table.h.
66DESC_SAMPLED_BIT = 0 # bit i: the index is bound in dimension i's sampled array 67DESC_SAMPLED_BIT = 0 # bit i: the index is bound in dimension i's sampled array
67DESC_STORAGE_BIT = 8 # bit 8 + i: ... in its storage arrays (dimensions 0..4 have them) 68DESC_STORAGE_BIT = 8 # bit 8 + i: ... in its storage arrays (dimensions 0..4 have them)
69# The bindless index in the T# (docs/design.md, "Bindless index in the T#"): the layer writes dword 6 of every T# in
70# the heaps it keeps (runtime/src/gfx10_descriptors.h, tsharp_index_word) as TAG << 28 | storage kind << 23 |
71# sampled kind << 16 | index, the kind being the table's kind bits 8..12 and 0..6. A module reads it, without the
72# hash table, where tools/descriptor_sources.py shows the T#'s dword 6 was loaded from such a heap, and records
73# TSHARP_INDEX in its meta, which tells the runtime to write the word.
74TSHARP_INDEX = "dword6"
75TSHARP_INDEX_DWORD = 6
76TSHARP_INDEX_TAG = 0xA
68WAVE64_EMULATE = False # --wave64-emulate: wave64 compute/mesh shaders exact on any subgroup size (Gen.x_round) 77WAVE64_EMULATE = False # --wave64-emulate: wave64 compute/mesh shaders exact on any subgroup size (Gen.x_round)
69# --wave64-emulate: use wave64_emulate_opt's inline structured form when it does not put an exchange barrier 78# --wave64-emulate: use wave64_emulate_opt's inline structured form when it does not put an exchange barrier
70# under control flow only some invocations take (translate() re-runs this module without it when it does). 79# under control flow only some invocations take (translate() re-runs this module without it when it does).
@@ -586,6 +595,10 @@ class Gen:
586 self.x_round_fn_types: dict[int, str] = {} # emulate_inline: arity -> OpTypeFunction id for x_round_fns 595 self.x_round_fn_types: dict[int, str] = {} # emulate_inline: arity -> OpTypeFunction id for x_round_fns
587 self.sgpr_imm = {} # SGPR -> literal an s_mov_b32 put there earlier in this basic block (see gather_addr_modes) 596 self.sgpr_imm = {} # SGPR -> literal an s_mov_b32 put there earlier in this basic block (see gather_addr_modes)
588 self.desc_cache = {} # (first SGPR, dwords) -> id of the %desc_lookup_fn result in the current basic block 597 self.desc_cache = {} # (first SGPR, dwords) -> id of the %desc_lookup_fn result in the current basic block
598 # id(instruction) -> True when its T#'s dword 6 comes from a heap slot the layer writes (descriptor_sources)
599 self.tsharp_from_heap = {}
600 self.tsharp_index_reads = 0 # image instructions that take the T#'s index from dword 6 alone
601 self.tsharp_lookups = 0 # ... that also look the T# up in the hash table (its source is not known)
589 self._scan = (None, 0, []) # (body list, lines already seen, open merge labels): see desc_cache_ok 602 self._scan = (None, 0, []) # (body list, lines already seen, open merge labels): see desc_cache_ok
590 self.block_label = "%entry" # label of the SPIR-V block the current instruction starts in 603 self.block_label = "%entry" # label of the SPIR-V block the current instruction starts in
591 self.build_meta = {} # runtime build metadata from tools/shader_meta.py 604 self.build_meta = {} # runtime build metadata from tools/shader_meta.py
@@ -13234,7 +13247,7 @@ class Gen:
13234 # The last word is the pad word a plain module never reads; --descriptor-table tagged fills it with the kind. 13247 # The last word is the pad word a plain module never reads; --descriptor-table tagged fills it with the kind.
13235 PROBES = 8 13248 PROBES = 8
13236 13249
13237 def desc_lookup(self, words): 13250 def desc_lookup(self, words, uniform=True):
13238 """words: 8 uint ids. Returns (bindless index, kind), kind being None with --descriptor-table plain. 13251 """words: 8 uint ids. Returns (bindless index, kind), kind being None with --descriptor-table plain.
13239 13252
13240 The probe is about 400 instructions, so it is one function in the module (%desc_lookup_fn) that every 13253 The probe is about 400 instructions, so it is one function in the module (%desc_lookup_fn) that every
@@ -13259,6 +13272,32 @@ class Gen:
13259 self.emit(f"{kind} = OpCompositeExtract %uint {r} 1") 13272 self.emit(f"{kind} = OpCompositeExtract %uint {r} 1")
13260 else: 13273 else:
13261 idx, kind = r, None 13274 idx, kind = r, None
13275 return self.desc_uniform(idx, kind) if uniform else (idx, kind)
13276
13277 def tsharp_index_word(self, words):
13278 """(index, kind, tagged) from the T#'s dword 6 as the layer writes it (TSHARP_INDEX): the bool `tagged` is
13279 whether the word carries the tag and dword 3 names an image (TYPE >= 8, bit 31); index and kind are 0 when it
13280 does not, index 0's fallback, which is what a T# that names no image reads. The words are SGPRs, so this is a
13281 handful of scalar operations and no memory access beyond the T# the shader loaded anyway."""
13282 w3, w6 = words[3], words[TSHARP_INDEX_DWORD]
13283 tag, tag_ok, img, img_ok, ok = (self.tmp() for _ in range(5))
13284 self.emit(f"{tag} = OpShiftRightLogical %uint {w6} {self.cu(28)}")
13285 self.emit(f"{tag_ok} = OpIEqual %bool {tag} {self.cu(TSHARP_INDEX_TAG)}")
13286 self.emit(f"{img} = OpShiftRightLogical %uint {w3} {self.cu(31)}")
13287 self.emit(f"{img_ok} = OpINotEqual %bool {img} {self.cu(0)}")
13288 self.emit(f"{ok} = OpLogicalAnd %bool {tag_ok} {img_ok}")
13289 raw, idx, sampled, storage, storage_hi, both, kind = (self.tmp() for _ in range(7))
13290 self.emit(f"{raw} = OpBitwiseAnd %uint {w6} {self.cu(0xFFFF)}")
13291 self.emit(f"{idx} = OpSelect %uint {ok} {raw} {self.cu(0)}")
13292 self.emit(f"{sampled} = OpBitFieldUExtract %uint {w6} {self.cu(16)} {self.cu(7)}")
13293 self.emit(f"{storage} = OpBitFieldUExtract %uint {w6} {self.cu(23)} {self.cu(5)}")
13294 self.emit(f"{storage_hi} = OpShiftLeftLogical %uint {storage} {self.cu(DESC_STORAGE_BIT)}")
13295 self.emit(f"{both} = OpBitwiseOr %uint {sampled} {storage_hi}")
13296 self.emit(f"{kind} = OpSelect %uint {ok} {both} {self.cu(0)}")
13297 return idx, kind, ok
13298
13299 def desc_uniform(self, idx, kind):
13300 """The index (and the kind, or None) made explicitly uniform, as the hash lookup's result always was."""
13262 if self.emulate: 13301 if self.emulate:
13263 return idx, kind 13302 return idx, kind
13264 if self.wave32_fragment: 13303 if self.wave32_fragment:
@@ -13850,6 +13889,20 @@ class Gen:
13850 self.image_read_typed(dim, self.sgpr_word(a[2], 1), img, img_idx, 13889 self.image_read_typed(dim, self.sgpr_word(a[2], 1), img, img_idx,
13851 0xf, vdata, d16, gather_mip) 13890 0xf, vdata, d16, gather_mip)
13852 13891
13892 def tsharp_index_sgpr(self, a):
13893 """(index, kind) of the current instruction's T# operand `a` when the dataflow showed its dword 6 is a heap
13894 slot's (Gen.tsharp_from_heap, tools/descriptor_sources.py), else None."""
13895 ins = self.cur_ins
13896 if ins is None or not self.tsharp_from_heap.get(id(ins)):
13897 return None
13898 regs = descriptor_sources.tsharp_operand(ins)
13899 if regs is None or tuple(regs) != self.tsharp_regs(a):
13900 return None
13901 self.uses_tex = True # set 0's image arrays, which the index reads, as desc_lookup declares them
13902 idx, kind, _ = self.tsharp_index_word(self.sgpr_words(a, 8))
13903 self.tsharp_index_reads += 1
13904 return self.desc_uniform(idx, kind)
13905
13853 def desc_lookup_sgpr(self, a, n): 13906 def desc_lookup_sgpr(self, a, n):
13854 """desc_lookup for an SGPR descriptor range (n=8: T#, n=4: S#), cached for the rest of the basic block. 13907 """desc_lookup for an SGPR descriptor range (n=8: T#, n=4: S#), cached for the rest of the basic block.
13855 13908
@@ -13858,12 +13911,21 @@ class Gen:
13858 array go through store_reg, including the 64-bit ones, which are two calls, s_load results, 13911 array go through store_reg, including the 64-bit ones, which are two calls, s_load results,
13859 v_readlane/v_readfirstlane results and the spare slots lane masks are parked in) and cleared when a basic 13912 v_readlane/v_readfirstlane results and the spare slots lane masks are parked in) and cleared when a basic
13860 block starts. Only lookups made at the block's top level are remembered, see desc_cache_ok. Returns 13913 block starts. Only lookups made at the block's top level are remembered, see desc_cache_ok. Returns
13861 (bindless index, kind), kind being None with --descriptor-table plain.""" 13914 (bindless index, kind), kind being None with --descriptor-table plain.
13915
13916 A T# (n=8) whose dword 6 the dataflow traced to a heap slot takes its index from that word alone
13917 (tsharp_index_sgpr). Any other T# is looked up, and the dword-6 index wins where the word carries it: such a
13918 T# may still come from a heap the layer writes, along a path the dataflow did not follow, and there its words
13919 are not the key the table holds (the key is the descriptor as the title wrote it)."""
13920 if n == 8:
13921 direct = self.tsharp_index_sgpr(a)
13922 if direct is not None:
13923 return direct
13862 if a["k"] == "slist" and len(a["r"]) >= n: 13924 if a["k"] == "slist" and len(a["r"]) >= n:
13863 words = self.sgpr_words(a, n) 13925 words = self.sgpr_words(a, n)
13864 if n < 8: 13926 if n < 8:
13865 words = words + [self.cu(0xFFFFFFFF)] * (8 - n) 13927 words = words + [self.cu(0xFFFFFFFF)] * (8 - n)
13866 return self.desc_lookup(words) 13928 return self.desc_lookup(words) if n < 8 else self.tsharp_lookup(words)
13867 if a["k"] != "sgpr" or a.get("n", 1) < n: 13929 if a["k"] != "sgpr" or a.get("n", 1) < n:
13868 raise Unsupported("descriptor operand") 13930 raise Unsupported("descriptor operand")
13869 key = (a["r"], n) 13931 key = (a["r"], n)
@@ -13874,11 +13936,33 @@ class Gen:
13874 words = self.sgpr_words(a, n) 13936 words = self.sgpr_words(a, n)
13875 if n < 8: 13937 if n < 8:
13876 words = words + [self.cu(0xFFFFFFFF)] * (8 - n) 13938 words = words + [self.cu(0xFFFFFFFF)] * (8 - n)
13877 idx = self.desc_lookup(words) 13939 idx = self.desc_lookup(words) if n < 8 else self.tsharp_lookup(words)
13878 if top: 13940 if top:
13879 self.desc_cache[key] = idx 13941 self.desc_cache[key] = idx
13880 return idx 13942 return idx
13881 13943
13944 def tsharp_lookup(self, words):
13945 """A T# of unknown source: its dword-6 index where the word carries one, else the hash table's answer for its
13946 words. The lookup sits in the branch taken only without the word: `ok` comes from SGPRs, so the branch is
13947 uniform, and a T# from a heap the layer writes, along a path the dataflow did not follow, costs no probe."""
13948 self.tsharp_lookups += 1
13949 direct, direct_kind, ok = self.tsharp_index_word(words)
13950 pre = self.current_label_placeholder()
13951 probe, end = self.tmp() + "_probe", self.tmp() + "_tsharp"
13952 self.emit(f"OpSelectionMerge {end} None")
13953 self.emit(f"OpBranchConditional {ok} {end} {probe}")
13954 self.emit(f"{probe} = OpLabel")
13955 idx, kind = self.desc_lookup(words, uniform=False)
13956 self.emit(f"OpBranch {end}")
13957 self.emit(f"{end} = OpLabel")
13958 out = self.tmp()
13959 self.emit(f"{out} = OpPhi %uint {direct} {pre} {idx} {probe}")
13960 out_kind = None
13961 if kind is not None:
13962 out_kind = self.tmp()
13963 self.emit(f"{out_kind} = OpPhi %uint {direct_kind} {pre} {kind} {probe}")
13964 return self.desc_uniform(out, out_kind)
13965
13882 # The dimension of an instruction's image array, indexed by STORE_DIMS' index (0 2D, 1 2D array, 2 3D, 3 1D). 13966 # The dimension of an instruction's image array, indexed by STORE_DIMS' index (0 2D, 1 2D array, 2 3D, 3 1D).
13883 # A cube instruction reads the 2D-array binding: a cube is six layers of a 2D array. 13967 # A cube instruction reads the 2D-array binding: a cube is six layers of a 2D array.
13884 DIM_TAGS = {"dim:SQ_RSRC_IMG_2D": 0, "dim:SQ_RSRC_IMG_2D_ARRAY": 1, "dim:SQ_RSRC_IMG_CUBE": 1, 13968 DIM_TAGS = {"dim:SQ_RSRC_IMG_2D": 0, "dim:SQ_RSRC_IMG_2D_ARRAY": 1, "dim:SQ_RSRC_IMG_CUBE": 1,
@@ -18965,6 +19049,7 @@ def _translate(path):
18965 user_sgpr_limit=user_limit, system_sgprs=sys_sgprs) 19049 user_sgpr_limit=user_limit, system_sgprs=sys_sgprs)
18966 g.fit_shared_memory() 19050 g.fit_shared_memory()
18967 end = next((k for k, ins in enumerate(insns) if base_op(ins["op"]) == "s_endpgm"), len(insns)) 19051 end = next((k for k, ins in enumerate(insns) if base_op(ins["op"]) == "s_endpgm"), len(insns))
19052 g.tsharp_from_heap = descriptor_sources.analyse([insns[:end]], [[]], user_limit, sys_sgprs)
18968 g.exec_changes = any(g.may_write_exec(ins) for ins in insns[:end]) 19053 g.exec_changes = any(g.may_write_exec(ins) for ins in insns[:end])
18969 g.insns(insns[:end]) 19054 g.insns(insns[:end])
18970 _translate.last_gen = g 19055 _translate.last_gen = g
@@ -19035,6 +19120,7 @@ def _translate(path):
19035 user_sgpr_limit=user_limit, system_sgprs=sys_sgprs) 19120 user_sgpr_limit=user_limit, system_sgprs=sys_sgprs)
19036 19121
19037 g.bar_rounds = needs_barrier_rounds(g, blocks, succ) 19122 g.bar_rounds = needs_barrier_rounds(g, blocks, succ)
19123 g.tsharp_from_heap = descriptor_sources.analyse(blocks, succ, user_limit, sys_sgprs)
19038 folds, fold_chain, absorbed = {}, {}, set() 19124 folds, fold_chain, absorbed = {}, {}, set()
19039 if g.emulate: 19125 if g.emulate:
19040 g.scc_live = wave64_emulate_opt.scc_live_outs(blocks, succ) 19126 g.scc_live = wave64_emulate_opt.scc_live_outs(blocks, succ)
@@ -19854,6 +19940,13 @@ def shader_meta(g, asm, src_path=None, fssm_path=None):
19854 # The module reads the kind word from every table entry it hits: the runtime must fill it 19940 # The module reads the kind word from every table entry it hits: the runtime must fill it
19855 # (runtime/src/descriptor_table.h, docs/design.md "Images and samplers (T# dimension)"). 19941 # (runtime/src/descriptor_table.h, docs/design.md "Images and samplers (T# dimension)").
19856 m["descriptor_table"] = g.descriptor_table 19942 m["descriptor_table"] = g.descriptor_table
19943 # Every module of this translator reads a T#'s bindless index from its dword 6 where the word carries one, so the
19944 # runtime must write that word into the heaps it keeps (docs/design.md, "Bindless index in the T#"). The counts
19945 # say how many image instructions take it alone and how many still look the T# up in the hash table too.
19946 m["tsharp_index"] = TSHARP_INDEX
19947 if g.tsharp_index_reads or g.tsharp_lookups:
19948 m["tsharp_index_reads"] = g.tsharp_index_reads
19949 m["tsharp_lookups"] = g.tsharp_lookups
19857 if g.w64g: 19950 if g.w64g:
19858 # SHADER-10: partition invariance on 32-wide subgroups. A and B are exact there (B: aggregated atomics up to 19951 # SHADER-10: partition invariance on 32-wide subgroups. A and B are exact there (B: aggregated atomics up to
19859 # the order of the slots), C is not; the reasons name the construct (docs/design.md, Wave64 graphics). 19952 # the order of the slots), C is not; the reasons name the construct (docs/design.md, Wave64 graphics).