diff options
| author | Tomgamer <tomanhorak22@gmail.com> | 2026-11-22 16:32:05 +0100 |
|---|---|---|
| committer | Tomgamer <tomanhorak22@gmail.com> | 2026-11-22 16:32:05 +0100 |
| commit | eb35aed2e7e8ea1d4a11fd4e42ab80d853f05169 (patch) | |
| tree | 22bd0e6fa6363235d1feedc1c9be678ab63bee4b /tests | |
| parent | 759a90c42e58886153f67dcd2d5d41c44face012 (diff) | |
| parent | 4eb6155d3ac4f9d3fadb0d095c4ce13e76783615 (diff) | |
Merge origin/main into shader-309-wave64-lds-limit
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Diffstat (limited to 'tests')
70 files changed, 8621 insertions, 112 deletions
diff --git a/tests/semantic/README.md b/tests/semantic/README.md index 65b741083..5244ec9b3 100644 --- a/tests/semantic/README.md +++ b/tests/semantic/README.md | |||
| @@ -35,6 +35,10 @@ What they check (`tools/rdna2spirv.py`, pixel shaders plus one compute shader): | |||
| 35 | RDNA2 ISA's swizzled buffer_offset and its OOB_SELECT 3 rule (docs/design.md Swizzled buffer addressing): the | 35 | RDNA2 ISA's swizzled buffer_offset and its OOB_SELECT 3 rule (docs/design.md Swizzled buffer addressing): the |
| 36 | exact addresses loaded and stored for dword, multi-dword and typed accesses, each with a literal and a run-time | 36 | exact addresses loaded and stored for dword, multi-dword and typed accesses, each with a literal and a run-time |
| 37 | V#, and the GPU fixture `cs_buf_swizzle` on 64 threads. | 37 | V#, and the GPU fixture `cs_buf_swizzle` on 64 threads. |
| 38 | - `test_tbuffer_store.py` runs the GPU test `cs_tbuffer_store` (13 `tbuffer_store_format_*` stores through V#s | ||
| 39 | whose format differs from the instruction's, or is 0) and asserts the 52 words `check.py` expects, measured natively on a | ||
| 40 | Radeon 680M; also the default `BUF_FMT_8_UNORM` byte, a format without an encoder staying `Unsupported`, and the | ||
| 41 | store's data VGPRs counting as reads. | ||
| 38 | - `test_scalar_mem_smem.py` runs the code `Gen.scalar_load` emits with its own small evaluator (64-bit | 42 | - `test_scalar_mem_smem.py` runs the code `Gen.scalar_load` emits with its own small evaluator (64-bit |
| 39 | addresses, forward selection constructs) and asserts the SGPR values and the addresses read, including the | 43 | addresses, forward selection constructs) and asserts the SGPR values and the addresses read, including the |
| 40 | measured SMEM truncation, `s_buffer_load` `NUM_RECORDS` bound and signed `s_load` immediate. | 44 | measured SMEM truncation, `s_buffer_load` `NUM_RECORDS` bound and signed `s_load` immediate. |
diff --git a/tests/semantic/fixtures/disasm/cs_tbuffer_store.s b/tests/semantic/fixtures/disasm/cs_tbuffer_store.s new file mode 100644 index 000000000..9f52a7b82 --- /dev/null +++ b/tests/semantic/fixtures/disasm/cs_tbuffer_store.s | |||
| @@ -0,0 +1,233 @@ | |||
| 1 | ; cs_tbuffer_store test fixture generated by tests/semantic/regen_fixtures.py from runtime/test/shaders/cs_tbuffer_store.asm | ||
| 2 | v_cmpx_eq_u32_e32 0, v0 | ||
| 3 | v_mov_b32_e32 v1, 0xa5a50200 | ||
| 4 | v_mov_b32_e32 v2, 0xa5a50204 | ||
| 5 | v_mov_b32_e32 v3, 0xa5a50208 | ||
| 6 | v_mov_b32_e32 v4, 0xa5a5020c | ||
| 7 | v_mov_b32_e32 v5, 0x200 | ||
| 8 | buffer_store_dwordx4 v[1:4], v5, s[0:3], 0 offen | ||
| 9 | v_mov_b32_e32 v1, 0xa5a50210 | ||
| 10 | v_mov_b32_e32 v2, 0xa5a50214 | ||
| 11 | v_mov_b32_e32 v3, 0xa5a50218 | ||
| 12 | v_mov_b32_e32 v4, 0xa5a5021c | ||
| 13 | v_mov_b32_e32 v5, 0x210 | ||
| 14 | buffer_store_dwordx4 v[1:4], v5, s[0:3], 0 offen | ||
| 15 | v_mov_b32_e32 v1, 0xa5a50220 | ||
| 16 | v_mov_b32_e32 v2, 0xa5a50224 | ||
| 17 | v_mov_b32_e32 v3, 0xa5a50228 | ||
| 18 | v_mov_b32_e32 v4, 0xa5a5022c | ||
| 19 | v_mov_b32_e32 v5, 0x220 | ||
| 20 | buffer_store_dwordx4 v[1:4], v5, s[0:3], 0 offen | ||
| 21 | v_mov_b32_e32 v1, 0xa5a50230 | ||
| 22 | v_mov_b32_e32 v2, 0xa5a50234 | ||
| 23 | v_mov_b32_e32 v3, 0xa5a50238 | ||
| 24 | v_mov_b32_e32 v4, 0xa5a5023c | ||
| 25 | v_mov_b32_e32 v5, 0x230 | ||
| 26 | buffer_store_dwordx4 v[1:4], v5, s[0:3], 0 offen | ||
| 27 | v_mov_b32_e32 v1, 0xa5a50240 | ||
| 28 | v_mov_b32_e32 v2, 0xa5a50244 | ||
| 29 | v_mov_b32_e32 v3, 0xa5a50248 | ||
| 30 | v_mov_b32_e32 v4, 0xa5a5024c | ||
| 31 | v_mov_b32_e32 v5, 0x240 | ||
| 32 | buffer_store_dwordx4 v[1:4], v5, s[0:3], 0 offen | ||
| 33 | v_mov_b32_e32 v1, 0xa5a50250 | ||
| 34 | v_mov_b32_e32 v2, 0xa5a50254 | ||
| 35 | v_mov_b32_e32 v3, 0xa5a50258 | ||
| 36 | v_mov_b32_e32 v4, 0xa5a5025c | ||
| 37 | v_mov_b32_e32 v5, 0x250 | ||
| 38 | buffer_store_dwordx4 v[1:4], v5, s[0:3], 0 offen | ||
| 39 | v_mov_b32_e32 v1, 0xa5a50260 | ||
| 40 | v_mov_b32_e32 v2, 0xa5a50264 | ||
| 41 | v_mov_b32_e32 v3, 0xa5a50268 | ||
| 42 | v_mov_b32_e32 v4, 0xa5a5026c | ||
| 43 | v_mov_b32_e32 v5, 0x260 | ||
| 44 | buffer_store_dwordx4 v[1:4], v5, s[0:3], 0 offen | ||
| 45 | v_mov_b32_e32 v1, 0xa5a50270 | ||
| 46 | v_mov_b32_e32 v2, 0xa5a50274 | ||
| 47 | v_mov_b32_e32 v3, 0xa5a50278 | ||
| 48 | v_mov_b32_e32 v4, 0xa5a5027c | ||
| 49 | v_mov_b32_e32 v5, 0x270 | ||
| 50 | buffer_store_dwordx4 v[1:4], v5, s[0:3], 0 offen | ||
| 51 | v_mov_b32_e32 v1, 0xa5a50280 | ||
| 52 | v_mov_b32_e32 v2, 0xa5a50284 | ||
| 53 | v_mov_b32_e32 v3, 0xa5a50288 | ||
| 54 | v_mov_b32_e32 v4, 0xa5a5028c | ||
| 55 | v_mov_b32_e32 v5, 0x280 | ||
| 56 | buffer_store_dwordx4 v[1:4], v5, s[0:3], 0 offen | ||
| 57 | v_mov_b32_e32 v1, 0xa5a50290 | ||
| 58 | v_mov_b32_e32 v2, 0xa5a50294 | ||
| 59 | v_mov_b32_e32 v3, 0xa5a50298 | ||
| 60 | v_mov_b32_e32 v4, 0xa5a5029c | ||
| 61 | v_mov_b32_e32 v5, 0x290 | ||
| 62 | buffer_store_dwordx4 v[1:4], v5, s[0:3], 0 offen | ||
| 63 | v_mov_b32_e32 v1, 0xa5a502a0 | ||
| 64 | v_mov_b32_e32 v2, 0xa5a502a4 | ||
| 65 | v_mov_b32_e32 v3, 0xa5a502a8 | ||
| 66 | v_mov_b32_e32 v4, 0xa5a502ac | ||
| 67 | v_mov_b32_e32 v5, 0x2a0 | ||
| 68 | buffer_store_dwordx4 v[1:4], v5, s[0:3], 0 offen | ||
| 69 | v_mov_b32_e32 v1, 0xa5a502b0 | ||
| 70 | v_mov_b32_e32 v2, 0xa5a502b4 | ||
| 71 | v_mov_b32_e32 v3, 0xa5a502b8 | ||
| 72 | v_mov_b32_e32 v4, 0xa5a502bc | ||
| 73 | v_mov_b32_e32 v5, 0x2b0 | ||
| 74 | buffer_store_dwordx4 v[1:4], v5, s[0:3], 0 offen | ||
| 75 | v_mov_b32_e32 v1, 0xa5a502c0 | ||
| 76 | v_mov_b32_e32 v2, 0xa5a502c4 | ||
| 77 | v_mov_b32_e32 v3, 0xa5a502c8 | ||
| 78 | v_mov_b32_e32 v4, 0xa5a502cc | ||
| 79 | v_mov_b32_e32 v5, 0x2c0 | ||
| 80 | buffer_store_dwordx4 v[1:4], v5, s[0:3], 0 offen | ||
| 81 | s_waitcnt_vscnt null, 0x0 | ||
| 82 | s_mov_b32 s4, s0 | ||
| 83 | s_mov_b32 s5, s1 | ||
| 84 | v_mov_b32_e32 v20, 0x3f800000 | ||
| 85 | v_mov_b32_e32 v21, 0x40000000 | ||
| 86 | v_mov_b32_e32 v22, 0x40400000 | ||
| 87 | v_mov_b32_e32 v23, 0x40800000 | ||
| 88 | s_mov_b32 s6, 0xffffffff | ||
| 89 | s_mov_b32 s7, 0x31016fac | ||
| 90 | v_mov_b32_e32 v5, 0x200 | ||
| 91 | tbuffer_store_format_xyzw v[20:23], v5, s[4:7], 0 format:[BUF_FMT_32_32_32_32_FLOAT] offen | ||
| 92 | v_mov_b32_e32 v20, 0x3f800000 | ||
| 93 | v_mov_b32_e32 v21, 0x40000000 | ||
| 94 | s_mov_b32 s6, 0xffffffff | ||
| 95 | s_mov_b32 s7, 0x3104dfac | ||
| 96 | v_mov_b32_e32 v5, 0x210 | ||
| 97 | tbuffer_store_format_xy v[20:21], v5, s[4:7], 0 format:[BUF_FMT_16_16_16_16_FLOAT] offen | ||
| 98 | v_mov_b32_e32 v20, 0x1 | ||
| 99 | v_mov_b32_e32 v21, 0x2 | ||
| 100 | v_mov_b32_e32 v22, 0x3 | ||
| 101 | s_mov_b32 s6, 0xffffffff | ||
| 102 | s_mov_b32 s7, 0x31016fac | ||
| 103 | v_mov_b32_e32 v5, 0x220 | ||
| 104 | tbuffer_store_format_xyz v[20:22], v5, s[4:7], 0 format:[BUF_FMT_8_8_8_8_UINT] offen | ||
| 105 | v_mov_b32_e32 v20, 0x3f800000 | ||
| 106 | s_mov_b32 s6, 0xffffffff | ||
| 107 | s_mov_b32 s7, 0x3104dfac | ||
| 108 | v_mov_b32_e32 v5, 0x231 | ||
| 109 | tbuffer_store_format_x v20, v5, s[4:7], 0 offen | ||
| 110 | v_mov_b32_e32 v20, 0x40000000 | ||
| 111 | s_mov_b32 s6, 0xffffffff | ||
| 112 | s_mov_b32 s7, 0x31016fac | ||
| 113 | v_mov_b32_e32 v5, 0x242 | ||
| 114 | tbuffer_store_format_x v20, v5, s[4:7], 0 format:[BUF_FMT_16_FLOAT] offen | ||
| 115 | v_mov_b32_e32 v20, 0x3f800000 | ||
| 116 | v_mov_b32_e32 v21, 0x0 | ||
| 117 | v_mov_b32_e32 v22, 0x3e800000 | ||
| 118 | v_mov_b32_e32 v23, 0x3f800000 | ||
| 119 | s_mov_b32 s6, 0xffffffff | ||
| 120 | s_mov_b32 s7, 0x31016fac | ||
| 121 | v_mov_b32_e32 v5, 0x250 | ||
| 122 | tbuffer_store_format_xyzw v[20:23], v5, s[4:7], 0 format:[BUF_FMT_2_10_10_10_UNORM] offen | ||
| 123 | v_mov_b32_e32 v20, 0x3f800000 | ||
| 124 | v_mov_b32_e32 v21, 0x40000000 | ||
| 125 | v_mov_b32_e32 v22, 0x40400000 | ||
| 126 | v_mov_b32_e32 v23, 0x40800000 | ||
| 127 | s_mov_b32 s6, 0xffffffff | ||
| 128 | s_mov_b32 s7, 0x3104dfac | ||
| 129 | v_mov_b32_e32 v5, 0x260 | ||
| 130 | tbuffer_store_format_xyzw v[20:23], v5, s[4:7], 0 format:[BUF_FMT_32_32_FLOAT] offen | ||
| 131 | v_mov_b32_e32 v20, 0x40003c00 | ||
| 132 | s_mov_b32 s6, 0xffffffff | ||
| 133 | s_mov_b32 s7, 0x3104dfac | ||
| 134 | v_mov_b32_e32 v5, 0x270 | ||
| 135 | tbuffer_store_format_d16_xy v20, v5, s[4:7], 0 format:[BUF_FMT_16_16_FLOAT] offen | ||
| 136 | v_mov_b32_e32 v20, 0x38003c00 | ||
| 137 | v_mov_b32_e32 v21, 0x3c000000 | ||
| 138 | s_mov_b32 s6, 0xffffffff | ||
| 139 | s_mov_b32 s7, 0x31016fac | ||
| 140 | v_mov_b32_e32 v5, 0x280 | ||
| 141 | tbuffer_store_format_d16_xyzw v[20:21], v5, s[4:7], 0 format:[BUF_FMT_8_8_8_8_UNORM] offen | ||
| 142 | v_mov_b32_e32 v20, 0x3f800000 | ||
| 143 | v_mov_b32_e32 v21, 0x40000000 | ||
| 144 | s_mov_b32 s6, 0x298 | ||
| 145 | s_mov_b32 s7, 0x31016fac | ||
| 146 | v_mov_b32_e32 v5, 0x290 | ||
| 147 | tbuffer_store_format_xy v[20:21], v5, s[4:7], 0 format:[BUF_FMT_32_32_32_32_FLOAT] offen | ||
| 148 | v_mov_b32_e32 v20, 0x3f800000 | ||
| 149 | s_mov_b32 s6, 0x2a1 | ||
| 150 | s_mov_b32 s7, 0x3104dfac | ||
| 151 | v_mov_b32_e32 v5, 0x2a0 | ||
| 152 | tbuffer_store_format_x v20, v5, s[4:7], 0 format:[BUF_FMT_8_UNORM] offen | ||
| 153 | v_mov_b32_e32 v20, 0x3f800000 | ||
| 154 | v_mov_b32_e32 v21, 0x40000000 | ||
| 155 | v_mov_b32_e32 v22, 0x40400000 | ||
| 156 | v_mov_b32_e32 v23, 0x40800000 | ||
| 157 | s_mov_b32 s6, 0xffffffff | ||
| 158 | s_mov_b32 s7, 0x3104dfac | ||
| 159 | v_mov_b32_e32 v5, 0x2b0 | ||
| 160 | tbuffer_store_format_xyzw v[20:23], v5, s[4:7], 0 format:[BUF_FMT_32_FLOAT] offen | ||
| 161 | v_mov_b32_e32 v20, 0x3f800000 | ||
| 162 | v_mov_b32_e32 v21, 0x40000000 | ||
| 163 | s_mov_b32 s6, 0xffffffff | ||
| 164 | s_mov_b32 s7, 0x31000fac | ||
| 165 | v_mov_b32_e32 v5, 0x2c0 | ||
| 166 | tbuffer_store_format_xy v[20:21], v5, s[4:7], 0 format:[BUF_FMT_32_32_FLOAT] offen | ||
| 167 | s_waitcnt_vscnt null, 0x0 | ||
| 168 | v_mov_b32_e32 v5, 0x200 | ||
| 169 | buffer_load_dwordx4 v[10:13], v5, s[0:3], 0 offen | ||
| 170 | s_waitcnt vmcnt(0) | ||
| 171 | v_mov_b32_e32 v6, 0x0 | ||
| 172 | buffer_store_dwordx4 v[10:13], v6, s[0:3], 0 offen | ||
| 173 | v_mov_b32_e32 v5, 0x210 | ||
| 174 | buffer_load_dwordx4 v[10:13], v5, s[0:3], 0 offen | ||
| 175 | s_waitcnt vmcnt(0) | ||
| 176 | v_mov_b32_e32 v6, 0x10 | ||
| 177 | buffer_store_dwordx4 v[10:13], v6, s[0:3], 0 offen | ||
| 178 | v_mov_b32_e32 v5, 0x220 | ||
| 179 | buffer_load_dwordx4 v[10:13], v5, s[0:3], 0 offen | ||
| 180 | s_waitcnt vmcnt(0) | ||
| 181 | v_mov_b32_e32 v6, 0x20 | ||
| 182 | buffer_store_dwordx4 v[10:13], v6, s[0:3], 0 offen | ||
| 183 | v_mov_b32_e32 v5, 0x230 | ||
| 184 | buffer_load_dwordx4 v[10:13], v5, s[0:3], 0 offen | ||
| 185 | s_waitcnt vmcnt(0) | ||
| 186 | v_mov_b32_e32 v6, 0x30 | ||
| 187 | buffer_store_dwordx4 v[10:13], v6, s[0:3], 0 offen | ||
| 188 | v_mov_b32_e32 v5, 0x240 | ||
| 189 | buffer_load_dwordx4 v[10:13], v5, s[0:3], 0 offen | ||
| 190 | s_waitcnt vmcnt(0) | ||
| 191 | v_mov_b32_e32 v6, 0x40 | ||
| 192 | buffer_store_dwordx4 v[10:13], v6, s[0:3], 0 offen | ||
| 193 | v_mov_b32_e32 v5, 0x250 | ||
| 194 | buffer_load_dwordx4 v[10:13], v5, s[0:3], 0 offen | ||
| 195 | s_waitcnt vmcnt(0) | ||
| 196 | v_mov_b32_e32 v6, 0x50 | ||
| 197 | buffer_store_dwordx4 v[10:13], v6, s[0:3], 0 offen | ||
| 198 | v_mov_b32_e32 v5, 0x260 | ||
| 199 | buffer_load_dwordx4 v[10:13], v5, s[0:3], 0 offen | ||
| 200 | s_waitcnt vmcnt(0) | ||
| 201 | v_mov_b32_e32 v6, 0x60 | ||
| 202 | buffer_store_dwordx4 v[10:13], v6, s[0:3], 0 offen | ||
| 203 | v_mov_b32_e32 v5, 0x270 | ||
| 204 | buffer_load_dwordx4 v[10:13], v5, s[0:3], 0 offen | ||
| 205 | s_waitcnt vmcnt(0) | ||
| 206 | v_mov_b32_e32 v6, 0x70 | ||
| 207 | buffer_store_dwordx4 v[10:13], v6, s[0:3], 0 offen | ||
| 208 | v_mov_b32_e32 v5, 0x280 | ||
| 209 | buffer_load_dwordx4 v[10:13], v5, s[0:3], 0 offen | ||
| 210 | s_waitcnt vmcnt(0) | ||
| 211 | v_mov_b32_e32 v6, 0x80 | ||
| 212 | buffer_store_dwordx4 v[10:13], v6, s[0:3], 0 offen | ||
| 213 | v_mov_b32_e32 v5, 0x290 | ||
| 214 | buffer_load_dwordx4 v[10:13], v5, s[0:3], 0 offen | ||
| 215 | s_waitcnt vmcnt(0) | ||
| 216 | v_mov_b32_e32 v6, 0x90 | ||
| 217 | buffer_store_dwordx4 v[10:13], v6, s[0:3], 0 offen | ||
| 218 | v_mov_b32_e32 v5, 0x2a0 | ||
| 219 | buffer_load_dwordx4 v[10:13], v5, s[0:3], 0 offen | ||
| 220 | s_waitcnt vmcnt(0) | ||
| 221 | v_mov_b32_e32 v6, 0xa0 | ||
| 222 | buffer_store_dwordx4 v[10:13], v6, s[0:3], 0 offen | ||
| 223 | v_mov_b32_e32 v5, 0x2b0 | ||
| 224 | buffer_load_dwordx4 v[10:13], v5, s[0:3], 0 offen | ||
| 225 | s_waitcnt vmcnt(0) | ||
| 226 | v_mov_b32_e32 v6, 0xb0 | ||
| 227 | buffer_store_dwordx4 v[10:13], v6, s[0:3], 0 offen | ||
| 228 | v_mov_b32_e32 v5, 0x2c0 | ||
| 229 | buffer_load_dwordx4 v[10:13], v5, s[0:3], 0 offen | ||
| 230 | s_waitcnt vmcnt(0) | ||
| 231 | v_mov_b32_e32 v6, 0xc0 | ||
| 232 | buffer_store_dwordx4 v[10:13], v6, s[0:3], 0 offen | ||
| 233 | s_endpgm | ||
diff --git a/tests/semantic/regen_fixtures.py b/tests/semantic/regen_fixtures.py index a7c9cb696..28a6fa232 100644 --- a/tests/semantic/regen_fixtures.py +++ b/tests/semantic/regen_fixtures.py | |||
| @@ -26,6 +26,7 @@ SHADERS = ("cs_smem_bounds", "cs_smem_stride_align", "cs_smem_sload_neg", "cs_bu | |||
| 26 | "ps_f32_mods", "ps_f64_mods", "ps_sff_imm", "cs_w32_lds_u8_d16", "cs_w32_lane_wrap", "ps_bary", | 26 | "ps_f32_mods", "ps_f64_mods", "ps_sff_imm", "cs_w32_lds_u8_d16", "cs_w32_lane_wrap", "ps_bary", |
| 27 | "cs_oob_select", "cs_oob_tail", "cs_w32_mask_imm", "cs_w64_mask_imm", | 27 | "cs_oob_select", "cs_oob_tail", "cs_w32_mask_imm", "cs_w64_mask_imm", |
| 28 | "cs_buf_swizzle", # swizzled MUBUF / ADD_TID (test_buffer_swizzle.py) | 28 | "cs_buf_swizzle", # swizzled MUBUF / ADD_TID (test_buffer_swizzle.py) |
| 29 | "cs_tbuffer_store", # tbuffer_store_format_*, words measured natively on a Radeon 680M | ||
| 29 | # TEST-175: GPU fixtures for the docs/design.md rules that were checked on the CPU only | 30 | # TEST-175: GPU fixtures for the docs/design.md rules that were checked on the CPU only |
| 30 | "ps_cmp_nlg", "ps_cvt_off", "ps_fmac_f16_mods", "ps_vop3_const_mods", "ps_interp_f32_mods", "ps_interp_mov_mods", | 31 | "ps_cmp_nlg", "ps_cvt_off", "ps_fmac_f16_mods", "ps_vop3_const_mods", "ps_interp_f32_mods", "ps_interp_mov_mods", |
| 31 | "ps_f16_pack_mods", # v_pack_b32_f16 neg/abs (SHADER-260) | 32 | "ps_f16_pack_mods", # v_pack_b32_f16 neg/abs (SHADER-260) |
diff --git a/tests/semantic/spirv_mini_interp.py b/tests/semantic/spirv_mini_interp.py index b288e42f7..3afc81c69 100644 --- a/tests/semantic/spirv_mini_interp.py +++ b/tests/semantic/spirv_mini_interp.py | |||
| @@ -43,13 +43,29 @@ class InvalidModule(AssertionError): | |||
| 43 | 43 | ||
| 44 | 44 | ||
| 45 | def check_structure(body): | 45 | def check_structure(body): |
| 46 | """spirv-val's merge rule (SPIR-V 2.16.2): OpSelectionMerge must be the second-to-last instruction of its block, | 46 | """spirv-val's merge, phi and Function-variable rules (SPIR-V 2.16.1-2): OpSelectionMerge must be the second-to-last instruction of its block, |
| 47 | directly before OpBranchConditional or OpSwitch, and OpLoopMerge directly before OpBranch or | 47 | directly before OpBranchConditional or OpSwitch, and OpLoopMerge directly before OpBranch or |
| 48 | OpBranchConditional. Until 2026-11-22 the interpreter skipped merges, so a translator change that put an | 48 | OpBranchConditional. Until 2026-11-22 the interpreter skipped merges, so a translator change that put an |
| 49 | instruction between a merge and its branch (#1633: OpLoad %active) passed every semantic test while every | 49 | instruction between a merge and its branch (#1633: OpLoad %active) passed every semantic test while every |
| 50 | driver rejected the module. `body` is the list of (result, opcode, operands, line) of a function.""" | 50 | driver rejected the module. `body` is the list of (result, opcode, operands, line) of a function.""" |
| 51 | follow = {"OpSelectionMerge": ("OpBranchConditional", "OpSwitch"), | 51 | follow = {"OpSelectionMerge": ("OpBranchConditional", "OpSwitch"), |
| 52 | "OpLoopMerge": ("OpBranch", "OpBranchConditional")} | 52 | "OpLoopMerge": ("OpBranch", "OpBranchConditional")} |
| 53 | # OpPhi must come first in its block: only OpLabel or other OpPhi before it (SPIR-V 2.16.2, "OpPhi ... must be | ||
| 54 | # the first instructions of a block"). A phi emitted after an instruction of the merge block is rejected by | ||
| 55 | # spirv-val, and every translator path that merges a guarded load (OpPhi of the loaded and the kept value) | ||
| 56 | # depends on the order. | ||
| 57 | # Function-storage OpVariable belongs in the function's first block (SPIR-V 2.16.1). | ||
| 58 | prev, blocks = None, 0 | ||
| 59 | for _, op, a, line in body: | ||
| 60 | if op == "OpPhi" and prev not in ("OpLabel", "OpPhi"): | ||
| 61 | raise InvalidModule(f"{line!r} follows {prev or 'the start of the function'}, not OpLabel or OpPhi") | ||
| 62 | if op == "OpFunction": | ||
| 63 | blocks = 0 | ||
| 64 | elif op == "OpLabel": | ||
| 65 | blocks += 1 | ||
| 66 | elif op == "OpVariable" and a[1:2] == ["Function"] and blocks > 1: | ||
| 67 | raise InvalidModule(f"{line!r} is a Function variable outside the function's first block") | ||
| 68 | prev = op | ||
| 53 | for k, (_, op, _, line) in enumerate(body): | 69 | for k, (_, op, _, line) in enumerate(body): |
| 54 | if op in follow: | 70 | if op in follow: |
| 55 | nxt = body[k + 1][1] if k + 1 < len(body) else None | 71 | nxt = body[k + 1][1] if k + 1 < len(body) else None |
| @@ -867,18 +883,6 @@ def _invocation(text, inputs, push_constants, memory, step=False): | |||
| 867 | values[res] = fma_f32(x, y, z) | 883 | values[res] = fma_f32(x, y, z) |
| 868 | elif op == "OpFNegate": | 884 | elif op == "OpFNegate": |
| 869 | values[res] = f32(-val(a[1])) | 885 | values[res] = f32(-val(a[1])) |
| 870 | elif op == "OpFDiv": | ||
| 871 | x, y = val(a[1]), val(a[2]) | ||
| 872 | if not (isinstance(x, float) and isinstance(y, float)): | ||
| 873 | raise UnsupportedConstruct("OpFDiv on non-float") | ||
| 874 | if y == 0.0: | ||
| 875 | raise UnsupportedConstruct("OpFDiv by zero (undefined in SPIR-V)") | ||
| 876 | if math.isinf(x) and math.isinf(y): | ||
| 877 | values[res] = math.nan | ||
| 878 | elif math.isnan(x) or math.isnan(y): | ||
| 879 | values[res] = math.nan | ||
| 880 | else: | ||
| 881 | values[res] = f32(x / y) # x/inf is a signed zero, as in Python | ||
| 882 | elif op == "OpQuantizeToF16": | 886 | elif op == "OpQuantizeToF16": |
| 883 | # Single-instruction f32 -> f16 -> f32 round to nearest, with the | 887 | # Single-instruction f32 -> f16 -> f32 round to nearest, with the |
| 884 | # SPIR-V subnormal rule: a magnitude too small for a normal f16 | 888 | # SPIR-V subnormal rule: a magnitude too small for a normal f16 |
diff --git a/tests/semantic/spirv_wave_interp.py b/tests/semantic/spirv_wave_interp.py index a3adf6544..0331c7b37 100644 --- a/tests/semantic/spirv_wave_interp.py +++ b/tests/semantic/spirv_wave_interp.py | |||
| @@ -160,7 +160,12 @@ class _Module: | |||
| 160 | raise UnsupportedConstruct(f"{op} before the first label") | 160 | raise UnsupportedConstruct(f"{op} before the first label") |
| 161 | if res and a and op != "OpStore": | 161 | if res and a and op != "OpStore": |
| 162 | self.id_type[res] = a[0] | 162 | self.id_type[res] = a[0] |
| 163 | if op == "OpVariable" and a[1:2] == ["Function"] and len(self.blocks) > 1: | ||
| 164 | raise InvalidModule(f"{line!r} is a Function variable outside the function's first block") | ||
| 163 | if op == "OpPhi": | 165 | if op == "OpPhi": |
| 166 | if cur.body: | ||
| 167 | raise InvalidModule(f"{line!r} follows a non-phi instruction of its block (spirv-val: " | ||
| 168 | "OpPhi must come first)") | ||
| 164 | cur.phis.append((res, a)) | 169 | cur.phis.append((res, a)) |
| 165 | elif op in ("OpSelectionMerge", "OpLoopMerge"): | 170 | elif op in ("OpSelectionMerge", "OpLoopMerge"): |
| 166 | cur.merge = (op, a[0], a[1] if op == "OpLoopMerge" else None) | 171 | cur.merge = (op, a[0], a[1] if op == "OpLoopMerge" else None) |
diff --git a/tests/semantic/test_alu_add_co_clamp.py b/tests/semantic/test_alu_add_co_clamp.py new file mode 100644 index 000000000..b39b8b26e --- /dev/null +++ b/tests/semantic/test_alu_add_co_clamp.py | |||
| @@ -0,0 +1,183 @@ | |||
| 1 | """Semantic interpreter tests for VOP3 clamp on RDNA2 carry-out u32 add/sub ops. | ||
| 2 | |||
| 3 | Covers all six carry-out forms: v_add_co_u32, v_sub_co_u32, v_subrev_co_u32, v_add_co_ci_u32, v_sub_co_ci_u32, | ||
| 4 | and v_subrev_co_ci_u32. With VOP3 `clamp`, RDNA2 hardware (measured natively on gfx1035 and gfx1036, wave32 & | ||
| 5 | wave64) saturates D to 0xFFFFFFFF on add carry or 0 on sub borrow while still writing the real carry/borrow bit | ||
| 6 | into sdst (0 for inactive EXEC lanes). Without `clamp`, D wraps at 32 bits. No game files. | ||
| 7 | """ | ||
| 8 | import os | ||
| 9 | import random | ||
| 10 | import struct | ||
| 11 | import sys | ||
| 12 | import tempfile | ||
| 13 | import unittest | ||
| 14 | import warnings | ||
| 15 | |||
| 16 | HERE = os.path.dirname(os.path.abspath(__file__)) | ||
| 17 | ROOT = os.path.dirname(os.path.dirname(HERE)) | ||
| 18 | TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") | ||
| 19 | |||
| 20 | sys.dont_write_bytecode = True | ||
| 21 | sys.path.insert(0, TOOLS_DIR) | ||
| 22 | sys.path.insert(0, HERE) | ||
| 23 | |||
| 24 | import rdna2spirv # noqa: E402 | ||
| 25 | import spirv_mini_interp as si # noqa: E402 | ||
| 26 | |||
| 27 | M32 = 0xFFFFFFFF | ||
| 28 | STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("<I", 0) + bytes(4) | ||
| 29 | |||
| 30 | CO_OPS = ("v_add_co_u32", "v_sub_co_u32", "v_subrev_co_u32") | ||
| 31 | CO_CI_OPS = ("v_add_co_ci_u32", "v_sub_co_ci_u32", "v_subrev_co_ci_u32") | ||
| 32 | EDGE_PAIRS = ( | ||
| 33 | (0, 0), | ||
| 34 | (0, 1), | ||
| 35 | (1, 0), | ||
| 36 | (5, 10), | ||
| 37 | (10, 5), | ||
| 38 | (5, 4), | ||
| 39 | (0xFFFFFFFF, 0), | ||
| 40 | (0, 0xFFFFFFFF), | ||
| 41 | (0xFFFFFFFF, 1), | ||
| 42 | (0xFFFFFFFF, 0xFFFFFFFF), | ||
| 43 | (0x80000000, 0x80000000), | ||
| 44 | (0x7FFFFFFF, 0x80000000), | ||
| 45 | ) | ||
| 46 | |||
| 47 | _TMP_DIR = None | ||
| 48 | _SRC_PATH = None | ||
| 49 | |||
| 50 | |||
| 51 | def setUpModule(): | ||
| 52 | global _TMP_DIR, _SRC_PATH | ||
| 53 | _TMP_DIR = tempfile.TemporaryDirectory() | ||
| 54 | disasm_dir = os.path.join(_TMP_DIR.name, "disasm") | ||
| 55 | os.mkdir(disasm_dir) | ||
| 56 | _SRC_PATH = os.path.join(disasm_dir, "ps_add_co_clamp.s") | ||
| 57 | with open(os.path.join(_TMP_DIR.name, "ps_add_co_clamp.dxbc"), "wb") as f: | ||
| 58 | f.write(STUB_DXBC) | ||
| 59 | |||
| 60 | |||
| 61 | def tearDownModule(): | ||
| 62 | global _TMP_DIR | ||
| 63 | if _TMP_DIR is not None: | ||
| 64 | _TMP_DIR.cleanup() | ||
| 65 | _TMP_DIR = None | ||
| 66 | |||
| 67 | |||
| 68 | def ref(op: str, x: int, y: int, cin: int, clamp: bool) -> tuple[int, int]: | ||
| 69 | x, y = x & M32, y & M32 | ||
| 70 | if op.startswith("v_subrev_co"): | ||
| 71 | x, y = y, x | ||
| 72 | sub = "sub" in op | ||
| 73 | c = (1 if cin else 0) if op.endswith("ci_u32") else 0 | ||
| 74 | if sub: | ||
| 75 | full = x - y - c | ||
| 76 | carry = 1 if full < 0 else 0 | ||
| 77 | res = 0 if (clamp and carry) else (full & M32) | ||
| 78 | else: | ||
| 79 | full = x + y + c | ||
| 80 | carry = 1 if full > M32 else 0 | ||
| 81 | res = M32 if (clamp and carry) else (full & M32) | ||
| 82 | return res, carry | ||
| 83 | |||
| 84 | |||
| 85 | def run_case(op: str, x: int, y: int, cin: int, clamp: bool, cd: str = "vcc_lo") -> tuple[int, int]: | ||
| 86 | if _TMP_DIR is None: | ||
| 87 | setUpModule() | ||
| 88 | mod = " clamp" if clamp else "" | ||
| 89 | lines = [ | ||
| 90 | f"v_mov_b32 v1, {x:#x}", | ||
| 91 | f"v_mov_b32 v2, {y:#x}", | ||
| 92 | f"s_mov_b32 vcc_lo, {-1 if cin else 0}", | ||
| 93 | ] | ||
| 94 | if op.endswith("ci_u32"): | ||
| 95 | lines.append(f"{op}_e64 v0, {cd}, v1, v2, vcc_lo{mod}") | ||
| 96 | else: | ||
| 97 | lines.append(f"{op} v0, {cd}, v1, v2{mod}") | ||
| 98 | if cd == "null": | ||
| 99 | lines.append("v_mov_b32 v7, 0") | ||
| 100 | else: | ||
| 101 | lines.append(f"v_cndmask_b32_e64 v7, 0, 1, {cd}") | ||
| 102 | lines += [ | ||
| 103 | "v_and_b32 v5, 0xffff, v0", | ||
| 104 | "v_lshrrev_b32 v6, 16, v0", | ||
| 105 | "v_or_b32 v5, 0x40000000, v5", | ||
| 106 | "v_or_b32 v6, 0x40000000, v6", | ||
| 107 | "v_or_b32 v7, 0x40000000, v7", | ||
| 108 | ] | ||
| 109 | asm = "; test_add_co_clamp\n" + "".join(f"\t{ln}\n" for ln in lines) + "\texp mrt0 v5, v6, v7, v5 done vm\n\ts_endpgm\n" | ||
| 110 | with open(_SRC_PATH, "w", encoding="utf-8", newline="\n") as f: | ||
| 111 | f.write(asm) | ||
| 112 | with warnings.catch_warnings(): | ||
| 113 | warnings.simplefilter("ignore", ResourceWarning) | ||
| 114 | spv = rdna2spirv.translate(_SRC_PATH) | ||
| 115 | lo, hi, cword = si.run_fragment(spv)["%out_mrt0"][:3] | ||
| 116 | assert lo >> 16 == 0x4000 and hi >> 16 == 0x4000 and cword >> 16 == 0x4000, (hex(lo), hex(hi), hex(cword)) | ||
| 117 | return (lo & 0xFFFF) | ((hi & 0xFFFF) << 16), cword & 1 | ||
| 118 | |||
| 119 | |||
| 120 | class AddCoClampTests(unittest.TestCase): | ||
| 121 | def test_edge_pairs_all_six_ops(self): | ||
| 122 | for op in CO_OPS: | ||
| 123 | for clamp in (False, True): | ||
| 124 | for x, y in EDGE_PAIRS: | ||
| 125 | self.assertEqual(run_case(op, x, y, 0, clamp), ref(op, x, y, 0, clamp), | ||
| 126 | (op, hex(x), hex(y), clamp)) | ||
| 127 | for op in CO_CI_OPS: | ||
| 128 | for clamp in (False, True): | ||
| 129 | for cin in (0, 1): | ||
| 130 | for x, y in EDGE_PAIRS: | ||
| 131 | self.assertEqual(run_case(op, x, y, cin, clamp), ref(op, x, y, cin, clamp), | ||
| 132 | (op, hex(x), hex(y), cin, clamp)) | ||
| 133 | |||
| 134 | def test_null_and_sgpr_carry_dests(self): | ||
| 135 | for op in ("v_add_co_u32", "v_sub_co_u32", "v_add_co_ci_u32", "v_sub_co_ci_u32"): | ||
| 136 | x, y, cin = (0xFFFFFFFF, 1, 1) if "add" in op else (0, 1, 1) | ||
| 137 | want_d, want_c = ref(op, x, y, cin, True) | ||
| 138 | got_d, _ = run_case(op, x, y, cin, True, cd="null") | ||
| 139 | self.assertEqual(got_d, want_d, (op, "null")) | ||
| 140 | self.assertEqual(run_case(op, x, y, cin, True, cd="s12"), (want_d, want_c), (op, "s12")) | ||
| 141 | |||
| 142 | def test_inactive_exec_lane(self): | ||
| 143 | if _TMP_DIR is None: | ||
| 144 | setUpModule() | ||
| 145 | lines = [ | ||
| 146 | "v_mov_b32 v0, 0x12345678", | ||
| 147 | "v_mov_b32 v1, 0xffffffff", | ||
| 148 | "v_mov_b32 v2, 0xffffffff", | ||
| 149 | "s_mov_b32 vcc_lo, -1", | ||
| 150 | "s_mov_b32 s10, exec_lo", | ||
| 151 | "s_mov_b32 exec_lo, 0", | ||
| 152 | "v_add_co_u32 v0, vcc_lo, v1, v2 clamp", | ||
| 153 | "s_mov_b32 exec_lo, s10", | ||
| 154 | "v_cndmask_b32_e64 v7, 0, 1, vcc_lo", | ||
| 155 | "v_and_b32 v5, 0xffff, v0", | ||
| 156 | "v_lshrrev_b32 v6, 16, v0", | ||
| 157 | "v_or_b32 v5, 0x40000000, v5", | ||
| 158 | "v_or_b32 v6, 0x40000000, v6", | ||
| 159 | "v_or_b32 v7, 0x40000000, v7", | ||
| 160 | ] | ||
| 161 | asm = "; test_inactive\n" + "".join(f"\t{ln}\n" for ln in lines) + "\texp mrt0 v5, v6, v7, v5 done vm\n\ts_endpgm\n" | ||
| 162 | with open(_SRC_PATH, "w", encoding="utf-8", newline="\n") as f: | ||
| 163 | f.write(asm) | ||
| 164 | with warnings.catch_warnings(): | ||
| 165 | warnings.simplefilter("ignore", ResourceWarning) | ||
| 166 | spv = rdna2spirv.translate(_SRC_PATH) | ||
| 167 | lo, hi, cword = si.run_fragment(spv)["%out_mrt0"][:3] | ||
| 168 | self.assertEqual((lo & 0xFFFF) | ((hi & 0xFFFF) << 16), 0x12345678) | ||
| 169 | self.assertEqual(cword & 1, 0) | ||
| 170 | |||
| 171 | def test_seeded_random(self): | ||
| 172 | rng = random.Random(20261122) | ||
| 173 | for op in CO_OPS + CO_CI_OPS: | ||
| 174 | for _ in range(12): | ||
| 175 | x, y = rng.randrange(1 << 32), rng.randrange(1 << 32) | ||
| 176 | cin = rng.randrange(2) | ||
| 177 | for clamp in (False, True): | ||
| 178 | self.assertEqual(run_case(op, x, y, cin, clamp), ref(op, x, y, cin, clamp), | ||
| 179 | (op, hex(x), hex(y), cin, clamp)) | ||
| 180 | |||
| 181 | |||
| 182 | if __name__ == "__main__": | ||
| 183 | unittest.main() | ||
diff --git a/tests/semantic/test_alu_cvt_flr_rpi.py b/tests/semantic/test_alu_cvt_flr_rpi.py index f31e82d99..eb9239af8 100644 --- a/tests/semantic/test_alu_cvt_flr_rpi.py +++ b/tests/semantic/test_alu_cvt_flr_rpi.py | |||
| @@ -1,13 +1,16 @@ | |||
| 1 | """Semantic interpreter tests for RDNA2 v_cvt_flr_i32_f32 and v_cvt_rpi_i32_f32. | 1 | """Semantic interpreter tests for RDNA2 v_cvt_flr_i32_f32 and v_cvt_rpi_i32_f32. |
| 2 | 2 | ||
| 3 | RDNA ISA pseudocode: v_cvt_flr_i32_f32 is f32_to_i32(floor(S0)), v_cvt_rpi_i32_f32 is f32_to_i32(floor(S0 + 0.5)), | 3 | Measured natively on RDNA2 (gfx1035 & gfx1036, wave32 & wave64): v_cvt_flr_i32_f32 is sat_i32(floor(S0)), and |
| 4 | with the + 0.5 rounded in binary32 like any f32 add. f32_to_i32 saturates as v_cvt_i32_f32 does (#300): at or past | 4 | v_cvt_rpi_i32_f32 is sat_i32(floor(S0 + 0.5)) computed **exactly** (without binary32 rounding of S0 + 0.5, so |
| 5 | +-2^31, and +-inf, it gives INT_MAX / INT_MIN; NaN gives 0. Each case translates a synthetic pixel shader with | 5 | 0x3EFFFFFF = 0.49999997 gives 0, 0x4B000001 gives 0x00800001, and 0x4B7FFFFF gives 0x00FFFFFF). Values at or past |
| 6 | tools/rdna2spirv.py, runs it in tests/semantic/spirv_mini_interp.py and compares the result with a plain-Python | 6 | +-2^31, +-inf, and NaNs all saturate by the sign bit of the operand (+ -> 0x7FFFFFFF, - -> 0x80000000), unlike |
| 7 | reference. Denormal inputs are left out (the float mode that would flush them is not modelled). The result leaves | 7 | v_cvt_i32_f32 which returns 0 for NaN. Each case translates a synthetic pixel shader with tools/rdna2spirv.py, runs |
| 8 | through exp as two 16-bit halves ORed into 0x40000000, so no export channel is a NaN or denormal pattern that a | 8 | it in tests/semantic/spirv_mini_interp.py and compares the result with an exact plain-Python reference. Denormal |
| 9 | float round trip could change. | 9 | inputs are left out (the float mode that would flush them is not modelled). The result leaves through exp as two |
| 10 | 16-bit halves ORed into 0x40000000, so no export channel is a NaN or denormal pattern that a float round trip could | ||
| 11 | change. | ||
| 10 | """ | 12 | """ |
| 13 | from fractions import Fraction | ||
| 11 | import math | 14 | import math |
| 12 | import os | 15 | import os |
| 13 | import random | 16 | import random |
| @@ -32,38 +35,34 @@ M32 = 0xFFFFFFFF | |||
| 32 | STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("<I", 0) + bytes(4) | 35 | STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("<I", 0) + bytes(4) |
| 33 | 36 | ||
| 34 | 37 | ||
| 35 | def u2f(u: int) -> float: | ||
| 36 | return struct.unpack("<f", struct.pack("<I", u & M32))[0] | ||
| 37 | |||
| 38 | |||
| 39 | def f32(x: float) -> float: | ||
| 40 | try: | ||
| 41 | return struct.unpack("<f", struct.pack("<f", x))[0] | ||
| 42 | except OverflowError: | ||
| 43 | return math.copysign(math.inf, x) | ||
| 44 | |||
| 45 | |||
| 46 | def f32_to_i32(x: float) -> int: | ||
| 47 | if math.isnan(x): | ||
| 48 | return 0 | ||
| 49 | if x >= 2.0 ** 31: | ||
| 50 | return 0x7FFFFFFF | ||
| 51 | if x < -(2.0 ** 31): | ||
| 52 | return 0x80000000 | ||
| 53 | return int(x) & M32 | ||
| 54 | |||
| 55 | |||
| 56 | def ref(op: str, u: int) -> int: | 38 | def ref(op: str, u: int) -> int: |
| 57 | x = u2f(u) | 39 | u &= M32 |
| 40 | sign = (u >> 31) & 1 | ||
| 41 | exp = (u >> 23) & 0xFF | ||
| 42 | mant = u & 0x7FFFFF | ||
| 43 | if exp == 0xFF: | ||
| 44 | return 0x80000000 if sign else 0x7FFFFFFF | ||
| 45 | if exp == 0: | ||
| 46 | x = Fraction(mant, 1 << 149) | ||
| 47 | else: | ||
| 48 | x = Fraction((1 << 23) | mant) * (Fraction(2) ** (exp - 150)) | ||
| 49 | if sign: | ||
| 50 | x = -x | ||
| 58 | if op == "v_cvt_rpi_i32_f32": | 51 | if op == "v_cvt_rpi_i32_f32": |
| 59 | x = f32(x + 0.5) # exact in double, then one rounding to binary32 | 52 | x += Fraction(1, 2) |
| 60 | return f32_to_i32(math.floor(x) if math.isfinite(x) else x) | 53 | iv = math.floor(x) |
| 54 | if iv >= (1 << 31): | ||
| 55 | return 0x7FFFFFFF | ||
| 56 | if iv < -(1 << 31): | ||
| 57 | return 0x80000000 | ||
| 58 | return iv & M32 | ||
| 61 | 59 | ||
| 62 | 60 | ||
| 63 | OPS = ("v_cvt_flr_i32_f32", "v_cvt_rpi_i32_f32") | 61 | OPS = ("v_cvt_flr_i32_f32", "v_cvt_rpi_i32_f32") |
| 64 | VALUES = [0x00000000, 0x80000000, 0x3F000000, 0xBF000000, 0x3EFFFFFF, 0xBEFFFFFF, 0x3FC00000, 0xBFC00000, | 62 | VALUES = [0x00000000, 0x80000000, 0x3F000000, 0xBF000000, 0x3EFFFFFF, 0xBEFFFFFF, 0xBF000001, 0x3FC00000, 0xBFC00000, |
| 65 | 0x40200000, 0xC0200000, 0x3F7FFFFF, 0x4B000001, 0xCB000001, 0x4EFFFFFF, 0xCEFFFFFF, 0x4F000000, | 63 | 0x40200000, 0xC0200000, 0x3F7FFFFF, 0x4AFFFFFF, 0x4B000000, 0x4B000001, 0x4B7FFFFF, 0xCB000001, 0x4EFFFFFF, |
| 66 | 0xCF000000, 0xCF000001, 0x7F7FFFFF, 0xFF7FFFFF, 0x7F800000, 0xFF800000, 0x7FC00000, 0xFFC00000, 0x7F800001] | 64 | 0xCEFFFFFF, 0x4F000000, 0xCF000000, 0xCF000001, 0x7F7FFFFF, 0xFF7FFFFF, 0x7F800000, 0xFF800000, 0x7FC00000, |
| 65 | 0xFFC00000, 0x7F800001, 0xFF800001] | ||
| 67 | 66 | ||
| 68 | _TMP_DIR = None | 67 | _TMP_DIR = None |
| 69 | _SRC_PATH = None | 68 | _SRC_PATH = None |
| @@ -112,9 +111,12 @@ class CvtFlrRpiTests(unittest.TestCase): | |||
| 112 | self.assertEqual(ref("v_cvt_flr_i32_f32", 0xC0200000), (-3) & M32) # floor(-2.5) | 111 | self.assertEqual(ref("v_cvt_flr_i32_f32", 0xC0200000), (-3) & M32) # floor(-2.5) |
| 113 | self.assertEqual(ref("v_cvt_rpi_i32_f32", 0xC0200000), (-2) & M32) # floor(-2.5 + 0.5) | 112 | self.assertEqual(ref("v_cvt_rpi_i32_f32", 0xC0200000), (-2) & M32) # floor(-2.5 + 0.5) |
| 114 | self.assertEqual(ref("v_cvt_rpi_i32_f32", 0x40200000), 3) # 2.5 rounds up | 113 | self.assertEqual(ref("v_cvt_rpi_i32_f32", 0x40200000), 3) # 2.5 rounds up |
| 115 | self.assertEqual(ref("v_cvt_rpi_i32_f32", 0x3EFFFFFF), 1) # 0.49999997 + 0.5 rounds to 1.0 | 114 | self.assertEqual(ref("v_cvt_rpi_i32_f32", 0x3EFFFFFF), 0) # 0.49999997 -> exact floor(x+0.5) = 0 |
| 115 | self.assertEqual(ref("v_cvt_rpi_i32_f32", 0x4B000001), 0x00800001) # 8388609.0 -> exact, not 8388610 | ||
| 116 | self.assertEqual(ref("v_cvt_rpi_i32_f32", 0x4B7FFFFF), 0x00FFFFFF) # 16777215.0 -> exact, not 16777216 | ||
| 116 | self.assertEqual(ref("v_cvt_flr_i32_f32", 0xCF000001), 0x80000000) # below -2^31: saturated | 117 | self.assertEqual(ref("v_cvt_flr_i32_f32", 0xCF000001), 0x80000000) # below -2^31: saturated |
| 117 | self.assertEqual(ref("v_cvt_flr_i32_f32", 0x7FC00000), 0) # NaN | 118 | self.assertEqual(ref("v_cvt_flr_i32_f32", 0x7FC00000), 0x7FFFFFFF) # +NaN saturates to INT_MAX |
| 119 | self.assertEqual(ref("v_cvt_flr_i32_f32", 0xFFC00000), 0x80000000) # -NaN saturates to INT_MIN | ||
| 118 | 120 | ||
| 119 | def test_edge_values(self): | 121 | def test_edge_values(self): |
| 120 | for op in OPS: | 122 | for op in OPS: |
diff --git a/tests/semantic/test_alu_dot4_i8.py b/tests/semantic/test_alu_dot4_i8.py new file mode 100644 index 000000000..ff60a8508 --- /dev/null +++ b/tests/semantic/test_alu_dot4_i8.py | |||
| @@ -0,0 +1,138 @@ | |||
| 1 | """v_dot4_i32_i8 and v_dot4c_i32_i8: the dot product of the signed bytes of two dwords, plus an addend. | ||
| 2 | |||
| 3 | ISA rule (RDNA2): D = S0.b0*S1.b0 + S0.b1*S1.b1 + S0.b2*S1.b2 + S0.b3*S1.b3 + addend, every byte sign-extended, the | ||
| 4 | sum kept modulo 2^32. The addend is the third source for v_dot4_i32_i8 (VOP3P) and the old value of the destination | ||
| 5 | for v_dot4c_i32_i8 (VOP2). The 29 FSPX programs of the package's upscaler DLL (docs/fspx.md) use the pair 27,271 | ||
| 6 | times. | ||
| 7 | |||
| 8 | The expected words below were measured on RDNA2 hardware (gfx1036, the integrated GPU of a Ryzen 9 7950X3D, through | ||
| 9 | tools/hw_oracle): each case ran `v_dot4_i32_i8 v8, v1, v2, v3`, `v_dot4c_i32_i8 v10, v1, v2` with v10 holding the | ||
| 10 | addend, and the same with the two sources swapped. All three gave the word in the table, which the plain-Python | ||
| 11 | reference `ref` reproduces. With `clamp` the hardware saturates v_dot4_i32_i8 to a signed 32-bit value | ||
| 12 | (0x7fffffff and 0x80000000 in the two overflowing cases); the translator refuses that form. | ||
| 13 | |||
| 14 | op_sel. The plain instruction has op_sel 0 and op_sel_hi 7. 89 words in 8 of those programs are v_dot4_i32_i8 with | ||
| 15 | op_sel 2 and op_sel_hi 5, which llvm-mc does not decode (docs/fspx.md). Run on the same hardware as two raw words | ||
| 16 | (0xCC165008 0x0C0E0501: v8 = v1 . v2 + v3 with those fields), that form gave the words of MEASURED_OP_SEL: the dot | ||
| 17 | product with the two 16-bit halves of the second source exchanged, as op_sel selects halves for the packed 16-bit | ||
| 18 | ops. `ref_op_sel` reproduces them; the translator refuses any op_sel on these two instructions until a listing can | ||
| 19 | carry it. | ||
| 20 | |||
| 21 | python -m unittest discover -s tests/semantic -p test_alu_dot4_i8.py | ||
| 22 | """ | ||
| 23 | import os | ||
| 24 | import sys | ||
| 25 | import unittest | ||
| 26 | |||
| 27 | HERE = os.path.dirname(os.path.abspath(__file__)) | ||
| 28 | if HERE not in sys.path: | ||
| 29 | sys.path.insert(0, HERE) | ||
| 30 | |||
| 31 | import support # noqa: E402 | ||
| 32 | |||
| 33 | rdna2spirv = support.rdna2spirv | ||
| 34 | |||
| 35 | # (S0, S1, addend, result measured on gfx1036) | ||
| 36 | MEASURED = [ | ||
| 37 | (0x01020304, 0x05060708, 0x00000000, 0x00000046), # 4*8 + 3*7 + 2*6 + 1*5 = 70 | ||
| 38 | (0x01020304, 0x05060708, 0x000003E8, 0x0000042E), # 70 + 1000 | ||
| 39 | (0xFF80017F, 0x7F7F80FF, 0x00000000, 0xFFFFBF02), # 127*-1 + 1*-128 + -128*127 + -1*127 = -16638 | ||
| 40 | (0xFF80017F, 0x7F7F80FF, 0x00010000, 0x0000BF02), | ||
| 41 | (0x80808080, 0x80808080, 0x00000000, 0x00010000), # 4 * (-128 * -128) | ||
| 42 | (0x80808080, 0x7F7F7F7F, 0x00000005, 0xFFFF0205), # 4 * (-128 * 127) + 5 | ||
| 43 | (0x7F7F7F7F, 0x7F7F7F7F, 0x7FFFFFFF, 0x8000FC03), # wraps upward: no saturation without clamp | ||
| 44 | (0x80808080, 0x7F7F7F7F, 0x80000000, 0x7FFF0200), # wraps downward | ||
| 45 | (0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0x00000003), # 4 * (-1 * -1) - 1 | ||
| 46 | (0x00000000, 0x12345678, 0xDEADBEEF, 0xDEADBEEF), | ||
| 47 | ] | ||
| 48 | |||
| 49 | |||
| 50 | # (S0, S1, addend, result measured on gfx1036 with op_sel 2 and op_sel_hi 5) | ||
| 51 | MEASURED_OP_SEL = [ | ||
| 52 | (0x04030201, 0x08070605, 0x00000000, 62), # the plain form gives 70 | ||
| 53 | (0x04030201, 0x08070605, 0x000003E8, 1062), | ||
| 54 | (0x7F01FE80, 0x02FD7F81, 0x00000000, 16382), # the plain form gives 16253 | ||
| 55 | (0x11223344, 0x55667788, 0x00010000, 74750), # the plain form gives 68358 | ||
| 56 | (0xFFFFFFFF, 0x01020304, 0x00000007, 0xFFFFFFFD), # every byte of S0 the same: the order cannot show | ||
| 57 | ] | ||
| 58 | |||
| 59 | |||
| 60 | def ref(a, b, addend): | ||
| 61 | def s8(x): | ||
| 62 | return x - 256 if x & 0x80 else x | ||
| 63 | total = sum(s8((a >> (8 * i)) & 0xFF) * s8((b >> (8 * i)) & 0xFF) for i in range(4)) | ||
| 64 | return (total + addend) & 0xFFFFFFFF | ||
| 65 | |||
| 66 | |||
| 67 | def ref_op_sel(a, b, addend): | ||
| 68 | """op_sel 2, op_sel_hi 5: the low half of the product reads the high half of S1 and the high half its low half.""" | ||
| 69 | return ref(a, (b & 0xFFFF) << 16 | b >> 16, addend) | ||
| 70 | |||
| 71 | |||
| 72 | def program(a, b, addend): | ||
| 73 | """mrt0 = (v_dot4_i32_i8, v_dot4c_i32_i8, v_dot4c_i32_i8 with the sources swapped, v_dot4_i32_i8 with the | ||
| 74 | sources and the addend taken from SGPRs and a literal, as the shaders do).""" | ||
| 75 | return [ | ||
| 76 | f"v_mov_b32_e32 v1, 0x{a:08x}", | ||
| 77 | f"v_mov_b32_e32 v2, 0x{b:08x}", | ||
| 78 | f"v_mov_b32_e32 v3, 0x{addend:08x}", | ||
| 79 | f"s_mov_b32 s4, 0x{addend:08x}", | ||
| 80 | "v_dot4_i32_i8 v8, v1, v2, v3", | ||
| 81 | f"v_mov_b32_e32 v9, 0x{addend:08x}", | ||
| 82 | "v_dot4c_i32_i8 v9, v1, v2", | ||
| 83 | f"v_mov_b32_e32 v10, 0x{addend:08x}", | ||
| 84 | "v_dot4c_i32_i8 v10, v2, v1", | ||
| 85 | f"v_dot4_i32_i8 v11, v1, 0x{b:08x}, s4", | ||
| 86 | "exp mrt0 v8, v9, v10, v11 done vm", | ||
| 87 | "s_endpgm", | ||
| 88 | ] | ||
| 89 | |||
| 90 | |||
| 91 | class Dot4I8(unittest.TestCase): | ||
| 92 | def test_the_reference_reproduces_the_hardware_words(self): | ||
| 93 | for a, b, addend, measured in MEASURED: | ||
| 94 | self.assertEqual(ref(a, b, addend), measured, f"{a:#x} . {b:#x} + {addend:#x}") | ||
| 95 | |||
| 96 | def test_both_forms_give_the_hardware_words(self): | ||
| 97 | for a, b, addend, measured in MEASURED: | ||
| 98 | with self.subTest(a=f"{a:#010x}", b=f"{b:#010x}", addend=f"{addend:#010x}"): | ||
| 99 | spv = support.translate_lines("ps_dot4_i8", program(a, b, addend)) | ||
| 100 | self.assertEqual(support.mrt0_words(spv), [measured] * 4) | ||
| 101 | |||
| 102 | def test_the_accumulating_form_reads_its_destination(self): | ||
| 103 | # v9 is never written before v_dot4c reads it: the old value is then the register's initial 0, not garbage | ||
| 104 | # from an expression that dropped the addend. 70 is the dot product alone. | ||
| 105 | lines = ["v_mov_b32_e32 v1, 0x01020304", "v_mov_b32_e32 v2, 0x05060708", "v_dot4c_i32_i8 v9, v1, v2", | ||
| 106 | "v_dot4c_i32_i8 v9, v1, v2", "exp mrt0 v9, v9, v9, v9 done vm", "s_endpgm"] | ||
| 107 | self.assertEqual(support.mrt0_words(support.translate_lines("ps_dot4c_twice", lines)), [140] * 4) | ||
| 108 | |||
| 109 | def test_the_bytes_are_signed(self): | ||
| 110 | # 0xff * 0x01: -1 as a signed byte, 255 as an unsigned one. | ||
| 111 | lines = ["v_mov_b32_e32 v1, 0x000000ff", "v_mov_b32_e32 v2, 0x00000001", "v_mov_b32_e32 v3, 0", | ||
| 112 | "v_dot4_i32_i8 v8, v1, v2, v3", "exp mrt0 v8, v8, v8, v8 done vm", "s_endpgm"] | ||
| 113 | self.assertEqual(support.mrt0_words(support.translate_lines("ps_dot4_signed", lines)), [0xFFFFFFFF] * 4) | ||
| 114 | |||
| 115 | def test_the_op_sel_reference_reproduces_the_hardware_words(self): | ||
| 116 | for a, b, addend, measured in MEASURED_OP_SEL: | ||
| 117 | self.assertEqual(ref_op_sel(a, b, addend), measured, f"{a:#x} . {b:#x} + {addend:#x}") | ||
| 118 | # The table can tell the two readings apart: the plain rule gives another word in four of the five cases. | ||
| 119 | self.assertEqual(sum(ref(a, b, c) != m for a, b, c, m in MEASURED_OP_SEL), 4) | ||
| 120 | |||
| 121 | def test_op_sel_is_refused(self): | ||
| 122 | lines = ["v_mov_b32_e32 v1, 1", "v_mov_b32_e32 v2, 1", "v_mov_b32_e32 v3, 0", | ||
| 123 | "v_dot4_i32_i8 v8, v1, v2, v3 op_sel:[0,1,0] op_sel_hi:[1,0,1]", | ||
| 124 | "exp mrt0 v8, v8, v8, v8 done vm", "s_endpgm"] | ||
| 125 | with self.assertRaises(rdna2spirv.Unsupported) as refused: | ||
| 126 | support.translate_lines("ps_dot4_op_sel", lines) | ||
| 127 | self.assertEqual(str(refused.exception), "v_dot4_i32_i8 op_sel") | ||
| 128 | |||
| 129 | def test_clamp_is_refused(self): | ||
| 130 | lines = ["v_mov_b32_e32 v1, 1", "v_mov_b32_e32 v2, 1", "v_mov_b32_e32 v3, 0", | ||
| 131 | "v_dot4_i32_i8 v8, v1, v2, v3 clamp", "exp mrt0 v8, v8, v8, v8 done vm", "s_endpgm"] | ||
| 132 | with self.assertRaises(rdna2spirv.Unsupported) as refused: | ||
| 133 | support.translate_lines("ps_dot4_clamp", lines) | ||
| 134 | self.assertEqual(str(refused.exception), "v_dot4_i32_i8 clamp") | ||
| 135 | |||
| 136 | |||
| 137 | if __name__ == "__main__": | ||
| 138 | unittest.main() | ||
diff --git a/tests/semantic/test_buffer_format_narrow_int.py b/tests/semantic/test_buffer_format_narrow_int.py new file mode 100644 index 000000000..0b1fbd15b --- /dev/null +++ b/tests/semantic/test_buffer_format_narrow_int.py | |||
| @@ -0,0 +1,257 @@ | |||
| 1 | """Narrow integer typed-buffer formats (8/16-bit UINT and SINT) in tools/rdna2spirv.py, against words measured natively. | ||
| 2 | |||
| 3 | Every expected word below was read back from an AMD Radeon RDNA2 iGPU (gfx1036, Ryzen 9 9950X3D, Windows AMD | ||
| 4 | driver, through tools/hw_oracle with AMD clang 23 from rocm-sdk-core 10.0.0), in wave32 and wave64 alike, with the | ||
| 5 | same V# and instruction the translated shader gets here: | ||
| 6 | |||
| 7 | - loads: `buffer_load_format_xyzw` and `_d16_xyzw` from four source dwords (SOURCE) with DST_SEL XYZW and X011. UINT | ||
| 8 | zero-extends and SINT sign-extends each channel; missing channels repeat the format's own (c mod n); DST_SEL 1 is | ||
| 9 | integer 1; d16 packs each result as a 16-bit integer. | ||
| 10 | - stores: `buffer_store_format_x/xy/xyzw` of four value sets into a buffer filled with 0xDEAD0000, with the V# | ||
| 11 | selectors the runtime gives each format (gfx10_descriptors.h: X001, XY01, XYZW). UINT saturates to the channel | ||
| 12 | (unsigned), SINT clamps the signed 32-bit value to [-2^(w-1), 2^(w-1) - 1]; a 1-2 byte element keeps the rest | ||
| 13 | of its dword. | ||
| 14 | |||
| 15 | Formats 27, 60 and 69 (16_16_UINT, 8_8_8_8_UINT, 16_16_16_16_UINT) were decoded before; they are the control. | ||
| 16 | """ | ||
| 17 | from __future__ import annotations | ||
| 18 | |||
| 19 | import os | ||
| 20 | import struct | ||
| 21 | import sys | ||
| 22 | import tempfile | ||
| 23 | import unittest | ||
| 24 | import warnings | ||
| 25 | |||
| 26 | HERE = os.path.dirname(os.path.abspath(__file__)) | ||
| 27 | ROOT = os.path.dirname(os.path.dirname(HERE)) | ||
| 28 | sys.dont_write_bytecode = True | ||
| 29 | sys.path.insert(0, os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools")) | ||
| 30 | sys.path.insert(0, HERE) | ||
| 31 | |||
| 32 | import rdna2spirv # noqa: E402 | ||
| 33 | import spirv_mini_interp as si # noqa: E402 | ||
| 34 | |||
| 35 | STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("<I", 0) + bytes(4) | ||
| 36 | BASE = 0x1000 | ||
| 37 | SOURCE = (0x7F01FF80, 0x8000FFFF, 0x12345678, 0x9ABCDEF0) | ||
| 38 | SEL_XYZW, SEL_X011 = 4 | 5 << 3 | 6 << 6 | 7 << 9, 4 | 0 << 3 | 1 << 6 | 1 << 9 | ||
| 39 | RUNTIME_SEL = {1: 4 | 0 << 3 | 0 << 6 | 1 << 9, 2: 4 | 5 << 3 | 0 << 6 | 1 << 9, 4: SEL_XYZW} | ||
| 40 | CHANNELS = {5: 1, 6: 1, 11: 1, 12: 1, 18: 2, 19: 2, 27: 2, 28: 2, 60: 4, 61: 4, 69: 4, 70: 4} | ||
| 41 | VALUES = {"big": (300, 0xFFFFFF38, 0x7FFFFFFF, 0x80000000), "edge": (0x7F, 0x80, 0xFFFFFF80, 0xFFFFFF7F), | ||
| 42 | "edge16": (0x7FFF, 0x8000, 0xFFFF8000, 0xFFFF7FFF), "small": (5, 0xFFFFFFFF, 0, 0x101)} | ||
| 43 | |||
| 44 | LOADS = { # format: (xyzw with DST_SEL XYZW, xyzw with DST_SEL X011, d16_xyzw's two registers) | ||
| 45 | 5: ((0x00000080, 0x00000080, 0x00000080, 0x00000080), (0x00000080, 0x00000000, 0x00000001, 0x00000001), (0x00800080, 0x00800080)), # 8_UINT | ||
| 46 | 6: ((0xffffff80, 0xffffff80, 0xffffff80, 0xffffff80), (0xffffff80, 0x00000000, 0x00000001, 0x00000001), (0xff80ff80, 0xff80ff80)), # 8_SINT | ||
| 47 | 11: ((0x0000ff80, 0x0000ff80, 0x0000ff80, 0x0000ff80), (0x0000ff80, 0x00000000, 0x00000001, 0x00000001), (0xff80ff80, 0xff80ff80)), # 16_UINT | ||
| 48 | 12: ((0xffffff80, 0xffffff80, 0xffffff80, 0xffffff80), (0xffffff80, 0x00000000, 0x00000001, 0x00000001), (0xff80ff80, 0xff80ff80)), # 16_SINT | ||
| 49 | 18: ((0x00000080, 0x000000ff, 0x00000080, 0x000000ff), (0x00000080, 0x00000000, 0x00000001, 0x00000001), (0x00ff0080, 0x00ff0080)), # 8_8_UINT | ||
| 50 | 19: ((0xffffff80, 0xffffffff, 0xffffff80, 0xffffffff), (0xffffff80, 0x00000000, 0x00000001, 0x00000001), (0xffffff80, 0xffffff80)), # 8_8_SINT | ||
| 51 | 27: ((0x0000ff80, 0x00007f01, 0x0000ff80, 0x00007f01), (0x0000ff80, 0x00000000, 0x00000001, 0x00000001), (0x7f01ff80, 0x7f01ff80)), # 16_16_UINT | ||
| 52 | 28: ((0xffffff80, 0x00007f01, 0xffffff80, 0x00007f01), (0xffffff80, 0x00000000, 0x00000001, 0x00000001), (0x7f01ff80, 0x7f01ff80)), # 16_16_SINT | ||
| 53 | 60: ((0x00000080, 0x000000ff, 0x00000001, 0x0000007f), (0x00000080, 0x00000000, 0x00000001, 0x00000001), (0x00ff0080, 0x007f0001)), # 8_8_8_8_UINT | ||
| 54 | 61: ((0xffffff80, 0xffffffff, 0x00000001, 0x0000007f), (0xffffff80, 0x00000000, 0x00000001, 0x00000001), (0xffffff80, 0x007f0001)), # 8_8_8_8_SINT | ||
| 55 | 69: ((0x0000ff80, 0x00007f01, 0x0000ffff, 0x00008000), (0x0000ff80, 0x00000000, 0x00000001, 0x00000001), (0x7f01ff80, 0x8000ffff)), # 16_16_16_16_UINT | ||
| 56 | 70: ((0xffffff80, 0x00007f01, 0xffffffff, 0xffff8000), (0xffffff80, 0x00000000, 0x00000001, 0x00000001), (0x7f01ff80, 0x8000ffff)), # 16_16_16_16_SINT | ||
| 57 | } | ||
| 58 | STORES = { # (format, value set, components): the two dwords at the element, 0xDEAD0000 before the store | ||
| 59 | (5, 'big', 1): (0xdead00ff, 0xdead0000), # 8_UINT | ||
| 60 | (5, 'big', 2): (0xdead00ff, 0xdead0000), # 8_UINT | ||
| 61 | (5, 'big', 4): (0xdead00ff, 0xdead0000), # 8_UINT | ||
| 62 | (5, 'edge', 1): (0xdead007f, 0xdead0000), # 8_UINT | ||
| 63 | (5, 'edge', 2): (0xdead007f, 0xdead0000), # 8_UINT | ||
| 64 | (5, 'edge', 4): (0xdead007f, 0xdead0000), # 8_UINT | ||
| 65 | (5, 'edge16', 1): (0xdead00ff, 0xdead0000), # 8_UINT | ||
| 66 | (5, 'edge16', 2): (0xdead00ff, 0xdead0000), # 8_UINT | ||
| 67 | (5, 'edge16', 4): (0xdead00ff, 0xdead0000), # 8_UINT | ||
| 68 | (5, 'small', 1): (0xdead0005, 0xdead0000), # 8_UINT | ||
| 69 | (5, 'small', 2): (0xdead0005, 0xdead0000), # 8_UINT | ||
| 70 | (5, 'small', 4): (0xdead0005, 0xdead0000), # 8_UINT | ||
| 71 | (6, 'big', 1): (0xdead007f, 0xdead0000), # 8_SINT | ||
| 72 | (6, 'big', 2): (0xdead007f, 0xdead0000), # 8_SINT | ||
| 73 | (6, 'big', 4): (0xdead007f, 0xdead0000), # 8_SINT | ||
| 74 | (6, 'edge', 1): (0xdead007f, 0xdead0000), # 8_SINT | ||
| 75 | (6, 'edge', 2): (0xdead007f, 0xdead0000), # 8_SINT | ||
| 76 | (6, 'edge', 4): (0xdead007f, 0xdead0000), # 8_SINT | ||
| 77 | (6, 'edge16', 1): (0xdead007f, 0xdead0000), # 8_SINT | ||
| 78 | (6, 'edge16', 2): (0xdead007f, 0xdead0000), # 8_SINT | ||
| 79 | (6, 'edge16', 4): (0xdead007f, 0xdead0000), # 8_SINT | ||
| 80 | (6, 'small', 1): (0xdead0005, 0xdead0000), # 8_SINT | ||
| 81 | (6, 'small', 2): (0xdead0005, 0xdead0000), # 8_SINT | ||
| 82 | (6, 'small', 4): (0xdead0005, 0xdead0000), # 8_SINT | ||
| 83 | (11, 'big', 1): (0xdead012c, 0xdead0000), # 16_UINT | ||
| 84 | (11, 'big', 2): (0xdead012c, 0xdead0000), # 16_UINT | ||
| 85 | (11, 'big', 4): (0xdead012c, 0xdead0000), # 16_UINT | ||
| 86 | (11, 'edge', 1): (0xdead007f, 0xdead0000), # 16_UINT | ||
| 87 | (11, 'edge', 2): (0xdead007f, 0xdead0000), # 16_UINT | ||
| 88 | (11, 'edge', 4): (0xdead007f, 0xdead0000), # 16_UINT | ||
| 89 | (11, 'edge16', 1): (0xdead7fff, 0xdead0000), # 16_UINT | ||
| 90 | (11, 'edge16', 2): (0xdead7fff, 0xdead0000), # 16_UINT | ||
| 91 | (11, 'edge16', 4): (0xdead7fff, 0xdead0000), # 16_UINT | ||
| 92 | (11, 'small', 1): (0xdead0005, 0xdead0000), # 16_UINT | ||
| 93 | (11, 'small', 2): (0xdead0005, 0xdead0000), # 16_UINT | ||
| 94 | (11, 'small', 4): (0xdead0005, 0xdead0000), # 16_UINT | ||
| 95 | (12, 'big', 1): (0xdead012c, 0xdead0000), # 16_SINT | ||
| 96 | (12, 'big', 2): (0xdead012c, 0xdead0000), # 16_SINT | ||
| 97 | (12, 'big', 4): (0xdead012c, 0xdead0000), # 16_SINT | ||
| 98 | (12, 'edge', 1): (0xdead007f, 0xdead0000), # 16_SINT | ||
| 99 | (12, 'edge', 2): (0xdead007f, 0xdead0000), # 16_SINT | ||
| 100 | (12, 'edge', 4): (0xdead007f, 0xdead0000), # 16_SINT | ||
| 101 | (12, 'edge16', 1): (0xdead7fff, 0xdead0000), # 16_SINT | ||
| 102 | (12, 'edge16', 2): (0xdead7fff, 0xdead0000), # 16_SINT | ||
| 103 | (12, 'edge16', 4): (0xdead7fff, 0xdead0000), # 16_SINT | ||
| 104 | (12, 'small', 1): (0xdead0005, 0xdead0000), # 16_SINT | ||
| 105 | (12, 'small', 2): (0xdead0005, 0xdead0000), # 16_SINT | ||
| 106 | (12, 'small', 4): (0xdead0005, 0xdead0000), # 16_SINT | ||
| 107 | (18, 'big', 1): (0xdead00ff, 0xdead0000), # 8_8_UINT | ||
| 108 | (18, 'big', 2): (0xdeadffff, 0xdead0000), # 8_8_UINT | ||
| 109 | (18, 'big', 4): (0xdeadffff, 0xdead0000), # 8_8_UINT | ||
| 110 | (18, 'edge', 1): (0xdead007f, 0xdead0000), # 8_8_UINT | ||
| 111 | (18, 'edge', 2): (0xdead807f, 0xdead0000), # 8_8_UINT | ||
| 112 | (18, 'edge', 4): (0xdead807f, 0xdead0000), # 8_8_UINT | ||
| 113 | (18, 'edge16', 1): (0xdead00ff, 0xdead0000), # 8_8_UINT | ||
| 114 | (18, 'edge16', 2): (0xdeadffff, 0xdead0000), # 8_8_UINT | ||
| 115 | (18, 'edge16', 4): (0xdeadffff, 0xdead0000), # 8_8_UINT | ||
| 116 | (18, 'small', 1): (0xdead0005, 0xdead0000), # 8_8_UINT | ||
| 117 | (18, 'small', 2): (0xdeadff05, 0xdead0000), # 8_8_UINT | ||
| 118 | (18, 'small', 4): (0xdeadff05, 0xdead0000), # 8_8_UINT | ||
| 119 | (19, 'big', 1): (0xdead007f, 0xdead0000), # 8_8_SINT | ||
| 120 | (19, 'big', 2): (0xdead807f, 0xdead0000), # 8_8_SINT | ||
| 121 | (19, 'big', 4): (0xdead807f, 0xdead0000), # 8_8_SINT | ||
| 122 | (19, 'edge', 1): (0xdead007f, 0xdead0000), # 8_8_SINT | ||
| 123 | (19, 'edge', 2): (0xdead7f7f, 0xdead0000), # 8_8_SINT | ||
| 124 | (19, 'edge', 4): (0xdead7f7f, 0xdead0000), # 8_8_SINT | ||
| 125 | (19, 'edge16', 1): (0xdead007f, 0xdead0000), # 8_8_SINT | ||
| 126 | (19, 'edge16', 2): (0xdead7f7f, 0xdead0000), # 8_8_SINT | ||
| 127 | (19, 'edge16', 4): (0xdead7f7f, 0xdead0000), # 8_8_SINT | ||
| 128 | (19, 'small', 1): (0xdead0005, 0xdead0000), # 8_8_SINT | ||
| 129 | (19, 'small', 2): (0xdeadff05, 0xdead0000), # 8_8_SINT | ||
| 130 | (19, 'small', 4): (0xdeadff05, 0xdead0000), # 8_8_SINT | ||
| 131 | (27, 'big', 1): (0x0000012c, 0xdead0000), # 16_16_UINT | ||
| 132 | (27, 'big', 2): (0xffff012c, 0xdead0000), # 16_16_UINT | ||
| 133 | (27, 'big', 4): (0xffff012c, 0xdead0000), # 16_16_UINT | ||
| 134 | (27, 'edge', 1): (0x0000007f, 0xdead0000), # 16_16_UINT | ||
| 135 | (27, 'edge', 2): (0x0080007f, 0xdead0000), # 16_16_UINT | ||
| 136 | (27, 'edge', 4): (0x0080007f, 0xdead0000), # 16_16_UINT | ||
| 137 | (27, 'edge16', 1): (0x00007fff, 0xdead0000), # 16_16_UINT | ||
| 138 | (27, 'edge16', 2): (0x80007fff, 0xdead0000), # 16_16_UINT | ||
| 139 | (27, 'edge16', 4): (0x80007fff, 0xdead0000), # 16_16_UINT | ||
| 140 | (27, 'small', 1): (0x00000005, 0xdead0000), # 16_16_UINT | ||
| 141 | (27, 'small', 2): (0xffff0005, 0xdead0000), # 16_16_UINT | ||
| 142 | (27, 'small', 4): (0xffff0005, 0xdead0000), # 16_16_UINT | ||
| 143 | (28, 'big', 1): (0x0000012c, 0xdead0000), # 16_16_SINT | ||
| 144 | (28, 'big', 2): (0xff38012c, 0xdead0000), # 16_16_SINT | ||
| 145 | (28, 'big', 4): (0xff38012c, 0xdead0000), # 16_16_SINT | ||
| 146 | (28, 'edge', 1): (0x0000007f, 0xdead0000), # 16_16_SINT | ||
| 147 | (28, 'edge', 2): (0x0080007f, 0xdead0000), # 16_16_SINT | ||
| 148 | (28, 'edge', 4): (0x0080007f, 0xdead0000), # 16_16_SINT | ||
| 149 | (28, 'edge16', 1): (0x00007fff, 0xdead0000), # 16_16_SINT | ||
| 150 | (28, 'edge16', 2): (0x7fff7fff, 0xdead0000), # 16_16_SINT | ||
| 151 | (28, 'edge16', 4): (0x7fff7fff, 0xdead0000), # 16_16_SINT | ||
| 152 | (28, 'small', 1): (0x00000005, 0xdead0000), # 16_16_SINT | ||
| 153 | (28, 'small', 2): (0xffff0005, 0xdead0000), # 16_16_SINT | ||
| 154 | (28, 'small', 4): (0xffff0005, 0xdead0000), # 16_16_SINT | ||
| 155 | (60, 'big', 1): (0x000000ff, 0xdead0000), # 8_8_8_8_UINT | ||
| 156 | (60, 'big', 2): (0x0000ffff, 0xdead0000), # 8_8_8_8_UINT | ||
| 157 | (60, 'big', 4): (0xffffffff, 0xdead0000), # 8_8_8_8_UINT | ||
| 158 | (60, 'edge', 1): (0x0000007f, 0xdead0000), # 8_8_8_8_UINT | ||
| 159 | (60, 'edge', 2): (0x0000807f, 0xdead0000), # 8_8_8_8_UINT | ||
| 160 | (60, 'edge', 4): (0xffff807f, 0xdead0000), # 8_8_8_8_UINT | ||
| 161 | (60, 'edge16', 1): (0x000000ff, 0xdead0000), # 8_8_8_8_UINT | ||
| 162 | (60, 'edge16', 2): (0x0000ffff, 0xdead0000), # 8_8_8_8_UINT | ||
| 163 | (60, 'edge16', 4): (0xffffffff, 0xdead0000), # 8_8_8_8_UINT | ||
| 164 | (60, 'small', 1): (0x00000005, 0xdead0000), # 8_8_8_8_UINT | ||
| 165 | (60, 'small', 2): (0x0000ff05, 0xdead0000), # 8_8_8_8_UINT | ||
| 166 | (60, 'small', 4): (0xff00ff05, 0xdead0000), # 8_8_8_8_UINT | ||
| 167 | (61, 'big', 1): (0x0000007f, 0xdead0000), # 8_8_8_8_SINT | ||
| 168 | (61, 'big', 2): (0x0000807f, 0xdead0000), # 8_8_8_8_SINT | ||
| 169 | (61, 'big', 4): (0x807f807f, 0xdead0000), # 8_8_8_8_SINT | ||
| 170 | (61, 'edge', 1): (0x0000007f, 0xdead0000), # 8_8_8_8_SINT | ||
| 171 | (61, 'edge', 2): (0x00007f7f, 0xdead0000), # 8_8_8_8_SINT | ||
| 172 | (61, 'edge', 4): (0x80807f7f, 0xdead0000), # 8_8_8_8_SINT | ||
| 173 | (61, 'edge16', 1): (0x0000007f, 0xdead0000), # 8_8_8_8_SINT | ||
| 174 | (61, 'edge16', 2): (0x00007f7f, 0xdead0000), # 8_8_8_8_SINT | ||
| 175 | (61, 'edge16', 4): (0x80807f7f, 0xdead0000), # 8_8_8_8_SINT | ||
| 176 | (61, 'small', 1): (0x00000005, 0xdead0000), # 8_8_8_8_SINT | ||
| 177 | (61, 'small', 2): (0x0000ff05, 0xdead0000), # 8_8_8_8_SINT | ||
| 178 | (61, 'small', 4): (0x7f00ff05, 0xdead0000), # 8_8_8_8_SINT | ||
| 179 | (69, 'big', 1): (0x0000012c, 0x00000000), # 16_16_16_16_UINT | ||
| 180 | (69, 'big', 2): (0xffff012c, 0x00000000), # 16_16_16_16_UINT | ||
| 181 | (69, 'big', 4): (0xffff012c, 0xffffffff), # 16_16_16_16_UINT | ||
| 182 | (69, 'edge', 1): (0x0000007f, 0x00000000), # 16_16_16_16_UINT | ||
| 183 | (69, 'edge', 2): (0x0080007f, 0x00000000), # 16_16_16_16_UINT | ||
| 184 | (69, 'edge', 4): (0x0080007f, 0xffffffff), # 16_16_16_16_UINT | ||
| 185 | (69, 'edge16', 1): (0x00007fff, 0x00000000), # 16_16_16_16_UINT | ||
| 186 | (69, 'edge16', 2): (0x80007fff, 0x00000000), # 16_16_16_16_UINT | ||
| 187 | (69, 'edge16', 4): (0x80007fff, 0xffffffff), # 16_16_16_16_UINT | ||
| 188 | (69, 'small', 1): (0x00000005, 0x00000000), # 16_16_16_16_UINT | ||
| 189 | (69, 'small', 2): (0xffff0005, 0x00000000), # 16_16_16_16_UINT | ||
| 190 | (69, 'small', 4): (0xffff0005, 0x01010000), # 16_16_16_16_UINT | ||
| 191 | (70, 'big', 1): (0x0000012c, 0x00000000), # 16_16_16_16_SINT | ||
| 192 | (70, 'big', 2): (0xff38012c, 0x00000000), # 16_16_16_16_SINT | ||
| 193 | (70, 'big', 4): (0xff38012c, 0x80007fff), # 16_16_16_16_SINT | ||
| 194 | (70, 'edge', 1): (0x0000007f, 0x00000000), # 16_16_16_16_SINT | ||
| 195 | (70, 'edge', 2): (0x0080007f, 0x00000000), # 16_16_16_16_SINT | ||
| 196 | (70, 'edge', 4): (0x0080007f, 0xff7fff80), # 16_16_16_16_SINT | ||
| 197 | (70, 'edge16', 1): (0x00007fff, 0x00000000), # 16_16_16_16_SINT | ||
| 198 | (70, 'edge16', 2): (0x7fff7fff, 0x00000000), # 16_16_16_16_SINT | ||
| 199 | (70, 'edge16', 4): (0x7fff7fff, 0x80008000), # 16_16_16_16_SINT | ||
| 200 | (70, 'small', 1): (0x00000005, 0x00000000), # 16_16_16_16_SINT | ||
| 201 | (70, 'small', 2): (0xffff0005, 0x00000000), # 16_16_16_16_SINT | ||
| 202 | (70, 'small', 4): (0xffff0005, 0x01010000), # 16_16_16_16_SINT | ||
| 203 | } | ||
| 204 | |||
| 205 | |||
| 206 | def run(fmt: int, body: str, dst_sel: int, memory: dict) -> tuple: | ||
| 207 | """Translate a pixel shader whose V# (s[0:3], raw, 256 bytes) points at BASE with this format and selectors.""" | ||
| 208 | with tempfile.TemporaryDirectory() as tmp: | ||
| 209 | os.mkdir(os.path.join(tmp, "disasm")) | ||
| 210 | src = os.path.join(tmp, "disasm", "ps_narrow_int.s") | ||
| 211 | with open(os.path.join(tmp, "ps_narrow_int.dxbc"), "wb") as f: | ||
| 212 | f.write(STUB_DXBC) | ||
| 213 | with open(src, "w", encoding="utf-8") as f: | ||
| 214 | f.write("; test_buffer_format_narrow_int\n" | ||
| 215 | f"\ts_mov_b32 s0, {BASE:#x}\n\ts_mov_b32 s1, 0\n\ts_mov_b32 s2, 0x100\n" | ||
| 216 | f"\ts_mov_b32 s3, {fmt << 12 | dst_sel | 1 << 24 | 3 << 28:#x}\n\tv_mov_b32 v1, 0\n" + body) | ||
| 217 | with warnings.catch_warnings(): | ||
| 218 | warnings.simplefilter("ignore", ResourceWarning) | ||
| 219 | spv = rdna2spirv.translate(src) | ||
| 220 | return si.run_fragment(spv, memory=memory)["%out_mrt0"] | ||
| 221 | |||
| 222 | |||
| 223 | def load(fmt: int, dst_sel: int, d16: bool = False) -> tuple: | ||
| 224 | regs, dst = ("v[2:3]", "v2, v3, v2, v3") if d16 else ("v[2:5]", "v2, v3, v4, v5") | ||
| 225 | body = (f"\tbuffer_load_format_{'d16_' if d16 else ''}xyzw {regs}, v1, s[0:3], 0 offen\n" | ||
| 226 | f"\ts_waitcnt vmcnt(0)\n\texp mrt0 {dst} done vm\n\ts_endpgm\n") | ||
| 227 | return run(fmt, body, dst_sel, {BASE + 4 * i: w for i, w in enumerate(SOURCE)}) | ||
| 228 | |||
| 229 | |||
| 230 | def store(fmt: int, values: tuple, n: int, channels: int) -> tuple: | ||
| 231 | memory = {BASE: 0xDEAD0000, BASE + 4: 0xDEAD0000} | ||
| 232 | movs = "".join(f"\tv_mov_b32 v{2 + i}, {v:#x}\n" for i, v in enumerate(values[:n])) | ||
| 233 | regs = "v2" if n == 1 else f"v[2:{1 + n}]" | ||
| 234 | body = (movs + f"\tbuffer_store_format_{'xyzw'[:n]} {regs}, v1, s[0:3], 0 offen\n" | ||
| 235 | "\texp mrt0 v2, v2, v2, v2 done vm\n\ts_endpgm\n") | ||
| 236 | run(fmt, body, RUNTIME_SEL[channels], memory) | ||
| 237 | return memory[BASE], memory[BASE + 4] | ||
| 238 | |||
| 239 | |||
| 240 | class NarrowIntegerLoads(unittest.TestCase): | ||
| 241 | def test_measured_words(self): | ||
| 242 | for fmt, (xyzw, x011, d16) in LOADS.items(): | ||
| 243 | with self.subTest(fmt=fmt): | ||
| 244 | self.assertEqual(load(fmt, SEL_XYZW), xyzw, "DST_SEL XYZW") | ||
| 245 | self.assertEqual(load(fmt, SEL_X011), x011, "DST_SEL X011: 0 and integer 1") | ||
| 246 | self.assertEqual(load(fmt, SEL_XYZW, d16=True)[:2], d16, "d16") | ||
| 247 | |||
| 248 | |||
| 249 | class NarrowIntegerStores(unittest.TestCase): | ||
| 250 | def test_measured_words(self): | ||
| 251 | for (fmt, values, n), want in STORES.items(): | ||
| 252 | with self.subTest(fmt=fmt, values=values, n=n): | ||
| 253 | self.assertEqual(store(fmt, VALUES[values], n, CHANNELS[fmt]), want) | ||
| 254 | |||
| 255 | |||
| 256 | if __name__ == "__main__": | ||
| 257 | unittest.main() | ||
diff --git a/tests/semantic/test_buffer_load_format.py b/tests/semantic/test_buffer_load_format.py index c5cf73a70..30f32bb31 100644 --- a/tests/semantic/test_buffer_load_format.py +++ b/tests/semantic/test_buffer_load_format.py | |||
| @@ -33,6 +33,7 @@ MEMORY = {BASE: 0x11223344, BASE + 4: 0xDEADBEEF, BASE + 8: 0xCAFEF00D, BASE + 1 | |||
| 33 | # V# FORMAT codes (word3 bits 12-18), from rdna2spirv.FORMATS | 33 | # V# FORMAT codes (word3 bits 12-18), from rdna2spirv.FORMATS |
| 34 | FMT_U32, FMT_U32X2, FMT_U32X4, FMT_UINT8X4, FMT_UINT16X2, FMT_UINT16X4, FMT_F16 = 20, 62, 75, 60, 27, 69, 13 | 34 | FMT_U32, FMT_U32X2, FMT_U32X4, FMT_UINT8X4, FMT_UINT16X2, FMT_UINT16X4, FMT_F16 = 20, 62, 75, 60, 27, 69, 13 |
| 35 | FMT_F32, FMT_F32X2, FMT_F32X3, FMT_UNORM8, FMT_UNORM8X4 = 22, 64, 74, 1, 56 | 35 | FMT_F32, FMT_F32X2, FMT_F32X3, FMT_UNORM8, FMT_UNORM8X4 = 22, 64, 74, 1, 56 |
| 36 | FMT_UNORM16, FMT_SNORM16, FMT_UNORM16X2 = 7, 8, 23 | ||
| 36 | DST_SEL_XYZW = 4 | 5 << 3 | 6 << 6 | 7 << 9 | 37 | DST_SEL_XYZW = 4 | 5 << 3 | 6 << 6 | 7 << 9 |
| 37 | # DST_SEL (X, 0, 1, 1): code 4, 0, 1, 1 — SHADER-86 measures float 1.0 vs integer 1 | 38 | # DST_SEL (X, 0, 1, 1): code 4, 0, 1, 1 — SHADER-86 measures float 1.0 vs integer 1 |
| 38 | DST_SEL_X_0_1_1 = 4 | 0 << 3 | 1 << 6 | 1 << 9 | 39 | DST_SEL_X_0_1_1 = 4 | 0 << 3 | 1 << 6 | 1 << 9 |
| @@ -150,9 +151,9 @@ class D16DestinationHalves(unittest.TestCase): | |||
| 150 | 151 | ||
| 151 | 152 | ||
| 152 | class D16NormalizedRounding(unittest.TestCase): | 153 | class D16NormalizedRounding(unittest.TestCase): |
| 153 | """d16 narrows a normalized value to f16 with round to nearest even, like the d16 image results (#489; inferred | 154 | """d16 narrows a normalized value to f16 with round to nearest even (#489; measured for typed buffer loads on an |
| 154 | for the hardware, not measured). These bytes are among the about half of unorm8 values where round toward zero, | 155 | RX 6700, BUILD-161). These bytes are among the about half of unorm8 values where round toward zero, which |
| 155 | which PackHalf2x16 becomes on AMD drivers, gives 1 ulp less.""" | 156 | PackHalf2x16 becomes on AMD drivers, gives 1 ulp less.""" |
| 156 | 157 | ||
| 157 | def test_unorm8_x(self): | 158 | def test_unorm8_x(self): |
| 158 | # byte 5 is 0xbe: 190/255 is 0x39f6 to nearest even, 0x39f5 toward zero | 159 | # byte 5 is 0xbe: 190/255 is 0x39f6 to nearest even, 0x39f5 toward zero |
| @@ -163,6 +164,40 @@ class D16NormalizedRounding(unittest.TestCase): | |||
| 163 | self.assertEqual(load_format(FMT_UNORM8X4, 4, 4, d16=True)[:2], (0x39F63B7F, 0x3AF7396D)) | 164 | self.assertEqual(load_format(FMT_UNORM8X4, 4, 4, d16=True)[:2], (0x39F63B7F, 0x3AF7396D)) |
| 164 | 165 | ||
| 165 | 166 | ||
| 167 | class D16NormalizedRoundsOnce(unittest.TestCase): | ||
| 168 | """BUILD-161, measured on an RX 6700 (gfx1031) with tools/d16_format_probe.py: d16 rounds the exact UNORM/SNORM | ||
| 169 | quotient once, straight to f16. The f32 decode followed by f16_bits rounds twice, which is 1 ulp high where the | ||
| 170 | f32 lands exactly on an f16 halfway point: UNORM16 0xffaf and 0xffef, SNORM16 0x7ff7 and 0x8009.""" | ||
| 171 | |||
| 172 | def d16_x(self, fmt, half, op="buffer_load_format", mods=""): | ||
| 173 | return load_format(fmt, 0, 1, memory={BASE: half}, d16=True, op=op, mods=mods)[0] | ||
| 174 | |||
| 175 | def test_unorm16_and_snorm16_halfway_values(self): | ||
| 176 | for fmt, half, want in ((FMT_UNORM16, 0xFFEF, 0x3BFF), (FMT_UNORM16, 0xFFAF, 0x3BFD), | ||
| 177 | (FMT_SNORM16, 0x7FF7, 0x3BFF), (FMT_SNORM16, 0x8009, 0xBBFF)): | ||
| 178 | with self.subTest(fmt=fmt, half=hex(half)): | ||
| 179 | self.assertEqual(self.d16_x(fmt, half), 0x12340000 | want) | ||
| 180 | |||
| 181 | def test_mtbuf_takes_the_same_rule(self): | ||
| 182 | self.assertEqual(self.d16_x(FMT_UNORM16, 0xFFEF, "tbuffer_load_format", " format:[BUF_FMT_16_UNORM]"), | ||
| 183 | 0x12343BFF) | ||
| 184 | self.assertEqual(self.d16_x(FMT_SNORM16, 0x8009, "tbuffer_load_format", " format:[BUF_FMT_16_SNORM]"), | ||
| 185 | 0x1234BBFF) | ||
| 186 | |||
| 187 | def test_neighbours_and_the_f32_result_are_unchanged(self): | ||
| 188 | self.assertEqual(self.d16_x(FMT_UNORM16, 0xFFEE), 0x12343BFF) # 65518/65535: not a halfway f32 | ||
| 189 | self.assertEqual(self.d16_x(FMT_UNORM16, 0xFFFF), 0x12343C00) | ||
| 190 | self.assertEqual(load_format(FMT_UNORM16, 0, 1, memory={BASE: 0xFFEF})[0], 0x3F7FF000) | ||
| 191 | |||
| 192 | def test_a_float_format_on_the_halfway_value_still_ties_to_even(self): | ||
| 193 | self.assertEqual(self.d16_x(FMT_F32, 0x3F7FF000), 0x12343C00) | ||
| 194 | self.assertEqual(self.d16_x(FMT_F32, 0xBF7FB000), 0x1234BBFE) | ||
| 195 | |||
| 196 | def test_both_halves_of_a_pair(self): | ||
| 197 | got = load_format(FMT_UNORM16X2, 0, 2, memory={BASE: 0xFFAF << 16 | 0xFFEF}, d16=True)[0] | ||
| 198 | self.assertEqual(got, 0x3BFD3BFF) | ||
| 199 | |||
| 200 | |||
| 166 | class CrossingDwordBoundary(unittest.TestCase): | 201 | class CrossingDwordBoundary(unittest.TestCase): |
| 167 | """An element that starts mid-dword must read the following dwords, not re-read dword 0. | 202 | """An element that starts mid-dword must read the following dwords, not re-read dword 0. |
| 168 | 203 | ||
diff --git a/tests/semantic/test_f16_interp_fallback.py b/tests/semantic/test_f16_interp_fallback.py index 5565252ea..3eb9c8b5d 100644 --- a/tests/semantic/test_f16_interp_fallback.py +++ b/tests/semantic/test_f16_interp_fallback.py | |||
| @@ -3,8 +3,9 @@ | |||
| 3 | By default a location any *_f16 interp reads is a PerVertexKHR vec4[3] of the producer's raw words, decoded and | 3 | By default a location any *_f16 interp reads is a PerVertexKHR vec4[3] of the producer's raw words, decoded and |
| 4 | weighted in the PS (test_interp_f16_high.py). MoltenVK can't compile that decoration to MSL ("PerVertexKHR decoration | 4 | weighted in the PS (test_interp_f16_high.py). MoltenVK can't compile that decoration to MSL ("PerVertexKHR decoration |
| 5 | is not supported in MSL"), so with the flag the producer (VS `exp paramN`, mesh params) also exports each channel's two | 5 | is not supported in MSL"), so with the flag the producer (VS `exp paramN`, mesh params) also exports each channel's two |
| 6 | f16 halves decoded to f32, low halves at location 29 - 2N and high halves at 30 - 2N, and the PS reads them as ordinary | 6 | f16 halves decoded to f32, low halves at location 28 - 2N and high halves at 29 - 2N, and the PS reads them as ordinary |
| 7 | smooth inputs. Interpolating the decoded halves is the same P0 + i(P1 - P0) + j(P2 - P0). Here: | 7 | smooth inputs (the top is 29: MoltenVK's maxVertexOutputComponents, 124, counts gl_Position; SHADER-291). |
| 8 | Interpolating the decoded halves is the same P0 + i(P1 - P0) + j(P2 - P0). Here: | ||
| 8 | * the PS has no PerVertexKHR, no barycentric builtin, and reads 1.75 / 9.0 from the decoded-half inputs (the | 9 | * the PS has no PerVertexKHR, no barycentric builtin, and reads 1.75 / 9.0 from the decoded-half inputs (the |
| 9 | per-vertex values of test_interp_f16_high.py, interpolated as Vulkan would), the f32 control and the flat raw read | 10 | per-vertex values of test_interp_f16_high.py, interpolated as Vulkan would), the f32 control and the flat raw read |
| 10 | unchanged; | 11 | unchanged; |
| @@ -15,6 +16,7 @@ smooth inputs. Interpolating the decoded halves is the same P0 + i(P1 - P0) + j( | |||
| 15 | The GPU check is runtime/test/shaders/ps_interp_f16_high drawn with vs_f16_pack, which run_gpu_tests.py translates | 16 | The GPU check is runtime/test/shaders/ps_interp_f16_high drawn with vs_f16_pack, which run_gpu_tests.py translates |
| 16 | with the flag where tools/vk_subgroup_info.py reports per_vertex_inputs false (MoltenVK). | 17 | with the flag where tools/vk_subgroup_info.py reports per_vertex_inputs false (MoltenVK). |
| 17 | """ | 18 | """ |
| 19 | import re | ||
| 18 | import struct | 20 | import struct |
| 19 | import unittest | 21 | import unittest |
| 20 | 22 | ||
| @@ -82,11 +84,11 @@ class FallbackPixelShader(unittest.TestCase): | |||
| 82 | self.assertNotIn("fragmentShaderBarycentric", self.meta["features"]) | 84 | self.assertNotIn("fragmentShaderBarycentric", self.meta["features"]) |
| 83 | 85 | ||
| 84 | def test_decoded_half_inputs(self): | 86 | def test_decoded_half_inputs(self): |
| 85 | self.assertIn("OpDecorate %in_f16h0_0 Location 29", self.spv) | 87 | self.assertIn("OpDecorate %in_f16h0_0 Location 28", self.spv) |
| 86 | self.assertIn("OpDecorate %in_f16h0_1 Location 30", self.spv) | 88 | self.assertIn("OpDecorate %in_f16h0_1 Location 29", self.spv) |
| 87 | self.assertNotIn("%in_f16h0_0 Flat", self.spv) | 89 | self.assertNotIn("%in_f16h0_0 Flat", self.spv) |
| 88 | self.assertEqual(self.meta["f16_halves"], {"0": [29, 30]}) | 90 | self.assertEqual(self.meta["f16_halves"], {"0": [28, 29]}) |
| 89 | self.assertEqual(self.meta["inputs"], [0, 1, 29, 30]) | 91 | self.assertEqual(self.meta["inputs"], [0, 1, 28, 29]) |
| 90 | 92 | ||
| 91 | def test_values(self): | 93 | def test_values(self): |
| 92 | words = support.mrt0_words(self.spv, inputs=self.inputs()) | 94 | words = support.mrt0_words(self.spv, inputs=self.inputs()) |
| @@ -102,9 +104,9 @@ class FallbackPixelShader(unittest.TestCase): | |||
| 102 | self.assertEqual([f"{w & 0xFFFF:#06x}" for w in words[:2]], ["0x3f00", "0x3f00"]) | 104 | self.assertEqual([f"{w & 0xFFFF:#06x}" for w in words[:2]], ["0x3f00", "0x3f00"]) |
| 103 | 105 | ||
| 104 | def test_location_clash_is_rejected(self): | 106 | def test_location_clash_is_rejected(self): |
| 105 | """attr29 read as f32 sits where attr0's low halves go: refuse instead of reading the wrong data.""" | 107 | """attr28 read as f32 sits where attr0's low halves go: refuse instead of reading the wrong data.""" |
| 106 | clash = ["v_interp_p1ll_f16 v2, v0, attr0.x", "v_interp_p2_f16 v2, v1, attr0.x, v2", | 108 | clash = ["v_interp_p1ll_f16 v2, v0, attr0.x", "v_interp_p2_f16 v2, v1, attr0.x, v2", |
| 107 | "v_interp_p1_f32_e32 v3, v0, attr29.x", "v_interp_p2_f32_e32 v3, v1, attr29.x", | 109 | "v_interp_p1_f32_e32 v3, v0, attr28.x", "v_interp_p2_f32_e32 v3, v1, attr28.x", |
| 108 | "exp mrt0 v2, v3, v3, v3 done vm", "s_endpgm"] | 110 | "exp mrt0 v2, v3, v3, v3 done vm", "s_endpgm"] |
| 109 | with self.assertRaises(rdna2spirv.Unsupported): | 111 | with self.assertRaises(rdna2spirv.Unsupported): |
| 110 | translate("ps_f16_clash", clash) | 112 | translate("ps_f16_clash", clash) |
| @@ -119,10 +121,10 @@ class FallbackPixelShader(unittest.TestCase): | |||
| 119 | class FallbackVertexShader(unittest.TestCase): | 121 | class FallbackVertexShader(unittest.TestCase): |
| 120 | def test_exports_decoded_halves(self): | 122 | def test_exports_decoded_halves(self): |
| 121 | spv, meta = translate("vs_f16_fallback", VS.splitlines()) | 123 | spv, meta = translate("vs_f16_fallback", VS.splitlines()) |
| 122 | for n, lo, hi in ((0, 29, 30), (1, 27, 28)): | 124 | for n, lo, hi in ((0, 28, 29), (1, 26, 27)): |
| 123 | self.assertIn(f"OpDecorate %out_f16h{n}_0 Location {lo}", spv) | 125 | self.assertIn(f"OpDecorate %out_f16h{n}_0 Location {lo}", spv) |
| 124 | self.assertIn(f"OpDecorate %out_f16h{n}_1 Location {hi}", spv) | 126 | self.assertIn(f"OpDecorate %out_f16h{n}_1 Location {hi}", spv) |
| 125 | self.assertEqual(meta["f16_halves"], {"0": [29, 30], "1": [27, 28]}) | 127 | self.assertEqual(meta["f16_halves"], {"0": [28, 29], "1": [26, 27]}) |
| 126 | for vid in range(3): | 128 | for vid in range(3): |
| 127 | out = run_fragment(spv, inputs={"%vertex_index": vid, "%instance_index": 0}) | 129 | out = run_fragment(spv, inputs={"%vertex_index": vid, "%instance_index": 0}) |
| 128 | u, v = float((vid << 1) & 2), float(vid & 2) | 130 | u, v = float((vid << 1) & 2), float(vid & 2) |
| @@ -137,13 +139,31 @@ class FallbackVertexShader(unittest.TestCase): | |||
| 137 | self.assertEqual(list(out["%out_param1"])[:2], [support_bits(u), support_bits(v)]) | 139 | self.assertEqual(list(out["%out_param1"])[:2], [support_bits(u), support_bits(v)]) |
| 138 | 140 | ||
| 139 | def test_halves_never_overlap_the_shaders_params(self): | 141 | def test_halves_never_overlap_the_shaders_params(self): |
| 140 | """param29 occupies location 29, so param0's halves (29, 30) are left out; nothing else moves.""" | 142 | """param28 occupies location 28, so param0's halves (28, 29) are left out; nothing else moves.""" |
| 141 | spv, meta = translate("vs_f16_far", ["v_mov_b32_e32 v1, 1.0", "exp pos0 v1, v1, v1, v1 done", | 143 | spv, meta = translate("vs_f16_far", ["v_mov_b32_e32 v1, 1.0", "exp pos0 v1, v1, v1, v1 done", |
| 142 | "exp param0 v1, v1, v1, v1", "exp param29 v1, v1, v1, v1", | 144 | "exp param0 v1, v1, v1, v1", "exp param28 v1, v1, v1, v1", |
| 143 | "s_endpgm"]) | 145 | "s_endpgm"]) |
| 144 | self.assertNotIn("%out_f16h0", spv) | 146 | self.assertNotIn("%out_f16h0", spv) |
| 145 | self.assertNotIn("f16_halves", meta) | 147 | self.assertNotIn("f16_halves", meta) |
| 146 | self.assertIn("OpDecorate %out_param29 Location 29", spv) | 148 | self.assertIn("OpDecorate %out_param28 Location 28", spv) |
| 149 | |||
| 150 | def test_halves_fit_just_above_the_shaders_params(self): | ||
| 151 | """param27 ends at location 27, so param0's halves still fit at 28 and 29.""" | ||
| 152 | spv, meta = translate("vs_f16_near", ["v_mov_b32_e32 v1, 1.0", "exp pos0 v1, v1, v1, v1 done", | ||
| 153 | "exp param0 v1, v1, v1, v1", "exp param27 v1, v1, v1, v1", | ||
| 154 | "s_endpgm"]) | ||
| 155 | self.assertEqual(meta["f16_halves"], {"0": [28, 29]}) | ||
| 156 | self.assertIn("OpDecorate %out_param27 Location 27", spv) | ||
| 157 | |||
| 158 | def test_top_half_fits_moltenvk_output_budget(self): | ||
| 159 | """SHADER-291: MoltenVK reports maxVertexOutputComponents = 124, and Metal and the validation layer count | ||
| 160 | gl_Position's 4 in it (VUID-RuntimeSpirv-Location-06272), so the highest location a VS writes must be 29.""" | ||
| 161 | top = rdna2spirv.f16_half_location(0, 1) | ||
| 162 | self.assertEqual(top, 29) | ||
| 163 | self.assertLessEqual((top + 1) * 4 + 4, 124) | ||
| 164 | spv, _ = translate("vs_f16_fallback", VS.splitlines()) | ||
| 165 | locations = [int(m) for m in re.findall(r"OpDecorate %out\S+ Location (\d+)", spv)] | ||
| 166 | self.assertEqual(max(locations), top) | ||
| 147 | 167 | ||
| 148 | def test_off_by_default(self): | 168 | def test_off_by_default(self): |
| 149 | spv, meta = translate("vs_f16_fallback", VS.splitlines(), fallback=False) | 169 | spv, meta = translate("vs_f16_fallback", VS.splitlines(), fallback=False) |
diff --git a/tests/semantic/test_interp_merge_check.py b/tests/semantic/test_interp_merge_check.py index 382955f5f..22156da60 100644 --- a/tests/semantic/test_interp_merge_check.py +++ b/tests/semantic/test_interp_merge_check.py | |||
| @@ -1,4 +1,4 @@ | |||
| 1 | """spirv_mini_interp and spirv_wave_interp reject a module that breaks spirv-val's merge rule. | 1 | """spirv_mini_interp and spirv_wave_interp reject a module that breaks spirv-val's merge or phi rule. |
| 2 | 2 | ||
| 3 | OpSelectionMerge must directly precede OpBranchConditional / OpSwitch, and OpLoopMerge directly precede OpBranch / | 3 | OpSelectionMerge must directly precede OpBranchConditional / OpSwitch, and OpLoopMerge directly precede OpBranch / |
| 4 | OpBranchConditional (SPIR-V 2.16.2). Both interpreters used to skip merges, so #1633's first version, with an | 4 | OpBranchConditional (SPIR-V 2.16.2). Both interpreters used to skip merges, so #1633's first version, with an |
| @@ -74,5 +74,76 @@ class MergeRule(unittest.TestCase): | |||
| 74 | si.check_structure([ok[0]]) | 74 | si.check_structure([ok[0]]) |
| 75 | 75 | ||
| 76 | 76 | ||
| 77 | CS_LINES = ["v_mov_b32_e32 v1, 0x40", "global_load_dword v2, v1, s[0:1]", "s_waitcnt vmcnt(0)", | ||
| 78 | "v_mov_b32_e32 v3, 0", "buffer_store_dword v2, v3, s[0:3], 0 offen", "s_endpgm"] | ||
| 79 | |||
| 80 | |||
| 81 | def cs_spv(): | ||
| 82 | from test_salu64_bitwise_data import translate_cs | ||
| 83 | text = translate_cs(CS_LINES) | ||
| 84 | assert " = OpPhi " in text | ||
| 85 | return text | ||
| 86 | |||
| 87 | |||
| 88 | def run_cs(text): | ||
| 89 | mem = {0x40: 0x1234} | ||
| 90 | si.run_workgroup(text, 1, 64, inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i}, | ||
| 91 | push_constants=[0, 0, 0x1000, 0x31016FAC] + [0] * 32, memory=mem) | ||
| 92 | return mem | ||
| 93 | |||
| 94 | |||
| 95 | class PhiRule(unittest.TestCase): | ||
| 96 | """OpPhi must be the first instructions of its block: only OpLabel or OpPhi before it (SPIR-V 2.16.2).""" | ||
| 97 | |||
| 98 | def test_translated_module_runs(self): | ||
| 99 | self.assertEqual(run_cs(cs_spv())[0], 0x1234) | ||
| 100 | |||
| 101 | def test_phi_after_another_instruction(self): | ||
| 102 | lines = cs_spv().splitlines() | ||
| 103 | k = next(i for i, ln in enumerate(lines) if " = OpPhi " in ln) | ||
| 104 | lines[k], lines[k + 1] = lines[k + 1], lines[k] # the phi now follows a non-phi instruction | ||
| 105 | bad = "\n".join(lines) + "\n" | ||
| 106 | with self.assertRaisesRegex(si.InvalidModule, "OpPhi"): | ||
| 107 | run_cs(bad) | ||
| 108 | |||
| 109 | def test_rule_directly(self): | ||
| 110 | lab = (None, "OpLabel", [], "%b = OpLabel") | ||
| 111 | phi = ("%p", "OpPhi", [], "%p = OpPhi %uint %a %x %c %y") | ||
| 112 | add = ("%q", "OpIAdd", [], "%q = OpIAdd %uint %a %a") | ||
| 113 | si.check_structure([lab, phi, phi, add]) | ||
| 114 | with self.assertRaisesRegex(si.InvalidModule, "OpPhi"): | ||
| 115 | si.check_structure([lab, add, phi]) | ||
| 116 | with self.assertRaisesRegex(wi.InvalidModule, "OpPhi"): | ||
| 117 | wi.run_wave("OpFunction %void None %f\n%b = OpLabel\n%q = OpIAdd %uint %a %a\n" | ||
| 118 | "%p = OpPhi %uint %a %x %c %y\nOpReturn\nOpFunctionEnd\n", wave=32) | ||
| 119 | |||
| 120 | |||
| 121 | class FunctionVariableRule(unittest.TestCase): | ||
| 122 | """A Function-storage OpVariable belongs in the function's first block (SPIR-V 2.16.1).""" | ||
| 123 | |||
| 124 | def test_rule_directly(self): | ||
| 125 | lab = (None, "OpLabel", [], "%b = OpLabel") | ||
| 126 | var = ("%v", "OpVariable", ["%_ptr_Function_uint", "Function"], "%v = OpVariable %_ptr_Function_uint Function") | ||
| 127 | br = (None, "OpBranch", ["%c"], "OpBranch %c") | ||
| 128 | si.check_structure([lab, var, br, lab]) | ||
| 129 | with self.assertRaisesRegex(si.InvalidModule, "first block"): | ||
| 130 | si.check_structure([lab, br, lab, var]) | ||
| 131 | # a new function starts counting again | ||
| 132 | fn = ("%f", "OpFunction", [], "%f = OpFunction %void None %t") | ||
| 133 | si.check_structure([fn, lab, br, lab, fn, lab, var]) | ||
| 134 | |||
| 135 | def test_translated_module_with_a_variable_moved(self): | ||
| 136 | lines = cs_spv().splitlines() | ||
| 137 | k = next(i for i, ln in enumerate(lines) if " OpVariable " in ln and " Function" in ln) | ||
| 138 | var = lines.pop(k) | ||
| 139 | last_label = max(i for i, ln in enumerate(lines) if ln.strip().endswith("= OpLabel")) | ||
| 140 | lines.insert(last_label + 1, var) | ||
| 141 | bad = "\n".join(lines) + "\n" | ||
| 142 | with self.assertRaisesRegex(si.InvalidModule, "first block"): | ||
| 143 | run_cs(bad) | ||
| 144 | with self.assertRaisesRegex(wi.InvalidModule, "first block"): | ||
| 145 | wi.run_wave(bad, wave=32) | ||
| 146 | |||
| 147 | |||
| 77 | if __name__ == "__main__": | 148 | if __name__ == "__main__": |
| 78 | unittest.main() | 149 | unittest.main() |
diff --git a/tests/semantic/test_interp_p1lv_f16.py b/tests/semantic/test_interp_p1lv_f16.py index b50e280dd..0ddf9bd74 100644 --- a/tests/semantic/test_interp_p1lv_f16.py +++ b/tests/semantic/test_interp_p1lv_f16.py | |||
| @@ -259,11 +259,11 @@ class InterpP1lvF16HalvesFallbackTests(unittest.TestCase): | |||
| 259 | self.assertNotIn("BaryCoordKHR", spv) | 259 | self.assertNotIn("BaryCoordKHR", spv) |
| 260 | self.assertNotIn("FragmentBarycentricKHR", spv) | 260 | self.assertNotIn("FragmentBarycentricKHR", spv) |
| 261 | self.assertNotIn("fragmentShaderBarycentric", meta["features"]) | 261 | self.assertNotIn("fragmentShaderBarycentric", meta["features"]) |
| 262 | self.assertIn("OpDecorate %in_f16h0_0 Location 29", spv) | 262 | self.assertIn("OpDecorate %in_f16h0_0 Location 28", spv) |
| 263 | self.assertIn("OpDecorate %in_f16h0_1 Location 30", spv) | 263 | self.assertIn("OpDecorate %in_f16h0_1 Location 29", spv) |
| 264 | self.assertNotIn("OpDecorate %in_f16h0_0 Flat", spv) | 264 | self.assertNotIn("OpDecorate %in_f16h0_0 Flat", spv) |
| 265 | self.assertEqual(meta["f16_halves"], {"0": [29, 30]}) | 265 | self.assertEqual(meta["f16_halves"], {"0": [28, 29]}) |
| 266 | self.assertEqual(meta["inputs"], [29, 30]) | 266 | self.assertEqual(meta["inputs"], [28, 29]) |
| 267 | 267 | ||
| 268 | inputs = { | 268 | inputs = { |
| 269 | "%in_f16h0_0": (lerp(LO), 0.5, 3.5, 0.0), # attr0 low: 1.75 (clamped->1.0), 0.5, 3.5 (p1lv f32) | 269 | "%in_f16h0_0": (lerp(LO), 0.5, 3.5, 0.0), # attr0 low: 1.75 (clamped->1.0), 0.5, 3.5 (p1lv f32) |
| @@ -372,9 +372,9 @@ class InterpF16BaryFallbackTests(unittest.TestCase): | |||
| 372 | spv, meta = translate_with_flags("ps_both_flags", P1LV_CLAMP_PAIR, | 372 | spv, meta = translate_with_flags("ps_both_flags", P1LV_CLAMP_PAIR, |
| 373 | dxbc=PS_ATTR01_DXBC, bary_fallback=True, f16_halves=True) | 373 | dxbc=PS_ATTR01_DXBC, bary_fallback=True, f16_halves=True) |
| 374 | self.assertNotIn("PerVertexKHR", spv) | 374 | self.assertNotIn("PerVertexKHR", spv) |
| 375 | self.assertIn("OpDecorate %in_f16h0_0 Location 29", spv) | 375 | self.assertIn("OpDecorate %in_f16h0_0 Location 28", spv) |
| 376 | self.assertIn("OpDecorate %in_f16h0_1 Location 30", spv) | 376 | self.assertIn("OpDecorate %in_f16h0_1 Location 29", spv) |
| 377 | self.assertEqual(meta["f16_halves"], {"0": [29, 30]}) | 377 | self.assertEqual(meta["f16_halves"], {"0": [28, 29]}) |
| 378 | 378 | ||
| 379 | 379 | ||
| 380 | class InterpF16GuardsAndRejectionsTests(unittest.TestCase): | 380 | class InterpF16GuardsAndRejectionsTests(unittest.TestCase): |
diff --git a/tests/semantic/test_mask_src_sgpr_const.py b/tests/semantic/test_mask_src_sgpr_const.py new file mode 100644 index 000000000..ddeaff21f --- /dev/null +++ b/tests/semantic/test_mask_src_sgpr_const.py | |||
| @@ -0,0 +1,114 @@ | |||
| 1 | """A constant lane mask that reaches a mask consumer through an SGPR: lane L takes bit L of the constant. | ||
| 2 | |||
| 3 | `s_mov_b32 s20, 0x3ffffc00; s_and_saveexec_b32 s6, s20` leaves lanes 10..29 active on hardware. Gen.mask_src read the | ||
| 4 | SGPR's raw value, which is the same non-zero constant in every invocation, so every lane stayed on (found writing | ||
| 5 | #1771's GPU test; the immediate form `s_and_saveexec_b32 s6, 0x3ffffc00` was already right). Each case runs a | ||
| 6 | translated pixel shader in tests/semantic/spirv_wave_interp.py as one wave and compares every lane with the | ||
| 7 | immediate form and with the bits of the constant. Masks built by compares still work (they hold 0 / ~0 per lane). | ||
| 8 | Standard library only; no GPU, no game files. | ||
| 9 | """ | ||
| 10 | import os | ||
| 11 | import sys | ||
| 12 | import unittest | ||
| 13 | |||
| 14 | HERE = os.path.dirname(os.path.abspath(__file__)) | ||
| 15 | sys.dont_write_bytecode = True | ||
| 16 | sys.path.insert(0, HERE) | ||
| 17 | |||
| 18 | from test_salu64_bitwise_data import run_ps_wave # noqa: E402 (also puts tools/ on sys.path) | ||
| 19 | |||
| 20 | EPILOGUE = ["v_mov_b32 v0, 0", "v_mov_b32 v2, 0", "v_mov_b32 v3, 0"] | ||
| 21 | |||
| 22 | |||
| 23 | def active_lanes(lines, wave): | ||
| 24 | """Lanes whose v1 ends as 0x22: the ones the mask under test left active.""" | ||
| 25 | outs, _ = run_ps_wave(["v_mov_b32 v1, 0x11"] + lines + ["v_mov_b32 v1, 0x22", f"s_mov_b{wave} exec, -1"] + | ||
| 26 | EPILOGUE, wave=wave) | ||
| 27 | return [lane for lane in range(wave) if outs[lane][1] == 0x22] | ||
| 28 | |||
| 29 | |||
| 30 | def bits(v, wave): | ||
| 31 | return [lane for lane in range(wave) if v >> lane & 1] | ||
| 32 | |||
| 33 | |||
| 34 | class SgprConstantMask(unittest.TestCase): | ||
| 35 | def test_saveexec_wave32(self): | ||
| 36 | for c in (0x3FFFFC00, 0x00000001, 0x80000000, 0x0000FF00, 0x55555555): | ||
| 37 | with self.subTest(c=hex(c)): | ||
| 38 | via_sgpr = active_lanes([f"s_mov_b32 s20, {c:#x}", "s_and_saveexec_b32 s6, s20"], 32) | ||
| 39 | via_imm = active_lanes([f"s_and_saveexec_b32 s6, {c:#x}"], 32) | ||
| 40 | self.assertEqual(via_sgpr, bits(c, 32)) | ||
| 41 | self.assertEqual(via_sgpr, via_imm) | ||
| 42 | |||
| 43 | def test_exec_write_and_cndmask(self): | ||
| 44 | c = 0x0F0F00FF | ||
| 45 | self.assertEqual(active_lanes([f"s_mov_b32 s20, {c:#x}", "s_and_b32 exec_lo, exec_lo, s20"], 32), bits(c, 32)) | ||
| 46 | outs, _ = run_ps_wave([f"s_mov_b32 s20, {c:#x}", "v_cndmask_b32_e64 v1, 0, 1, s20"] + EPILOGUE, wave=32) | ||
| 47 | self.assertEqual([lane for lane in range(32) if outs[lane][1] == 1], bits(c, 32)) | ||
| 48 | |||
| 49 | def test_sop2_with_a_constant_and_exec(self): | ||
| 50 | # 32-bit bitwise SOP2 on EXEC with a constant, inline or in an SGPR (both were taken whole before). | ||
| 51 | c, full = 0x0F0F00FF, 0xFFFFFFFF # EXEC starts with every lane on | ||
| 52 | for kind, want in (("and", full & c), ("andn2", full & ~c), ("or", full | c), ("xor", full ^ c)): | ||
| 53 | for src in (f"{c:#x}", "s20"): | ||
| 54 | with self.subTest(op=kind, src=src): | ||
| 55 | lines = [f"s_mov_b32 s20, {c:#x}", f"s_{kind}_b32 exec_lo, exec_lo, {src}"] | ||
| 56 | self.assertEqual(active_lanes(lines, 32), bits(want & full, 32)) | ||
| 57 | |||
| 58 | def test_exec_lo_from_an_sgpr_constant(self): | ||
| 59 | c = 0x00FF00F0 | ||
| 60 | self.assertEqual(active_lanes([f"s_mov_b32 s20, {c:#x}", "s_mov_b32 exec_lo, s20"], 32), bits(c, 32)) | ||
| 61 | |||
| 62 | def test_wave64_pair_takes_each_half_from_its_own_sgpr(self): | ||
| 63 | lo, hi = 0x0000FFFF, 0xF0000000 | ||
| 64 | lanes = active_lanes([f"s_mov_b32 s20, {lo:#x}", f"s_mov_b32 s21, {hi:#x}", | ||
| 65 | "s_and_saveexec_b64 s[6:7], s[20:21]"], 64) | ||
| 66 | self.assertEqual(lanes, bits(lo | hi << 32, 64)) | ||
| 67 | |||
| 68 | def test_masks_from_compares_still_work(self): | ||
| 69 | lines = ["v_mbcnt_lo_u32_b32 v4, -1, 0", "v_cmp_gt_u32_e64 s20, 12, v4", "s_and_saveexec_b32 s6, s20"] | ||
| 70 | self.assertEqual(active_lanes(lines, 32), list(range(12))) | ||
| 71 | lines = ["v_mbcnt_lo_u32_b32 v4, -1, 0", "v_mbcnt_hi_u32_b32 v4, -1, v4", "v_cmp_lt_u32_e64 s[20:21], 40, v4", | ||
| 72 | "s_and_saveexec_b64 s[6:7], s[20:21]"] | ||
| 73 | self.assertEqual(active_lanes(lines, 64), list(range(41, 64))) | ||
| 74 | |||
| 75 | |||
| 76 | class MaskAndConstantIntoAnSgpr(unittest.TestCase): | ||
| 77 | """@Pierre-Kookis's case on #1792 (GPU-reproduced on AMD RDNA2 and an RTX 4070 Ti SUPER): an SOP2 of EXEC with a | ||
| 78 | constant into a plain SGPR is data, and s_bcnt1 counts the wave's bits. The first version of this fix put each | ||
| 79 | lane's bit there and got 32 / 0 instead of 1 / 8.""" | ||
| 80 | |||
| 81 | def test_s_and_of_exec_with_a_constant_counts_the_wave_bits(self): | ||
| 82 | import struct | ||
| 83 | import tempfile | ||
| 84 | import warnings | ||
| 85 | import spirv_mini_interp as si | ||
| 86 | from support import STUB_DXBC, rdna2spirv | ||
| 87 | lines = ["s_and_b32 s20, exec_lo, 1", "s_bcnt1_i32_b32 s21, s20", "s_and_b32 s22, exec_lo, 0xff00", | ||
| 88 | "s_bcnt1_i32_b32 s23, s22", "v_lshlrev_b32 v3, 3, v0", "v_mov_b32_e32 v1, s21", | ||
| 89 | "buffer_store_dword v1, v3, s[0:3], 0 offen", "v_add_nc_u32 v3, 4, v3", "v_mov_b32_e32 v1, s23", | ||
| 90 | "buffer_store_dword v1, v3, s[0:3], 0 offen", "s_endpgm"] | ||
| 91 | with tempfile.TemporaryDirectory() as tmp: | ||
| 92 | os.mkdir(os.path.join(tmp, "disasm")) | ||
| 93 | os.mkdir(os.path.join(tmp, "fssm")) | ||
| 94 | with open(os.path.join(tmp, "cs_bcnt.dxbc"), "wb") as f: | ||
| 95 | f.write(STUB_DXBC) | ||
| 96 | hdr = bytearray(0x148) | ||
| 97 | struct.pack_into("<4I", hdr, 0x138, 0x88, 32, 1, 1) | ||
| 98 | with open(os.path.join(tmp, "fssm", "cs_bcnt.fssm"), "wb") as f: | ||
| 99 | f.write(hdr) | ||
| 100 | src = os.path.join(tmp, "disasm", "cs_bcnt.s") | ||
| 101 | with open(src, "w", encoding="utf-8") as f: | ||
| 102 | f.write("; cs_bcnt\n" + "".join(f"\t{ln}\n" for ln in lines)) | ||
| 103 | with warnings.catch_warnings(): | ||
| 104 | warnings.simplefilter("ignore", ResourceWarning) | ||
| 105 | spv = rdna2spirv.translate(src) | ||
| 106 | mem = si.run_workgroup(spv, 32, 32, inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), | ||
| 107 | "%sg_lane": i}, | ||
| 108 | push_constants=[0, 0, 0x1000, 0x31016FAC] + [0] * 28, memory={}) | ||
| 109 | for lane in range(32): | ||
| 110 | self.assertEqual((mem[8 * lane], mem[8 * lane + 4]), (1, 8), f"lane {lane}") | ||
| 111 | |||
| 112 | |||
| 113 | if __name__ == "__main__": | ||
| 114 | unittest.main() | ||
diff --git a/tests/semantic/test_scalar_noop_waitcnt.py b/tests/semantic/test_scalar_noop_waitcnt.py new file mode 100644 index 000000000..67b805220 --- /dev/null +++ b/tests/semantic/test_scalar_noop_waitcnt.py | |||
| @@ -0,0 +1,636 @@ | |||
| 1 | """Semantic and translation tests for RDNA2 scalar no-op, hint, waitcnt, and mode instructions. | ||
| 2 | |||
| 3 | Covers the 11 named scalar instructions and their syntax variants in tools/shader_ir.py and tools/rdna2spirv.py: | ||
| 4 | * In rdna2spirv.NOOPS (emits no SPIR-V instructions, preserves VGPRs, SGPRs, VCC, SCC, and EXEC): | ||
| 5 | s_clause, s_delay_alu (RDNA3 hint kept in NOOPS), s_inst_prefetch, s_setprio, s_sleep, | ||
| 6 | s_waitcnt_depctr, s_waitcnt_expcnt, s_waitcnt_lgkmcnt, s_waitcnt_vmcnt, | ||
| 7 | plus the sibling wait/no-op forms s_waitcnt, s_waitcnt_vscnt, s_nop, and v_nop. | ||
| 8 | * Refused mode mnemonics in rdna2spirv._insn: | ||
| 9 | s_denorm_mode and s_round_mode raise Unsupported ("MODE is modelled through s_setreg only"); | ||
| 10 | valid MODE.FP_ROUND[3:2] writes go through s_setreg_imm32_b32 hwreg(HW_REG_MODE, 2, 2), 0|3, | ||
| 11 | which updates %mode_r16 only and leaves VGPRs, SGPRs, VCC, SCC, and EXEC intact, while | ||
| 12 | non-MODE s_setreg* writes emit nothing and other MODE writes stay Unsupported. | ||
| 13 | |||
| 14 | Standard library only (runs with python -I); hand-written RDNA2 listings, no GPU or game data. | ||
| 15 | """ | ||
| 16 | from __future__ import annotations | ||
| 17 | |||
| 18 | import gc | ||
| 19 | import os | ||
| 20 | import struct | ||
| 21 | import sys | ||
| 22 | import tempfile | ||
| 23 | import unittest | ||
| 24 | import warnings | ||
| 25 | |||
| 26 | HERE = os.path.dirname(os.path.abspath(__file__)) | ||
| 27 | ROOT = os.path.dirname(os.path.dirname(HERE)) | ||
| 28 | TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") | ||
| 29 | |||
| 30 | sys.dont_write_bytecode = True | ||
| 31 | for _p in (HERE, TOOLS_DIR): | ||
| 32 | if _p not in sys.path: | ||
| 33 | sys.path.insert(0, _p) | ||
| 34 | |||
| 35 | import rdna2spirv # noqa: E402 | ||
| 36 | import shader_ir # noqa: E402 | ||
| 37 | import spirv_mini_interp as si # noqa: E402 | ||
| 38 | |||
| 39 | M32 = 0xFFFFFFFF | ||
| 40 | STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("<I", 0) + bytes(4) | ||
| 41 | # Raw buffer V# (OOB_SELECT 3, stride 0): any dword offset is in bounds in spirv_mini_interp. | ||
| 42 | VSHARP = [0, 0, 0xFFFFFFFF, 0x31016FAC] | ||
| 43 | |||
| 44 | # Handled scalar no-op/hint/waitcnt instructions and explicit syntax variants accepted by shader_ir.py. | ||
| 45 | SCALAR_NOOP_VARIANTS = [ | ||
| 46 | "s_clause 0x1", | ||
| 47 | "s_clause 0", | ||
| 48 | "s_clause 15", | ||
| 49 | "s_delay_alu 0", | ||
| 50 | "s_delay_alu instid0(VALU_DEP_1) | instskip(NEXT) | instid1(SALU_CYCLE_1)", | ||
| 51 | "s_delay_alu instid0(VALU_DEP_2)", | ||
| 52 | "s_inst_prefetch 0x0", | ||
| 53 | "s_inst_prefetch 0x1", | ||
| 54 | "s_inst_prefetch -1", | ||
| 55 | "s_setprio 0x0", | ||
| 56 | "s_setprio 0x2", | ||
| 57 | "s_setprio 3", | ||
| 58 | "s_sleep 0x0", | ||
| 59 | "s_sleep 0x1", | ||
| 60 | "s_sleep 7", | ||
| 61 | "s_waitcnt_depctr 0xffe3", | ||
| 62 | "s_waitcnt_depctr 0x0", | ||
| 63 | "s_waitcnt_depctr depctr_vm_vsrc(0) depctr_va_sdst(0)", | ||
| 64 | "s_waitcnt_depctr depctr_hold_cnt(0) depctr_sa_sdst(0) depctr_va_vdst(0)", | ||
| 65 | "s_waitcnt_expcnt null, 0x0", | ||
| 66 | "s_waitcnt_expcnt null, 0x7", | ||
| 67 | "s_waitcnt_expcnt 0x0", | ||
| 68 | "s_waitcnt_lgkmcnt null, 0x0", | ||
| 69 | "s_waitcnt_lgkmcnt null, 0x3f", | ||
| 70 | "s_waitcnt_lgkmcnt 0x0", | ||
| 71 | "s_waitcnt_vmcnt null, 0x0", | ||
| 72 | "s_waitcnt_vmcnt null, 0x3f", | ||
| 73 | "s_waitcnt_vmcnt 0x0", | ||
| 74 | # Sibling wait/no-op and non-MODE setreg forms handled alongside them in NOOPS / mode_write. | ||
| 75 | "s_waitcnt vmcnt(0)", | ||
| 76 | "s_waitcnt expcnt(0)", | ||
| 77 | "s_waitcnt lgkmcnt(0)", | ||
| 78 | "s_waitcnt vmcnt(1) lgkmcnt(2)", | ||
| 79 | "s_waitcnt vmcnt(0) expcnt(0) lgkmcnt(0)", | ||
| 80 | "s_waitcnt 0", | ||
| 81 | "s_waitcnt_vscnt null, 0x0", | ||
| 82 | "s_waitcnt_vscnt vscnt(0)", | ||
| 83 | "s_nop 0", | ||
| 84 | "s_nop 0x7", | ||
| 85 | "v_nop", | ||
| 86 | "v_nop_e32", | ||
| 87 | "v_nop_e64", | ||
| 88 | "s_setreg_imm32_b32 hwreg(HW_REG_FLAT_SCR_LO, 0, 32), 0", | ||
| 89 | "s_setreg_b32 hwreg(HW_REG_IB_STS), s2", | ||
| 90 | ] | ||
| 91 | |||
| 92 | # Representative instruction per handled mnemonic from the 9-op scalar NOOPS group + s_waitcnt / s_nop. | ||
| 93 | REPRESENTATIVE_NOOPS = [ | ||
| 94 | "s_clause 0x1", | ||
| 95 | "s_delay_alu instid0(VALU_DEP_1) | instskip(NEXT) | instid1(SALU_CYCLE_1)", | ||
| 96 | "s_inst_prefetch 0x0", | ||
| 97 | "s_setprio 0x2", | ||
| 98 | "s_sleep 0x1", | ||
| 99 | "s_waitcnt_depctr 0xffe3", | ||
| 100 | "s_waitcnt_expcnt null, 0x0", | ||
| 101 | "s_waitcnt_lgkmcnt null, 0x0", | ||
| 102 | "s_waitcnt_vmcnt null, 0x0", | ||
| 103 | "s_waitcnt vmcnt(0) expcnt(0) lgkmcnt(0)", | ||
| 104 | "s_waitcnt_vscnt null, 0x0", | ||
| 105 | "s_nop 0", | ||
| 106 | ] | ||
| 107 | |||
| 108 | REFUSED_MODE_VARIANTS = [ | ||
| 109 | "s_denorm_mode 0x3", | ||
| 110 | "s_denorm_mode 0", | ||
| 111 | "s_round_mode 0x3", | ||
| 112 | "s_round_mode 0", | ||
| 113 | ] | ||
| 114 | |||
| 115 | MODELLED_MODE_VARIANTS = [ | ||
| 116 | ("s_setreg_imm32_b32 hwreg(HW_REG_MODE, 2, 2), 0", "%c0"), | ||
| 117 | ("s_setreg_imm32_b32 hwreg(HW_REG_MODE, 2, 2), 3", "%c3"), | ||
| 118 | ] | ||
| 119 | |||
| 120 | _TMP_DIR: tempfile.TemporaryDirectory | None = None | ||
| 121 | |||
| 122 | |||
| 123 | def setUpModule() -> None: | ||
| 124 | global _TMP_DIR | ||
| 125 | _TMP_DIR = tempfile.TemporaryDirectory() | ||
| 126 | os.mkdir(os.path.join(_TMP_DIR.name, "disasm")) | ||
| 127 | os.mkdir(os.path.join(_TMP_DIR.name, "fssm")) | ||
| 128 | |||
| 129 | |||
| 130 | def tearDownModule() -> None: | ||
| 131 | global _TMP_DIR | ||
| 132 | if _TMP_DIR is not None: | ||
| 133 | gc.collect() | ||
| 134 | _TMP_DIR.cleanup() | ||
| 135 | _TMP_DIR = None | ||
| 136 | |||
| 137 | |||
| 138 | def _ensure_dir() -> str: | ||
| 139 | if _TMP_DIR is None: | ||
| 140 | setUpModule() | ||
| 141 | assert _TMP_DIR is not None | ||
| 142 | return _TMP_DIR.name | ||
| 143 | |||
| 144 | |||
| 145 | def make_fssm(threads: int, user_sgprs: int = 4) -> bytes: | ||
| 146 | """Synthetic compute FSSM header: user_sgprs USER_SGPRs, TGID_X_EN=0, TIDIG_COMP_CNT=0, size=(threads,1,1).""" | ||
| 147 | blob = bytearray(0x148) | ||
| 148 | rsrc2 = (user_sgprs & 31) << 1 | ||
| 149 | struct.pack_into("<4I", blob, 0x138, rsrc2, threads, 1, 1) | ||
| 150 | return bytes(blob) | ||
| 151 | |||
| 152 | |||
| 153 | def translate_ps(name: str, lines: list[str]) -> str: | ||
| 154 | root = _ensure_dir() | ||
| 155 | src = os.path.join(root, "disasm", name + ".s") | ||
| 156 | with open(src, "w", encoding="utf-8", newline="\n") as f: | ||
| 157 | f.write(f"; {name}\n" + "".join(f"\t{ln}\n" for ln in lines)) | ||
| 158 | with open(os.path.join(root, name + ".dxbc"), "wb") as f: | ||
| 159 | f.write(STUB_DXBC) | ||
| 160 | with warnings.catch_warnings(): | ||
| 161 | warnings.simplefilter("ignore", ResourceWarning) | ||
| 162 | return rdna2spirv.translate(src) | ||
| 163 | |||
| 164 | |||
| 165 | def translate_cs(name: str, lines: list[str], threads: int) -> str: | ||
| 166 | root = _ensure_dir() | ||
| 167 | src = os.path.join(root, "disasm", name + ".s") | ||
| 168 | with open(src, "w", encoding="utf-8", newline="\n") as f: | ||
| 169 | f.write(f"; {name}\n" + "".join(f"\t{ln}\n" for ln in lines)) | ||
| 170 | with open(os.path.join(root, name + ".dxbc"), "wb") as f: | ||
| 171 | f.write(STUB_DXBC) | ||
| 172 | with open(os.path.join(root, "fssm", name + ".fssm"), "wb") as f: | ||
| 173 | f.write(make_fssm(threads)) | ||
| 174 | with warnings.catch_warnings(): | ||
| 175 | warnings.simplefilter("ignore", ResourceWarning) | ||
| 176 | return rdna2spirv.translate(src) | ||
| 177 | |||
| 178 | |||
| 179 | def ps_program(middle: list[str], *, scc_one: bool = True, vcc_one: bool = True, | ||
| 180 | exec_lo: int = 0xAAAA5555, add_k: int = 0x10) -> list[str]: | ||
| 181 | """Synthetic PS testing VGPRs, SGPRs, SCC, VCC, and EXEC across interleaved arithmetic and `middle`.""" | ||
| 182 | s_rhs = 5 if scc_one else 0 | ||
| 183 | s_lhs = 0xFFFFFFFF if scc_one else 0x12340000 | ||
| 184 | cmp_val = (0x11112222 + add_k) & M32 if vcc_one else 0x00000000 | ||
| 185 | return [ | ||
| 186 | "v_mov_b32 v0, 0x11112222", | ||
| 187 | "v_mov_b32 v1, 0x33334444", | ||
| 188 | "v_mov_b32 v2, 0x55556666", | ||
| 189 | "v_mov_b32 v3, 0x77778888", | ||
| 190 | f"s_mov_b32 s2, {s_lhs:#x}", | ||
| 191 | f"s_mov_b32 s3, {s_rhs:#x}", | ||
| 192 | "s_add_u32 s4, s2, s3", # SCC = 1 iff s_lhs + s_rhs overflows 32 bits | ||
| 193 | f"v_add_nc_u32 v0, v0, {add_k:#x}", | ||
| 194 | f"v_cmp_eq_u32 vcc_lo, v0, {cmp_val:#x}", # VCC = 1 iff vcc_one | ||
| 195 | f"s_mov_b32 exec_lo, {exec_lo:#x}", | ||
| 196 | *middle, | ||
| 197 | "s_cselect_b32 s5, 0x10000001, 0x20000002", # reads SCC | ||
| 198 | "s_add_u32 s6, s4, s5", # reads SGPR s4 and selected s5 | ||
| 199 | "v_cndmask_b32 v1, 0x99990000, v1, vcc_lo", # reads VCC (and VGPR v1 when VCC=1) | ||
| 200 | "v_add_nc_u32 v2, v2, s6", # reads EXEC, VGPR v2, SGPR s6 | ||
| 201 | "exp mrt0 v0, v1, v2, v3 done vm", | ||
| 202 | "s_endpgm", | ||
| 203 | ] | ||
| 204 | |||
| 205 | |||
| 206 | def expected_ps_mrt0(*, scc_one: bool = True, vcc_one: bool = True, | ||
| 207 | exec_lo: int = 0xAAAA5555, add_k: int = 0x10) -> tuple[int, int, int, int]: | ||
| 208 | """Plain-Python reference for ps_program().""" | ||
| 209 | active = bool(exec_lo & 1) | ||
| 210 | s_lhs = 0xFFFFFFFF if scc_one else 0x12340000 | ||
| 211 | s_rhs = 5 if scc_one else 0 | ||
| 212 | s4 = (s_lhs + s_rhs) & M32 | ||
| 213 | scc = (s_lhs + s_rhs) > M32 | ||
| 214 | v0 = ((0x11112222 + add_k) & M32) # executed while EXEC=1 initially | ||
| 215 | vcc = vcc_one # evaluated while EXEC=1 initially | ||
| 216 | s5 = 0x10000001 if scc else 0x20000002 | ||
| 217 | s6 = (s4 + s5) & M32 | ||
| 218 | v1 = (0x33334444 if vcc else 0x99990000) if active else 0x33334444 | ||
| 219 | v2 = ((0x55556666 + s6) & M32) if active else 0x55556666 | ||
| 220 | v3 = 0x77778888 | ||
| 221 | if not active: | ||
| 222 | return (0, 0, 0, 0) | ||
| 223 | return (v0, v1, v2, v3) | ||
| 224 | |||
| 225 | |||
| 226 | def cs_program(middle: list[str], *, wave64: bool, scc_one: bool = True, | ||
| 227 | exec_lo: int = 0xA5A55A5A, exec_hi: int = 0x3C3C6969) -> list[str]: | ||
| 228 | """Synthetic wave32/wave64 CS checking VGPRs, SGPRs, SCC, VCC, and EXEC across all lanes.""" | ||
| 229 | s_lhs = 0xFFFFFFFF if scc_one else 0x10203040 | ||
| 230 | s_rhs = 3 if scc_one else 1 | ||
| 231 | if wave64: | ||
| 232 | lane_setup = [ | ||
| 233 | "s_mov_b64 exec, -1", | ||
| 234 | "v_mbcnt_lo_u32_b32 v0, -1, 0", | ||
| 235 | "v_mbcnt_hi_u32_b32 v0, -1, v0", | ||
| 236 | ] | ||
| 237 | vcc_cmp = "v_cmp_eq_u32 vcc, v4, 0" | ||
| 238 | set_exec = [f"s_mov_b32 exec_lo, {exec_lo:#x}", f"s_mov_b32 exec_hi, {exec_hi:#x}"] | ||
| 239 | reset_exec = "s_mov_b64 exec, -1" | ||
| 240 | vcc_cnd = "v_cndmask_b32 v2, 0x99990000, v2, vcc" | ||
| 241 | else: | ||
| 242 | lane_setup = [] # v0 is seeded directly from LocalInvocationId.x | ||
| 243 | vcc_cmp = "v_cmp_eq_u32 vcc_lo, v4, 0" | ||
| 244 | set_exec = [f"s_mov_b32 exec_lo, {exec_lo:#x}"] | ||
| 245 | reset_exec = "s_mov_b32 exec_lo, -1" | ||
| 246 | vcc_cnd = "v_cndmask_b32 v2, 0x99990000, v2, vcc_lo" | ||
| 247 | |||
| 248 | return [ | ||
| 249 | *lane_setup, | ||
| 250 | "v_mov_b32 v1, v0", | ||
| 251 | "v_add_nc_u32 v1, v1, 10", | ||
| 252 | "v_mov_b32 v2, 0x77770000", | ||
| 253 | "v_add_nc_u32 v2, v2, v0", | ||
| 254 | "v_mov_b32 v3, 0x1000", | ||
| 255 | "v_and_b32 v4, v0, 1", | ||
| 256 | vcc_cmp, # even lanes: VCC = 1; odd lanes: VCC = 0 | ||
| 257 | "s_mov_b32 s8, 0x01020304", | ||
| 258 | "s_mov_b32 s9, 0x55667788", | ||
| 259 | f"s_mov_b32 s10, {s_lhs:#x}", | ||
| 260 | f"s_add_u32 s11, s10, {s_rhs:#x}", # SCC = 1 iff scc_one | ||
| 261 | *set_exec, | ||
| 262 | *middle, | ||
| 263 | "v_add_nc_u32 v1, v1, 0x100", # updates v1 only in lanes where EXEC=1 | ||
| 264 | "s_cselect_b32 s12, 0x10000, 0x20000", # reads SCC | ||
| 265 | reset_exec, | ||
| 266 | vcc_cnd, # reads VCC across all lanes (even keeps v2, odd gets 0x99990000) | ||
| 267 | "v_add_nc_u32 v3, v3, s8", # reads SGPR s8 | ||
| 268 | "v_add_nc_u32 v3, v3, s12", # reads s12 (SCC outcome) | ||
| 269 | "v_add_nc_u32 v3, v3, s11", # reads s11 (s_add_u32 sum) | ||
| 270 | "v_mov_b32 v4, s9", # reads SGPR s9 | ||
| 271 | "v_lshlrev_b32 v5, 4, v0", # byte offset = 16 * lane | ||
| 272 | "buffer_store_dwordx4 v[1:4], v5, s[0:3], 0 offen", | ||
| 273 | "s_endpgm", | ||
| 274 | ] | ||
| 275 | |||
| 276 | |||
| 277 | def expected_cs_words(lanes: int, *, scc_one: bool = True, | ||
| 278 | exec_lo: int = 0xA5A55A5A, exec_hi: int = 0x3C3C6969) -> list[tuple[int, int, int, int]]: | ||
| 279 | """Plain-Python reference for cs_program().""" | ||
| 280 | s_lhs = 0xFFFFFFFF if scc_one else 0x10203040 | ||
| 281 | s_rhs = 3 if scc_one else 1 | ||
| 282 | s11 = (s_lhs + s_rhs) & M32 | ||
| 283 | s12 = 0x10000 if ((s_lhs + s_rhs) > M32) else 0x20000 | ||
| 284 | exec_mask = (exec_hi << 32) | exec_lo | ||
| 285 | out = [] | ||
| 286 | for lane in range(lanes): | ||
| 287 | active = bool((exec_mask >> lane) & 1) | ||
| 288 | w0 = (lane + 10 + (0x100 if active else 0)) & M32 | ||
| 289 | w1 = (0x77770000 + lane) if (lane % 2 == 0) else 0x99990000 | ||
| 290 | w2 = (0x1000 + 0x01020304 + s12 + s11) & M32 | ||
| 291 | w3 = 0x55667788 | ||
| 292 | out.append((w0, w1, w2, w3)) | ||
| 293 | return out | ||
| 294 | |||
| 295 | |||
| 296 | def run_cs(spv: str, lanes: int) -> list[tuple[int, int, int, int]]: | ||
| 297 | mem = si.run_workgroup( | ||
| 298 | spv, lanes, lanes, | ||
| 299 | inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i}, | ||
| 300 | push_constants=VSHARP + [0] * 28, | ||
| 301 | memory={}, | ||
| 302 | ) | ||
| 303 | return [tuple(mem[16 * lane + 4 * c] for c in range(4)) for lane in range(lanes)] | ||
| 304 | |||
| 305 | |||
| 306 | class ScalarNoopWaitcntParsingTests(unittest.TestCase): | ||
| 307 | """Exact syntax and operand parsing in tools/shader_ir.py for all 11 scalar ops and variants.""" | ||
| 308 | |||
| 309 | def test_parse_all_scalar_noop_waitcnt_and_mode_forms(self): | ||
| 310 | cases = [ | ||
| 311 | ("s_clause 0x1", "s_clause", [{"k": "imm", "v": 1}]), | ||
| 312 | ("s_delay_alu 0", "s_delay_alu", [{"k": "imm", "v": 0}]), | ||
| 313 | ( | ||
| 314 | "s_delay_alu instid0(VALU_DEP_1) | instskip(NEXT) | instid1(SALU_CYCLE_1)", | ||
| 315 | "s_delay_alu", | ||
| 316 | [{"k": "special", "t": "instid0(VALU_DEP_1) | instskip(NEXT) | instid1(SALU_CYCLE_1)"}], | ||
| 317 | ), | ||
| 318 | ("s_denorm_mode 0x3", "s_denorm_mode", [{"k": "imm", "v": 3}]), | ||
| 319 | ("s_inst_prefetch 0x0", "s_inst_prefetch", [{"k": "imm", "v": 0}]), | ||
| 320 | ("s_inst_prefetch -1", "s_inst_prefetch", [{"k": "imm", "v": -1}]), | ||
| 321 | ("s_round_mode 0x3", "s_round_mode", [{"k": "imm", "v": 3}]), | ||
| 322 | ("s_setprio 0x2", "s_setprio", [{"k": "imm", "v": 2}]), | ||
| 323 | ("s_sleep 0x1", "s_sleep", [{"k": "imm", "v": 1}]), | ||
| 324 | ("s_waitcnt_depctr 0xffe3", "s_waitcnt_depctr", [{"k": "imm", "v": 0xFFE3}]), | ||
| 325 | ( | ||
| 326 | "s_waitcnt_depctr depctr_vm_vsrc(0) depctr_va_sdst(0)", | ||
| 327 | "s_waitcnt_depctr", | ||
| 328 | [{"k": "special", "t": "depctr_vm_vsrc(0)"}, {"k": "special", "t": "depctr_va_sdst(0)"}], | ||
| 329 | ), | ||
| 330 | ( | ||
| 331 | "s_waitcnt_expcnt null, 0x0", | ||
| 332 | "s_waitcnt_expcnt", | ||
| 333 | [{"k": "special", "t": "null", "neg": False, "abs": False}, {"k": "imm", "v": 0}], | ||
| 334 | ), | ||
| 335 | ( | ||
| 336 | "s_waitcnt_lgkmcnt null, 0x3f", | ||
| 337 | "s_waitcnt_lgkmcnt", | ||
| 338 | [{"k": "special", "t": "null", "neg": False, "abs": False}, {"k": "imm", "v": 0x3F}], | ||
| 339 | ), | ||
| 340 | ( | ||
| 341 | "s_waitcnt_vmcnt null, 0x0", | ||
| 342 | "s_waitcnt_vmcnt", | ||
| 343 | [{"k": "special", "t": "null", "neg": False, "abs": False}, {"k": "imm", "v": 0}], | ||
| 344 | ), | ||
| 345 | ( | ||
| 346 | "s_waitcnt_vscnt null, 0x0", | ||
| 347 | "s_waitcnt_vscnt", | ||
| 348 | [{"k": "special", "t": "null", "neg": False, "abs": False}, {"k": "imm", "v": 0}], | ||
| 349 | ), | ||
| 350 | ("s_waitcnt vmcnt(0)", "s_waitcnt", [{"k": "special", "t": "vmcnt(0)"}]), | ||
| 351 | ("s_waitcnt expcnt(0)", "s_waitcnt", [{"k": "special", "t": "expcnt(0)"}]), | ||
| 352 | ("s_waitcnt lgkmcnt(0)", "s_waitcnt", [{"k": "special", "t": "lgkmcnt(0)"}]), | ||
| 353 | ( | ||
| 354 | "s_waitcnt vmcnt(1) lgkmcnt(2)", | ||
| 355 | "s_waitcnt", | ||
| 356 | [{"k": "special", "t": "vmcnt(1)"}, {"k": "special", "t": "lgkmcnt(2)"}], | ||
| 357 | ), | ||
| 358 | ( | ||
| 359 | "s_waitcnt vmcnt(0) expcnt(0) lgkmcnt(0)", | ||
| 360 | "s_waitcnt", | ||
| 361 | [{"k": "special", "t": "vmcnt(0) expcnt(0) lgkmcnt(0)"}], | ||
| 362 | ), | ||
| 363 | ("s_waitcnt 0", "s_waitcnt", [{"k": "imm", "v": 0}]), | ||
| 364 | ( | ||
| 365 | "s_setreg_imm32_b32 hwreg(HW_REG_MODE, 2, 2), 3", | ||
| 366 | "s_setreg_imm32_b32", | ||
| 367 | [{"k": "special", "t": "hwreg(HW_REG_MODE, 2, 2)"}, {"k": "imm", "v": 3}], | ||
| 368 | ), | ||
| 369 | ("s_nop 0", "s_nop", [{"k": "imm", "v": 0}]), | ||
| 370 | ("v_nop", "v_nop", []), | ||
| 371 | ] | ||
| 372 | for text, want_op, want_args in cases: | ||
| 373 | with self.subTest(line=text): | ||
| 374 | parsed = shader_ir.parse_line("\t" + text) | ||
| 375 | self.assertIsNotNone(parsed) | ||
| 376 | self.assertEqual(parsed["op"], want_op) | ||
| 377 | self.assertEqual(parsed["args"], want_args) | ||
| 378 | self.assertEqual(parsed["mods"], []) | ||
| 379 | self.assertTrue(all(arg["k"] != "raw" for arg in parsed["args"])) | ||
| 380 | |||
| 381 | |||
| 382 | class PixelShaderNoopWaitcntTests(unittest.TestCase): | ||
| 383 | """PS translation and spirv_mini_interp execution across all handled NOOPS and waitcnt variants.""" | ||
| 384 | |||
| 385 | def test_variants_emit_no_extra_spirv_and_preserve_state_active_scc1_vcc1(self): | ||
| 386 | baseline = translate_ps("ps_noop_base_11", ps_program([], scc_one=True, vcc_one=True)) | ||
| 387 | want = expected_ps_mrt0(scc_one=True, vcc_one=True) | ||
| 388 | self.assertEqual(want, (0x11112232, 0x33334444, 0x6555666B, 0x77778888)) | ||
| 389 | self.assertEqual(tuple(si.run_fragment(baseline, inputs={"%sg_lane": 0})["%out_mrt0"]), want) | ||
| 390 | self.assertNotIn("OpControlBarrier", baseline) | ||
| 391 | self.assertNotIn("OpMemoryBarrier", baseline) | ||
| 392 | |||
| 393 | for variant in SCALAR_NOOP_VARIANTS: | ||
| 394 | with self.subTest(insn=variant): | ||
| 395 | spv = translate_ps("ps_noop_var", ps_program([variant], scc_one=True, vcc_one=True)) | ||
| 396 | self.assertEqual(spv, baseline, f"{variant} emitted unexpected SPIR-V operations") | ||
| 397 | self.assertEqual(tuple(si.run_fragment(spv, inputs={"%sg_lane": 0})["%out_mrt0"]), want) | ||
| 398 | |||
| 399 | def test_variants_preserve_scc0_and_vcc0(self): | ||
| 400 | baseline = translate_ps("ps_noop_base_00", ps_program([], scc_one=False, vcc_one=False)) | ||
| 401 | want = expected_ps_mrt0(scc_one=False, vcc_one=False) | ||
| 402 | self.assertEqual(want, (0x11112232, 0x99990000, 0x87896668, 0x77778888)) | ||
| 403 | self.assertEqual(tuple(si.run_fragment(baseline, inputs={"%sg_lane": 0})["%out_mrt0"]), want) | ||
| 404 | |||
| 405 | for variant in SCALAR_NOOP_VARIANTS: | ||
| 406 | with self.subTest(insn=variant): | ||
| 407 | spv = translate_ps("ps_noop_var00", ps_program([variant], scc_one=False, vcc_one=False)) | ||
| 408 | self.assertEqual(spv, baseline) | ||
| 409 | self.assertEqual(tuple(si.run_fragment(spv, inputs={"%sg_lane": 0})["%out_mrt0"]), want) | ||
| 410 | |||
| 411 | def test_interleaved_across_every_arithmetic_step(self): | ||
| 412 | base_lines = ps_program([], scc_one=True, vcc_one=True) | ||
| 413 | baseline = translate_ps("ps_interleave_base", base_lines) | ||
| 414 | want = expected_ps_mrt0(scc_one=True, vcc_one=True) | ||
| 415 | interleaved = [ | ||
| 416 | "v_mov_b32 v0, 0x11112222", | ||
| 417 | "v_mov_b32 v1, 0x33334444", | ||
| 418 | "v_mov_b32 v2, 0x55556666", | ||
| 419 | "v_mov_b32 v3, 0x77778888", | ||
| 420 | "s_clause 0x1", | ||
| 421 | "s_mov_b32 s2, 0xffffffff", | ||
| 422 | "s_mov_b32 s3, 5", | ||
| 423 | "s_delay_alu instid0(VALU_DEP_1) | instskip(NEXT) | instid1(SALU_CYCLE_1)", | ||
| 424 | "s_add_u32 s4, s2, s3", | ||
| 425 | "s_inst_prefetch 0x0", | ||
| 426 | "s_setprio 0x2", | ||
| 427 | "v_add_nc_u32 v0, v0, 0x10", | ||
| 428 | "s_sleep 0x1", | ||
| 429 | "v_cmp_eq_u32 vcc_lo, v0, 0x11112232", | ||
| 430 | "s_waitcnt_depctr depctr_vm_vsrc(0) depctr_va_sdst(0)", | ||
| 431 | "s_mov_b32 exec_lo, 0xaaaa5555", | ||
| 432 | "s_waitcnt_expcnt null, 0x0", | ||
| 433 | "s_waitcnt_lgkmcnt null, 0x0", | ||
| 434 | "s_waitcnt_vmcnt null, 0x0", | ||
| 435 | "s_waitcnt vmcnt(0) expcnt(0) lgkmcnt(0)", | ||
| 436 | "s_waitcnt_vscnt null, 0x0", | ||
| 437 | "s_nop 0", | ||
| 438 | "v_nop", | ||
| 439 | "s_cselect_b32 s5, 0x10000001, 0x20000002", | ||
| 440 | "s_add_u32 s6, s4, s5", | ||
| 441 | "v_cndmask_b32 v1, 0x99990000, v1, vcc_lo", | ||
| 442 | "v_add_nc_u32 v2, v2, s6", | ||
| 443 | "exp mrt0 v0, v1, v2, v3 done vm", | ||
| 444 | "s_endpgm", | ||
| 445 | ] | ||
| 446 | spv = translate_ps("ps_interleave", interleaved) | ||
| 447 | self.assertEqual(spv, baseline) | ||
| 448 | self.assertEqual(tuple(si.run_fragment(spv, inputs={"%sg_lane": 0})["%out_mrt0"]), want) | ||
| 449 | |||
| 450 | def test_inactive_exec_stays_zero_for_vgpr_writes_and_exports(self): | ||
| 451 | # Part 1: EXEC=0 around all handled no-ops blocks VGPR writes, then restoring EXEC exports intact values. | ||
| 452 | base_vgpr = [ | ||
| 453 | "v_mov_b32 v0, 0x10000001", | ||
| 454 | "v_mov_b32 v1, 0x20000002", | ||
| 455 | "v_mov_b32 v2, 0x30000003", | ||
| 456 | "v_mov_b32 v3, 0x40000004", | ||
| 457 | "s_mov_b32 exec_lo, 0", | ||
| 458 | "v_add_nc_u32 v2, v2, 0x1234", | ||
| 459 | "v_mov_b32 v3, 0xdeadbeef", | ||
| 460 | "s_mov_b32 exec_lo, -1", | ||
| 461 | "exp mrt0 v0, v1, v2, v3 done vm", | ||
| 462 | "s_endpgm", | ||
| 463 | ] | ||
| 464 | with_noops = base_vgpr[:5] + REPRESENTATIVE_NOOPS + base_vgpr[5:] | ||
| 465 | spv_base = translate_ps("ps_exec0_vgpr_base", base_vgpr) | ||
| 466 | spv_noops = translate_ps("ps_exec0_vgpr_noops", with_noops) | ||
| 467 | self.assertEqual(spv_noops, spv_base) | ||
| 468 | self.assertEqual(tuple(si.run_fragment(spv_noops, inputs={"%sg_lane": 0})["%out_mrt0"]), | ||
| 469 | (0x10000001, 0x20000002, 0x30000003, 0x40000004)) | ||
| 470 | |||
| 471 | # Part 2: EXEC=0 across all handled no-ops keeps the lane inactive through end of shader (OpKill -> {}). | ||
| 472 | base_exp = [ | ||
| 473 | "v_mov_b32 v0, 0x10000001", | ||
| 474 | "v_mov_b32 v1, 0x20000002", | ||
| 475 | "v_mov_b32 v2, 0x30000003", | ||
| 476 | "v_mov_b32 v3, 0x40000004", | ||
| 477 | "exp mrt0 v0, v1, v2, v3 vm", | ||
| 478 | "s_mov_b32 exec_lo, 0xaaaa5554", | ||
| 479 | "v_mov_b32 v0, 0xbad00000", | ||
| 480 | "exp mrt0 v0, v0, v0, v0 done vm", | ||
| 481 | "s_endpgm", | ||
| 482 | ] | ||
| 483 | spv_exp_base = translate_ps("ps_exec0_exp_base", base_exp) | ||
| 484 | spv_exp_noops = translate_ps("ps_exec0_exp_noops", base_exp[:6] + REPRESENTATIVE_NOOPS + base_exp[6:]) | ||
| 485 | self.assertEqual(spv_exp_noops, spv_exp_base) | ||
| 486 | self.assertEqual(si.run_fragment(spv_exp_noops, inputs={"%sg_lane": 0}), {}) | ||
| 487 | |||
| 488 | |||
| 489 | class ComputeShaderNoopWaitcntTests(unittest.TestCase): | ||
| 490 | """FSSM compute shader translation and multi-lane execution (wave32 & wave64).""" | ||
| 491 | |||
| 492 | def test_wave32_each_and_all_preserve_registers_vcc_scc_and_exec(self): | ||
| 493 | for scc_one in (True, False): | ||
| 494 | baseline = translate_cs("cs_w32_base", cs_program([], wave64=False, scc_one=scc_one), threads=32) | ||
| 495 | want = expected_cs_words(32, scc_one=scc_one) | ||
| 496 | self.assertEqual(run_cs(baseline, 32), want) | ||
| 497 | self.assertNotIn("OpControlBarrier", baseline) | ||
| 498 | self.assertNotIn("OpMemoryBarrier", baseline) | ||
| 499 | |||
| 500 | for variant in SCALAR_NOOP_VARIANTS: | ||
| 501 | with self.subTest(scc_one=scc_one, insn=variant): | ||
| 502 | spv = translate_cs("cs_w32_var", cs_program([variant], wave64=False, scc_one=scc_one), threads=32) | ||
| 503 | self.assertEqual(spv, baseline) | ||
| 504 | self.assertEqual(run_cs(spv, 32), want) | ||
| 505 | |||
| 506 | spv_all = translate_cs("cs_w32_all", cs_program(REPRESENTATIVE_NOOPS, wave64=False, scc_one=scc_one), | ||
| 507 | threads=32) | ||
| 508 | self.assertEqual(spv_all, baseline) | ||
| 509 | self.assertEqual(run_cs(spv_all, 32), want) | ||
| 510 | |||
| 511 | def test_wave64_preserves_state_across_all_64_lanes(self): | ||
| 512 | for scc_one in (True, False): | ||
| 513 | baseline = translate_cs("cs_w64_base", cs_program([], wave64=True, scc_one=scc_one), threads=64) | ||
| 514 | want = expected_cs_words(64, scc_one=scc_one) | ||
| 515 | self.assertEqual(run_cs(baseline, 64), want) | ||
| 516 | self.assertNotIn("OpControlBarrier", baseline) | ||
| 517 | self.assertNotIn("OpMemoryBarrier", baseline) | ||
| 518 | |||
| 519 | with self.subTest(scc_one=scc_one): | ||
| 520 | spv_all = translate_cs("cs_w64_all", cs_program(REPRESENTATIVE_NOOPS, wave64=True, scc_one=scc_one), | ||
| 521 | threads=64) | ||
| 522 | self.assertEqual(spv_all, baseline) | ||
| 523 | self.assertEqual(run_cs(spv_all, 64), want) | ||
| 524 | |||
| 525 | |||
| 526 | class ModeInstructionsTests(unittest.TestCase): | ||
| 527 | """Tests for s_denorm_mode, s_round_mode, and s_setreg* hardware MODE writes.""" | ||
| 528 | |||
| 529 | def test_s_denorm_mode_and_s_round_mode_stay_unsupported(self): | ||
| 530 | for insn in REFUSED_MODE_VARIANTS: | ||
| 531 | op = insn.split()[0] | ||
| 532 | with self.subTest(stage="ps", insn=insn): | ||
| 533 | with self.assertRaises(rdna2spirv.Unsupported) as ctx: | ||
| 534 | translate_ps("ps_refused_mode", ps_program([insn])) | ||
| 535 | self.assertIn(op, str(ctx.exception)) | ||
| 536 | self.assertIn("s_setreg", str(ctx.exception)) | ||
| 537 | |||
| 538 | with self.subTest(stage="cs", insn=insn): | ||
| 539 | with self.assertRaises(rdna2spirv.Unsupported) as ctx: | ||
| 540 | translate_cs("cs_refused_mode", cs_program([insn], wave64=False), threads=32) | ||
| 541 | self.assertIn(op, str(ctx.exception)) | ||
| 542 | self.assertIn("s_setreg", str(ctx.exception)) | ||
| 543 | |||
| 544 | def test_s_setreg_mode_fp_round_emits_only_mode_r16_and_preserves_state(self): | ||
| 545 | ps_base = translate_ps("ps_mode_base", ps_program([])) | ||
| 546 | want_ps = expected_ps_mrt0() | ||
| 547 | cs_base = translate_cs("cs_mode_base", cs_program([], wave64=False), threads=32) | ||
| 548 | want_cs = expected_cs_words(32) | ||
| 549 | |||
| 550 | for insn, mode_const in MODELLED_MODE_VARIANTS: | ||
| 551 | with self.subTest(stage="ps", insn=insn): | ||
| 552 | spv = translate_ps("ps_mode_setreg", ps_program([insn])) | ||
| 553 | self.assertIn("%mode_r16 = OpVariable %_ptr_Function_uint Function %c0", spv) | ||
| 554 | self.assertIn(f"OpStore %mode_r16 {mode_const}", spv) | ||
| 555 | self.assertNotIn("OpControlBarrier", spv) | ||
| 556 | # Removing the two mode lines recovers the exact baseline SPIR-V (modulo unused %c3 if added). | ||
| 557 | self.assertEqual(spv.count("OpStore %mode_r16"), 1) | ||
| 558 | self.assertEqual(tuple(si.run_fragment(spv, inputs={"%sg_lane": 0})["%out_mrt0"]), want_ps) | ||
| 559 | self.assertEqual(tuple(si.run_fragment(ps_base, inputs={"%sg_lane": 0})["%out_mrt0"]), want_ps) | ||
| 560 | |||
| 561 | with self.subTest(stage="cs", insn=insn): | ||
| 562 | spv = translate_cs("cs_mode_setreg", cs_program([insn], wave64=False), threads=32) | ||
| 563 | self.assertIn("%mode_r16 = OpVariable %_ptr_Function_uint Function %c0", spv) | ||
| 564 | self.assertIn(f"OpStore %mode_r16 {mode_const}", spv) | ||
| 565 | self.assertEqual(run_cs(spv, 32), want_cs) | ||
| 566 | self.assertEqual(run_cs(cs_base, 32), want_cs) | ||
| 567 | |||
| 568 | def test_unmodelled_s_setreg_mode_forms_raise_unsupported(self): | ||
| 569 | bad_mode_writes = [ | ||
| 570 | "s_setreg_imm32_b32 hwreg(HW_REG_MODE, 0, 2), 3", | ||
| 571 | "s_setreg_imm32_b32 hwreg(HW_REG_MODE, 4, 4), 15", | ||
| 572 | "s_setreg_imm32_b32 hwreg(HW_REG_MODE), 0", | ||
| 573 | "s_setreg_imm32_b32 hwreg(HW_REG_MODE, 2, 2), 1", | ||
| 574 | "s_setreg_imm32_b32 hwreg(HW_REG_MODE, 2, 2), 2", | ||
| 575 | "s_setreg_b32 hwreg(HW_REG_MODE, 2, 2), s2", | ||
| 576 | ] | ||
| 577 | for insn in bad_mode_writes: | ||
| 578 | with self.subTest(insn=insn): | ||
| 579 | with self.assertRaises(rdna2spirv.Unsupported): | ||
| 580 | translate_ps("ps_bad_mode", ps_program([insn])) | ||
| 581 | |||
| 582 | |||
| 583 | class NegativeControlTests(unittest.TestCase): | ||
| 584 | """Negative controls: sabotaging arithmetic or using unknown mnemonics must be detected.""" | ||
| 585 | |||
| 586 | def test_sabotaging_arithmetic_around_noop_waitcnt_changes_output(self): | ||
| 587 | good_spv = translate_ps("ps_neg_good", ps_program(["s_waitcnt_vmcnt null, 0x0", "s_clause 0x1"])) | ||
| 588 | good_out = si.run_fragment(good_spv, inputs={"%sg_lane": 0}) | ||
| 589 | self.assertEqual(tuple(good_out["%out_mrt0"]), expected_ps_mrt0(scc_one=True, vcc_one=True)) | ||
| 590 | |||
| 591 | # Assembly-level sabotage around the waitcnt/clause instructions: | ||
| 592 | sabotaged_cases = [ | ||
| 593 | ("SCC flipped 1->0", ps_program(["s_waitcnt_vmcnt null, 0x0", "s_clause 0x1"], scc_one=False)), | ||
| 594 | ("VCC flipped 1->0", ps_program(["s_waitcnt_vmcnt null, 0x0", "s_clause 0x1"], vcc_one=False)), | ||
| 595 | ("v_add_nc_u32 addend changed", ps_program(["s_waitcnt_vmcnt null, 0x0", "s_clause 0x1"], add_k=0x20)), | ||
| 596 | ("EXEC bit 0 cleared", ps_program(["s_waitcnt_vmcnt null, 0x0", "s_clause 0x1"], exec_lo=0xAAAA5554)), | ||
| 597 | ] | ||
| 598 | for label, bad_lines in sabotaged_cases: | ||
| 599 | with self.subTest(sabotage=label): | ||
| 600 | bad_spv = translate_ps("ps_neg_bad", bad_lines) | ||
| 601 | bad_out = si.run_fragment(bad_spv, inputs={"%sg_lane": 0}) | ||
| 602 | self.assertNotEqual(bad_out, good_out) | ||
| 603 | |||
| 604 | # SPIR-V-level sabotage on the translated output around the no-op/waitcnt block: | ||
| 605 | for old, new, label in ( | ||
| 606 | ("OpIAdd %uint", "OpISub %uint", "v_add_nc_u32/s_add_u32 turned into OpISub"), | ||
| 607 | ("OpIEqual %bool", "OpINotEqual %bool", "v_cmp_eq_u32 inverted"), | ||
| 608 | ): | ||
| 609 | with self.subTest(spirv_sabotage=label): | ||
| 610 | self.assertIn(old, good_spv) | ||
| 611 | mutated = good_spv.replace(old, new) | ||
| 612 | self.assertNotEqual(si.run_fragment(mutated, inputs={"%sg_lane": 0}), good_out) | ||
| 613 | |||
| 614 | # CS multi-lane negative control: | ||
| 615 | cs_good = translate_cs("cs_neg_good", cs_program(["s_sleep 0x1", "s_waitcnt_depctr 0xffe3"], wave64=False), | ||
| 616 | threads=32) | ||
| 617 | cs_good_words = run_cs(cs_good, 32) | ||
| 618 | cs_bad = translate_cs("cs_neg_bad", cs_program(["s_sleep 0x1", "s_waitcnt_depctr 0xffe3"], | ||
| 619 | wave64=False, scc_one=False), threads=32) | ||
| 620 | self.assertNotEqual(run_cs(cs_bad, 32), cs_good_words) | ||
| 621 | |||
| 622 | def test_unknown_waitcnt_and_noop_mnemonics_fail_with_unsupported(self): | ||
| 623 | for bogus in ("s_bogus_waitcnt 0x0", "s_bogus_waitcnt", "s_bogus_noop 0"): | ||
| 624 | with self.subTest(stage="ps", insn=bogus): | ||
| 625 | with self.assertRaises(rdna2spirv.Unsupported) as ctx: | ||
| 626 | translate_ps("ps_bogus", ps_program([bogus])) | ||
| 627 | self.assertIn(bogus.split()[0], str(ctx.exception)) | ||
| 628 | |||
| 629 | with self.subTest(stage="cs", insn=bogus): | ||
| 630 | with self.assertRaises(rdna2spirv.Unsupported) as ctx: | ||
| 631 | translate_cs("cs_bogus", cs_program([bogus], wave64=False), threads=32) | ||
| 632 | self.assertIn(bogus.split()[0], str(ctx.exception)) | ||
| 633 | |||
| 634 | |||
| 635 | if __name__ == "__main__": | ||
| 636 | unittest.main() | ||
diff --git a/tests/semantic/test_tbuffer_store.py b/tests/semantic/test_tbuffer_store.py new file mode 100644 index 000000000..890c68d5d --- /dev/null +++ b/tests/semantic/test_tbuffer_store.py | |||
| @@ -0,0 +1,86 @@ | |||
| 1 | """tbuffer_store_format_* (MTBUF stores with the instruction's own format) through the translator and the interpreter. | ||
| 2 | |||
| 3 | cs_tbuffer_store.asm stores into 13 sentinel-filled regions through V#s whose FORMAT differs from the instruction's, | ||
| 4 | then reads every region back into out[0..51]. check.py's TBUFFER_STORE_WORDS holds the words a Radeon 680M (gfx1035) | ||
| 5 | gives natively; the rules are in the .asm header. Here the translated fixture runs on the CPU and must give the same | ||
| 6 | words, so the GPU test, the hardware and the translation are kept in step. | ||
| 7 | """ | ||
| 8 | import os | ||
| 9 | import struct | ||
| 10 | import sys | ||
| 11 | import unittest | ||
| 12 | |||
| 13 | HERE = os.path.dirname(os.path.abspath(__file__)) | ||
| 14 | ROOT = os.path.dirname(os.path.dirname(HERE)) | ||
| 15 | sys.path.insert(0, HERE) | ||
| 16 | sys.path.insert(0, os.path.join(ROOT, "runtime", "test", "shaders")) | ||
| 17 | sys.path.insert(0, os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools")) | ||
| 18 | |||
| 19 | import check # noqa: E402 (runtime/test/shaders/check.py; importing it runs nothing) | ||
| 20 | import rdna2spirv # noqa: E402 | ||
| 21 | import support # noqa: E402 | ||
| 22 | |||
| 23 | |||
| 24 | def fssm(rsrc2, group): | ||
| 25 | """The compute-shader header words the translator reads: COMPUTE_PGM_RSRC2 and the thread-group size.""" | ||
| 26 | header = bytearray(0x148) | ||
| 27 | struct.pack_into("<4I", header, 0x138, rsrc2, *group) | ||
| 28 | return bytes(header) | ||
| 29 | |||
| 30 | |||
| 31 | # 4 user SGPRs (the output V#), workgroup id in s4, 64x1x1 threads: the header build.py gives the GPU tests. | ||
| 32 | CS_FSSM = fssm(0x8088, (64, 1, 1)) | ||
| 33 | # The output V# vk_compute_test passes in s[0:3]: base 0, num_records 0xffffffff, 32_FLOAT, OOB_SELECT 3. | ||
| 34 | OUT_VSHARP = [0, 0, 0xFFFFFFFF, 0x31016FAC] | ||
| 35 | |||
| 36 | |||
| 37 | def run(spv): | ||
| 38 | memory = {} | ||
| 39 | outputs = support.run_fragment(spv, inputs={"%wg_id": (0, 0, 0), "%local_id": (0, 0, 0)}, | ||
| 40 | push_constants=OUT_VSHARP + [0] * 28, memory=memory) | ||
| 41 | return outputs, memory | ||
| 42 | |||
| 43 | |||
| 44 | class TbufferStoreFixture(unittest.TestCase): | ||
| 45 | def test_words_match_the_native_measurement(self): | ||
| 46 | outputs, memory = run(support.translate_fixture("cs_tbuffer_store", fssm=CS_FSSM)) | ||
| 47 | self.assertEqual(outputs, {}) | ||
| 48 | want = check.TBUFFER_STORE_WORDS | ||
| 49 | got = [memory.get(4 * i, 0) for i in range(len(want))] | ||
| 50 | for i, (g, w) in enumerate(zip(got, want)): | ||
| 51 | with self.subTest(out=i, region=hex(0x200 + 16 * (i // 4))): | ||
| 52 | self.assertEqual(f"{g:#010x}", f"{w:#010x}") | ||
| 53 | # The regions themselves hold the same words, and nothing lands between out[] and the regions. | ||
| 54 | self.assertEqual([memory.get(0x200 + 4 * i, 0) for i in range(len(want))], want) | ||
| 55 | self.assertEqual(sorted(a for a in memory if len(want) * 4 <= a < 0x200), []) | ||
| 56 | |||
| 57 | |||
| 58 | class TbufferStoreTranslation(unittest.TestCase): | ||
| 59 | def store(self, fmt_mod): | ||
| 60 | return support.translate_lines("cs_tbuf_one", [ | ||
| 61 | "v_mov_b32_e32 v20, 1.0", "v_mov_b32_e32 v5, 0x200", | ||
| 62 | f"tbuffer_store_format_x v20, v5, s[0:3], 0{fmt_mod} offen", "s_endpgm"], fssm=CS_FSSM) | ||
| 63 | |||
| 64 | def test_format_outside_formats_is_unsupported(self): | ||
| 65 | # BUF_FMT_8_USCALED is a GFX10 format the FORMATS table has no encoder for: reported, never guessed. | ||
| 66 | # (BUF_FMT_8_UINT was the example until #1871 added the measured 8/16-bit UINT/SINT formats.) | ||
| 67 | with self.assertRaises(rdna2spirv.Unsupported): | ||
| 68 | self.store(" format:[BUF_FMT_8_USCALED]") | ||
| 69 | |||
| 70 | def test_default_format_is_one_unorm_byte(self): | ||
| 71 | # No modifier is GFX10's default, BUF_FMT_8_UNORM: 1.0 is 0xff in the low byte, the other three kept. | ||
| 72 | spv = self.store("") | ||
| 73 | memory = {0x200: 0x11223344} | ||
| 74 | support.run_fragment(spv, inputs={"%wg_id": (0, 0, 0), "%local_id": (0, 0, 0)}, | ||
| 75 | push_constants=OUT_VSHARP + [0] * 28, memory=memory) | ||
| 76 | self.assertEqual(f"{memory[0x200]:#010x}", "0x112233ff") | ||
| 77 | |||
| 78 | def test_data_vgprs_are_read(self): | ||
| 79 | # read_before_write_vgprs: a store's vdata is a source, as for buffer_store. | ||
| 80 | import shader_ir | ||
| 81 | ins = shader_ir.parse_line("\ttbuffer_store_format_xy v[7:8], v5, s[4:7], 0 format:[BUF_FMT_32_32_FLOAT] offen") | ||
| 82 | self.assertEqual(sorted(rdna2spirv.read_before_write_vgprs([ins])), [5, 7, 8]) | ||
| 83 | |||
| 84 | |||
| 85 | if __name__ == "__main__": | ||
| 86 | unittest.main() | ||
diff --git a/tests/semantic/test_valu_fma_mix.py b/tests/semantic/test_valu_fma_mix.py index 1d0730fe3..6c2a39cc6 100644 --- a/tests/semantic/test_valu_fma_mix.py +++ b/tests/semantic/test_valu_fma_mix.py | |||
| @@ -212,6 +212,25 @@ class FmaMixF16Tests(unittest.TestCase): | |||
| 212 | got = run("v_fma_mixhi_f16 v0, v0, v1, v2 op_sel:[0,0,0] op_sel_hi:[1,0,1]", f2u(2.0), pack_h(0.5, 9.0), 0, old=old) | 212 | got = run("v_fma_mixhi_f16 v0, v0, v1, v2 op_sel:[0,0,0] op_sel_hi:[1,0,1]", f2u(2.0), pack_h(0.5, 9.0), 0, old=old) |
| 213 | self.assertEqual(got, pack_h(1.5, 3.5)) | 213 | self.assertEqual(got, pack_h(1.5, 3.5)) |
| 214 | 214 | ||
| 215 | def test_single_rounding_discriminating_cases(self): | ||
| 216 | # Discriminating test cases A through G from tools/fma_mix_probe.py where | ||
| 217 | # hardware single rounding gives 1 ulp difference from double rounding. | ||
| 218 | # Case A: 1 * 2^-40 + (1 + 2^-11) -> single: 0x3c01, double: 0x3c00 | ||
| 219 | got_a = run("v_fma_mixlo_f16 v0, v1, v2, v3", 0x3F800000, 0x2B800000, 0x3F801000, old=OLD) | ||
| 220 | self.assertEqual(got_a, (OLD & 0xFFFF0000) | 0x3C01) | ||
| 221 | |||
| 222 | # Case B: 1 * -2^-40 + (1 + 3 * 2^-11) -> single: 0x3c01, double: 0x3c02 | ||
| 223 | got_b = run("v_fma_mixhi_f16 v0, v1, v2, v3", 0x3F800000, 0xAB800000, 0x3F803000, old=OLD) | ||
| 224 | self.assertEqual(got_b, (0x3C01 << 16) | (OLD & 0xFFFF)) | ||
| 225 | |||
| 226 | # Case C: -1 * 2^-40 - (1 + 2^-11) -> single: 0xbc01, double: 0xbc00 | ||
| 227 | got_c = run("v_fma_mixlo_f16 v0, v1, v2, v3", 0xBF800000, 0x2B800000, 0xBF801000, old=OLD) | ||
| 228 | self.assertEqual(got_c, (OLD & 0xFFFF0000) | 0xBC01) | ||
| 229 | |||
| 230 | # Case G (f16 operands): (1 + 2^-7) * (2^-11 - 2^-18) + (1 + 2^-10) -> single: 0x3c01, double: 0x3c02 | ||
| 231 | got_g = run("v_fma_mixlo_f16 v0, v1, v2, v3 op_sel_hi:[1,1,1]", 0x3C08, 0x0FF0, 0x3C01, old=OLD) | ||
| 232 | self.assertEqual(got_g, (OLD & 0xFFFF0000) | 0x3C01) | ||
| 233 | |||
| 215 | 234 | ||
| 216 | class NegativeControls(unittest.TestCase): | 235 | class NegativeControls(unittest.TestCase): |
| 217 | """Sabotaging the translated SPIR-V must change the observed output.""" | 236 | """Sabotaging the translated SPIR-V must change the observed output.""" |
| @@ -226,5 +245,52 @@ class NegativeControls(unittest.TestCase): | |||
| 226 | self.assertNotEqual(si.run_fragment(bad)["%out_mrt0"][0], good) | 245 | self.assertNotEqual(si.run_fragment(bad)["%out_mrt0"][0], good) |
| 227 | 246 | ||
| 228 | 247 | ||
| 248 | class FmaMixF32DenormalOperandTests(unittest.TestCase): | ||
| 249 | """SHADER-298: an f32 operand of v_fma_mix* that is denormal reads as a zero of its sign (the game's MODE has | ||
| 250 | denorm_mode_32 = 0), measured on gfx1036 by @Sanonymous01 for 0x00000001, 0x807fffff and the integer inline | ||
| 251 | constants 1 and 64. The result is not flushed here (not measured), so 0 * y + denormal keeps the denormal only | ||
| 252 | when the denormal is not an operand, which cannot happen; the checks below use operands only.""" | ||
| 253 | |||
| 254 | BIG = f2u(1.0e30) | ||
| 255 | ZERO = 0x00000000 | ||
| 256 | NEG_ZERO = 0x80000000 | ||
| 257 | |||
| 258 | def test_denormal_multiplicand_reads_as_zero(self): | ||
| 259 | # 1.4e-45 * 1e30 = 1.4e-15 if the denormal is kept; 0 if it is flushed. | ||
| 260 | for d in (0x00000001, 0x007FFFFF): | ||
| 261 | with self.subTest(denormal=hex(d), slot="src0"): | ||
| 262 | self.assertEqual(run("v_fma_mix_f32 v0, v1, v2, v3", d, self.BIG, self.ZERO), 0x00000000) | ||
| 263 | with self.subTest(denormal=hex(d), slot="src1"): | ||
| 264 | self.assertEqual(run("v_fma_mix_f32 v0, v1, v2, v3", self.BIG, d, self.ZERO), 0x00000000) | ||
| 265 | |||
| 266 | def test_negative_denormal_reads_as_negative_zero(self): | ||
| 267 | # (-0) * 1e30 + (-0) = -0; a kept denormal would give -1.1e-8-ish tiny non-zero. | ||
| 268 | for d in (0x80000001, 0x807FFFFF): | ||
| 269 | with self.subTest(denormal=hex(d)): | ||
| 270 | self.assertEqual(run("v_fma_mix_f32 v0, v1, v2, v3", d, self.BIG, self.NEG_ZERO), 0x80000000) | ||
| 271 | |||
| 272 | def test_denormal_addend_reads_as_zero(self): | ||
| 273 | # 0 * y + denormal: the denormal addend is flushed, so the result is +0 (kept it would be the denormal). | ||
| 274 | self.assertEqual(run("v_fma_mix_f32 v0, v1, v2, v3", self.ZERO, self.BIG, 0x00000001), 0x00000000) | ||
| 275 | |||
| 276 | def test_integer_inline_constants_are_denormal_f32_operands(self): | ||
| 277 | # `1` and `64` in an f32 operand slot are the words 0x00000001 and 0x00000040: denormal, flushed to +0. | ||
| 278 | for const in ("1", "64"): | ||
| 279 | with self.subTest(const=const): | ||
| 280 | self.assertEqual(run(f"v_fma_mix_f32 v0, {const}, v2, v3", self.ZERO, self.BIG, self.ZERO), 0x00000000) | ||
| 281 | |||
| 282 | def test_normal_operands_are_untouched(self): | ||
| 283 | a, b, c = f2u(2.5), f2u(-1.25), f2u(0.75) | ||
| 284 | self.assertEqual(run("v_fma_mix_f32 v0, v1, v2, v3", a, b, c), f2u(ref_fma(a, b, c, (0, 0, 0), (0, 0, 0)))) | ||
| 285 | smallest_normal = 0x00800000 # 2**-126 is the first value that is not flushed | ||
| 286 | got = run("v_fma_mix_f32 v0, v1, v2, v3", smallest_normal, f2u(1.0), self.ZERO) | ||
| 287 | self.assertEqual(got, smallest_normal) | ||
| 288 | |||
| 289 | def test_the_flush_reaches_the_f16_result(self): | ||
| 290 | # 1.4e-45 * 3e37 = 4.2e-8 rounds to the f16 subnormal 0x0001 if the denormal is kept, and is 0 flushed. | ||
| 291 | got = run("v_fma_mixlo_f16 v0, v1, v2, v3", 0x00000001, f2u(3.0e37), self.ZERO, old=0xAAAA0000) | ||
| 292 | self.assertEqual(got, 0xAAAA0000) | ||
| 293 | |||
| 294 | |||
| 229 | if __name__ == "__main__": | 295 | if __name__ == "__main__": |
| 230 | unittest.main() | 296 | unittest.main() |
diff --git a/tests/semantic/test_valu_fract_f16.py b/tests/semantic/test_valu_fract_f16.py new file mode 100644 index 000000000..aabad97c6 --- /dev/null +++ b/tests/semantic/test_valu_fract_f16.py | |||
| @@ -0,0 +1,703 @@ | |||
| 1 | """End-to-end semantic value tests for RDNA2 v_fract_f16 (S0.f16 - floor(S0.f16)). | ||
| 2 | |||
| 3 | Covers v_fract_f16 executed end-to-end through tools/rdna2spirv.py and | ||
| 4 | tests/semantic/spirv_mini_interp.py against an independent Fraction-based | ||
| 5 | IEEE-754 binary16 `x - floor(x)` oracle: | ||
| 6 | - Positive & negative finite non-integers, including tiny negatives and | ||
| 7 | negative subnormals (-0.0001, -1e-5, -2**-12, -2**-24) whose exact | ||
| 8 | x - floor(x) rounds to 1.0 in binary16 and maps to 0x3bff (the largest | ||
| 9 | binary16 strictly below 1.0), plus the adjacent 0x3bfe / 0x3bff edge. | ||
| 10 | - Exact integers (0.0, 1.0, -1.0, 65504.0, -65504.0 -> +0.0) and -0.0 -> +0.0. | ||
| 11 | - +-inf and qNaN/sNaN behavior (GLSL.std.450 Fract returns NaN; fract_below_one | ||
| 12 | uses OpFOrdEqual + OpSelect so NaN survives into f16_bits -> qNaN). | ||
| 13 | - _e32, _e64, and bare mnemonics, keeping the untouched 16-bit half of dst. | ||
| 14 | - Runtime memory inputs via s_buffer_load_dwordx4 alongside immediate inputs. | ||
| 15 | - All 4 op_sel:[src,dst] combinations ([0,0], [1,0], [0,1], [1,1]). | ||
| 16 | - VOP3 source modifiers (-v1, |v1|, -|v1|) and output modifiers | ||
| 17 | (clamp, mul:2, mul:4, div:2, mul:2 clamp, mul:4 clamp). | ||
| 18 | - Inline f16 constants (0.5, -0.5, 1.0, -1.0), SGPR sources, destination | ||
| 19 | aliasing (v0, v0), single-lane and multi-lane EXEC masking, and SPIR-V | ||
| 20 | sabotage negative controls (Fract -> Trunc / Floor). | ||
| 21 | |||
| 22 | Note: Under VOP3 `clamp`, GLSL.std.450 FClamp on NaN is undefined in SPIR-V | ||
| 23 | and spirv_mini_interp.py raises UnsupportedConstruct (documented in | ||
| 24 | docs/design.md), so `clamp` value tests use finite inputs. Standard library | ||
| 25 | only; hand-written RDNA2 disassembly listings only; zero game data. | ||
| 26 | """ | ||
| 27 | from fractions import Fraction | ||
| 28 | import gc | ||
| 29 | import itertools | ||
| 30 | import math | ||
| 31 | import os | ||
| 32 | import re | ||
| 33 | import struct | ||
| 34 | import sys | ||
| 35 | import tempfile | ||
| 36 | import unittest | ||
| 37 | import warnings | ||
| 38 | |||
| 39 | HERE = os.path.dirname(os.path.abspath(__file__)) | ||
| 40 | ROOT = os.path.dirname(os.path.dirname(HERE)) | ||
| 41 | TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") | ||
| 42 | |||
| 43 | sys.dont_write_bytecode = True | ||
| 44 | if TOOLS_DIR not in sys.path: | ||
| 45 | sys.path.insert(0, TOOLS_DIR) | ||
| 46 | if HERE not in sys.path: | ||
| 47 | sys.path.insert(0, HERE) | ||
| 48 | |||
| 49 | import rdna2spirv # noqa: E402 | ||
| 50 | import spirv_mini_interp as si # noqa: E402 | ||
| 51 | |||
| 52 | STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("<I", 0) + bytes(4) | ||
| 53 | OLD = 0xBEEF1234 | ||
| 54 | PUSH_ADDR = [0x1000, 0, 32, 0] + [0] * 28 | ||
| 55 | VSHARP_CS = [0, 0, 0xFFFFFFFF, 0x31016FAC] | ||
| 56 | HEAP_FILL = 0xEEEEEEEE | ||
| 57 | |||
| 58 | # Representative binary16 encodings (cross-checked in OracleTests). | ||
| 59 | H_POS_ZERO = 0x0000 # +0.0 | ||
| 60 | H_NEG_ZERO = 0x8000 # -0.0 | ||
| 61 | H_SUB_MIN = 0x0001 # +2^-24 (~5.96e-8) | ||
| 62 | H_NEG_SUB_MIN = 0x8001 # -2^-24 | ||
| 63 | H_SUB_1E5 = 0x00A8 # +1e-5 rounded to f16 subnormal (~1.001e-5) | ||
| 64 | H_NEG_SUB_1E5 = 0x80A8 # -1e-5 rounded to f16 subnormal (~-1.001e-5) | ||
| 65 | H_SUB_MAX = 0x03FF # +1023 * 2^-24 (largest +subnormal) | ||
| 66 | H_NEG_SUB_MAX = 0x83FF # -1023 * 2^-24 (largest-magnitude -subnormal) | ||
| 67 | H_NORM_MIN = 0x0400 # +2^-14 (smallest +normal) | ||
| 68 | H_NEG_NORM_MIN = 0x8400 # -2^-14 | ||
| 69 | H_1E4 = 0x068E # +0.0001 rounded to f16 (~1.000166e-4) | ||
| 70 | H_NEG_1E4 = 0x868E # -0.0001 rounded to f16 (~-1.000166e-4) | ||
| 71 | H_2PM13 = 0x0800 # +2^-13 | ||
| 72 | H_NEG_2PM13 = 0x8800 # -2^-13 | ||
| 73 | H_NEG_2PM12_M = 0x8BFF # -(2^-12 - 2^-23): just above -2^-12 | ||
| 74 | H_NEG_2PM12 = 0x8C00 # -2^-12: exact tie between 0x3bff and 0x3c00 | ||
| 75 | H_NEG_2PM12_P = 0x8C01 # -(2^-12 + 2^-22): strictly closer to 0x3bff | ||
| 76 | H_NEG_3P2M13 = 0x8E00 # -3 * 2^-13: strictly closer to 0x3bff | ||
| 77 | H_NEG_2PM11 = 0x9000 # -2^-11: 1 - 2^-11 = 0x3bff exact | ||
| 78 | H_NEG_3P2M12 = 0x9200 # -3 * 2^-12: exact tie between 0x3bfe (even) and 0x3bff (odd) -> 0x3bfe | ||
| 79 | H_NEG_2PM10 = 0x9400 # -2^-10: 1 - 2^-10 = 0x3bfe exact | ||
| 80 | H_0P125 = 0x3000 # 0.125 | ||
| 81 | H_0P25 = 0x3400 # 0.25 | ||
| 82 | H_NEG_0P25 = 0xB400 # -0.25 | ||
| 83 | H_0P375 = 0x3600 # 0.375 | ||
| 84 | H_0P5 = 0x3800 # 0.5 | ||
| 85 | H_NEG_0P5 = 0xB800 # -0.5 | ||
| 86 | H_0P75 = 0x3A00 # 0.75 | ||
| 87 | H_NEG_0P75 = 0xBA00 # -0.75 | ||
| 88 | H_NEAR_ONE = 0x3BFF # 1 - 2^-11 (largest f16 < 1.0) | ||
| 89 | H_1P0 = 0x3C00 # 1.0 | ||
| 90 | H_NEG_1P0 = 0xBC00 # -1.0 | ||
| 91 | H_1P25 = 0x3D00 # 1.25 | ||
| 92 | H_NEG_1P25 = 0xBD00 # -1.25 | ||
| 93 | H_1P5 = 0x3E00 # 1.5 | ||
| 94 | H_NEG_1P5 = 0xBE00 # -1.5 | ||
| 95 | H_1P75 = 0x3F00 # 1.75 | ||
| 96 | H_NEG_1P75 = 0xBF00 # -1.75 | ||
| 97 | H_2P0 = 0x4000 # 2.0 | ||
| 98 | H_NEG_2P0 = 0xC000 # -2.0 | ||
| 99 | H_2P5 = 0x4100 # 2.5 | ||
| 100 | H_NEG_2P5 = 0xC100 # -2.5 | ||
| 101 | H_3P0 = 0x4200 # 3.0 | ||
| 102 | H_NEG_3P0 = 0xC200 # -3.0 | ||
| 103 | H_3P75 = 0x4380 # 3.75 | ||
| 104 | H_NEG_3P75 = 0xC380 # -3.75 | ||
| 105 | H_1023P5 = 0x63FF # 1023.5 | ||
| 106 | H_NEG_1023P5 = 0xE3FF # -1023.5 | ||
| 107 | H_1024 = 0x6400 # 1024.0 | ||
| 108 | H_NEG_1024 = 0xE400 # -1024.0 | ||
| 109 | H_MAX = 0x7BFF # 65504.0 | ||
| 110 | H_NEG_MAX = 0xFBFF # -65504.0 | ||
| 111 | H_POS_INF = 0x7C00 # +inf | ||
| 112 | H_NEG_INF = 0xFC00 # -inf | ||
| 113 | H_QNAN = 0x7E01 # +qNaN | ||
| 114 | H_NEG_QNAN = 0xFE01 # -qNaN | ||
| 115 | H_SNAN = 0x7C01 # +sNaN | ||
| 116 | H_NEG_SNAN = 0xFC01 # -sNaN | ||
| 117 | |||
| 118 | |||
| 119 | # ----------------------------------------------------------------------------- | ||
| 120 | # Independent Fraction-Based IEEE-754 Binary16 Oracle | ||
| 121 | # ----------------------------------------------------------------------------- | ||
| 122 | |||
| 123 | def h16_is_finite(h: int) -> bool: | ||
| 124 | return ((h >> 10) & 0x1F) != 0x1F | ||
| 125 | |||
| 126 | |||
| 127 | def h16_is_nan(h: int) -> bool: | ||
| 128 | return (h & 0x7FFF) > 0x7C00 | ||
| 129 | |||
| 130 | |||
| 131 | def h16_is_inf(h: int) -> bool: | ||
| 132 | return (h & 0x7FFF) == 0x7C00 | ||
| 133 | |||
| 134 | |||
| 135 | def h16_to_fraction(h: int) -> Fraction: | ||
| 136 | """Decode finite IEEE-754 binary16 bit pattern ``h`` into an exact Fraction.""" | ||
| 137 | h &= 0xFFFF | ||
| 138 | exp = (h >> 10) & 0x1F | ||
| 139 | if exp == 0x1F: | ||
| 140 | raise ValueError(f"non-finite binary16 {h:#06x}") | ||
| 141 | sign = -1 if (h >> 15) else 1 | ||
| 142 | mant = h & 0x3FF | ||
| 143 | if exp == 0: | ||
| 144 | return Fraction(0) if mant == 0 else Fraction(sign * mant, 1 << 24) | ||
| 145 | return Fraction(sign * ((1 << 10) | mant)) * (Fraction(2) ** (exp - 25)) | ||
| 146 | |||
| 147 | |||
| 148 | def fraction_to_h16(q: Fraction) -> int: | ||
| 149 | """Round an exact Fraction to IEEE-754 binary16 (nearest, ties to even).""" | ||
| 150 | if q == 0: | ||
| 151 | return H_POS_ZERO | ||
| 152 | sgn = 0x8000 if q < 0 else 0 | ||
| 153 | a = abs(q) | ||
| 154 | e = max(a.numerator.bit_length() - a.denominator.bit_length(), -14) | ||
| 155 | if e > -14 and Fraction(2) ** e > a: | ||
| 156 | e -= 1 | ||
| 157 | m = a / (Fraction(2) ** (e - 10)) | ||
| 158 | n = m.numerator // m.denominator | ||
| 159 | rem = m - n | ||
| 160 | if rem > Fraction(1, 2) or (rem == Fraction(1, 2) and (n & 1)): | ||
| 161 | n += 1 | ||
| 162 | if e == -14 and n < 1024: | ||
| 163 | return sgn | n | ||
| 164 | if n >= 2048: | ||
| 165 | n >>= 1 | ||
| 166 | e += 1 | ||
| 167 | if e > 15: | ||
| 168 | return sgn | H_POS_INF | ||
| 169 | return sgn | ((e + 15) << 10) | (n - 1024) | ||
| 170 | |||
| 171 | |||
| 172 | def exact_fract_fraction(h: int) -> Fraction | None: | ||
| 173 | """Exact ``x - floor(x)`` as a Fraction in [0, 1), or None for +-inf / NaN.""" | ||
| 174 | if not h16_is_finite(h): | ||
| 175 | return None | ||
| 176 | q = h16_to_fraction(h) | ||
| 177 | return q - math.floor(q) | ||
| 178 | |||
| 179 | |||
| 180 | def oracle_fract_f16( | ||
| 181 | h: int, | ||
| 182 | *, | ||
| 183 | abs_: bool = False, | ||
| 184 | neg: bool = False, | ||
| 185 | mul: int = 1, | ||
| 186 | div: int = 1, | ||
| 187 | clamp: bool = False, | ||
| 188 | ) -> int | None: | ||
| 189 | """Independent binary16 reference for v_fract_f16, returning 16-bit int or None for NaN. | ||
| 190 | |||
| 191 | Models RDNA2 source modifiers (abs before neg), exact ``x - floor(x)``, | ||
| 192 | the hardware/translator 0x3c00 -> 0x3bff clamp when no output multiplier is | ||
| 193 | present, and VOP3 output scaling (mul/div) + [0, 1] clamp before narrowing. | ||
| 194 | """ | ||
| 195 | h &= 0xFFFF | ||
| 196 | if abs_: | ||
| 197 | h &= 0x7FFF | ||
| 198 | if neg: | ||
| 199 | h ^= 0x8000 | ||
| 200 | r = exact_fract_fraction(h) | ||
| 201 | if r is None: | ||
| 202 | return None | ||
| 203 | if mul == 1 and div == 1: | ||
| 204 | res = fraction_to_h16(r) | ||
| 205 | return H_NEAR_ONE if res == H_1P0 else res | ||
| 206 | scaled = r * Fraction(mul, div) | ||
| 207 | if clamp: | ||
| 208 | scaled = min(max(scaled, Fraction(0)), Fraction(1)) | ||
| 209 | return fraction_to_h16(scaled) | ||
| 210 | |||
| 211 | |||
| 212 | def merge_half(old: int, half: int, dst_hi: int) -> int: | ||
| 213 | h = half & 0xFFFF | ||
| 214 | return ((h << 16) | (old & 0xFFFF)) if dst_hi else ((old & 0xFFFF0000) | h) | ||
| 215 | |||
| 216 | |||
| 217 | # ----------------------------------------------------------------------------- | ||
| 218 | # Translation & Execution Helpers | ||
| 219 | # ----------------------------------------------------------------------------- | ||
| 220 | |||
| 221 | _TMP_DIR = None | ||
| 222 | _PS_PATH = None | ||
| 223 | _CS_PATH = None | ||
| 224 | _CS_FSSM = None | ||
| 225 | |||
| 226 | |||
| 227 | def _make_fssm(rsrc2: int, group: tuple[int, int, int]) -> bytes: | ||
| 228 | header = bytearray(0x148) | ||
| 229 | struct.pack_into("<4I", header, 0x138, rsrc2, *group) | ||
| 230 | return bytes(header) | ||
| 231 | |||
| 232 | |||
| 233 | def setUpModule(): | ||
| 234 | global _TMP_DIR, _PS_PATH, _CS_PATH, _CS_FSSM | ||
| 235 | _TMP_DIR = tempfile.TemporaryDirectory() | ||
| 236 | disasm_dir = os.path.join(_TMP_DIR.name, "disasm") | ||
| 237 | fssm_dir = os.path.join(_TMP_DIR.name, "fssm") | ||
| 238 | os.mkdir(disasm_dir) | ||
| 239 | os.mkdir(fssm_dir) | ||
| 240 | _PS_PATH = os.path.join(disasm_dir, "ps_fract_f16.s") | ||
| 241 | _CS_PATH = os.path.join(disasm_dir, "cs_fract_f16.s") | ||
| 242 | _CS_FSSM = os.path.join(fssm_dir, "cs_fract_f16.fssm") | ||
| 243 | with open(os.path.join(_TMP_DIR.name, "ps_fract_f16.dxbc"), "wb") as f: | ||
| 244 | f.write(STUB_DXBC) | ||
| 245 | |||
| 246 | |||
| 247 | def tearDownModule(): | ||
| 248 | global _TMP_DIR, _PS_PATH, _CS_PATH, _CS_FSSM | ||
| 249 | if _TMP_DIR is not None: | ||
| 250 | gc.collect() | ||
| 251 | _TMP_DIR.cleanup() | ||
| 252 | _TMP_DIR = None | ||
| 253 | _PS_PATH = None | ||
| 254 | _CS_PATH = None | ||
| 255 | _CS_FSSM = None | ||
| 256 | |||
| 257 | |||
| 258 | def translate_ps(lines: list[str]) -> str: | ||
| 259 | if _TMP_DIR is None: | ||
| 260 | setUpModule() | ||
| 261 | asm = ( | ||
| 262 | "; test_valu_fract_f16\n" | ||
| 263 | + "".join(f"\t{ln}\n" for ln in lines) | ||
| 264 | + "\texp mrt0 v0, v0, v0, v0 done vm\n\ts_endpgm\n" | ||
| 265 | ) | ||
| 266 | with open(_PS_PATH, "w", encoding="utf-8", newline="\n") as f: | ||
| 267 | f.write(asm) | ||
| 268 | with warnings.catch_warnings(): | ||
| 269 | warnings.simplefilter("ignore", ResourceWarning) | ||
| 270 | spv = rdna2spirv.translate(_PS_PATH) | ||
| 271 | gc.collect() | ||
| 272 | return spv | ||
| 273 | |||
| 274 | |||
| 275 | def run_ps(lines: list[str], *, push_constants=None, memory=None) -> int: | ||
| 276 | out = si.run_fragment(translate_ps(lines), push_constants=push_constants, memory=memory) | ||
| 277 | return out["%out_mrt0"][0] | ||
| 278 | |||
| 279 | |||
| 280 | def run_op(line: str, v1: int = 0, *, old: int = OLD, s4: int = 0) -> int: | ||
| 281 | return run_ps([ | ||
| 282 | f"s_mov_b32 s4, {s4:#x}", | ||
| 283 | f"v_mov_b32 v1, {v1:#x}", | ||
| 284 | f"v_mov_b32 v0, {old:#x}", | ||
| 285 | line, | ||
| 286 | ]) | ||
| 287 | |||
| 288 | |||
| 289 | def run_cs(lines: list[str], group_size: int, memory: dict[int, int]) -> None: | ||
| 290 | if _TMP_DIR is None: | ||
| 291 | setUpModule() | ||
| 292 | # rsrc2 = 0x0088: USER_SGPR = 4 (s[0:3] V#), TGID_X_EN = 1 (s4), TIDIG_COMP_CNT = 0 (v0 = local_id.x). | ||
| 293 | with open(_CS_FSSM, "wb") as f: | ||
| 294 | f.write(_make_fssm(0x0088, (group_size, 1, 1))) | ||
| 295 | asm = "; test_cs_valu_fract_f16\n" + "".join(f"\t{ln}\n" for ln in lines) + "\ts_endpgm\n" | ||
| 296 | with open(_CS_PATH, "w", encoding="utf-8", newline="\n") as f: | ||
| 297 | f.write(asm) | ||
| 298 | with warnings.catch_warnings(): | ||
| 299 | warnings.simplefilter("ignore", ResourceWarning) | ||
| 300 | spv = rdna2spirv.translate(_CS_PATH) | ||
| 301 | gc.collect() | ||
| 302 | si.run_workgroup( | ||
| 303 | spv, | ||
| 304 | group_size, | ||
| 305 | 32, | ||
| 306 | inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0)}, | ||
| 307 | push_constants=VSHARP_CS + [0] * 28, | ||
| 308 | memory=memory, | ||
| 309 | ) | ||
| 310 | |||
| 311 | |||
| 312 | class _Heap(dict): | ||
| 313 | def get(self, key, default=None): | ||
| 314 | return super().get(key, HEAP_FILL) | ||
| 315 | |||
| 316 | |||
| 317 | # ----------------------------------------------------------------------------- | ||
| 318 | # Oracle Self-Tests | ||
| 319 | # ----------------------------------------------------------------------------- | ||
| 320 | |||
| 321 | class OracleTests(unittest.TestCase): | ||
| 322 | """Cross-checks the independent Fraction binary16 oracle against IEEE-754 encodings.""" | ||
| 323 | |||
| 324 | def test_exhaustive_binary16_decode_and_roundtrip(self): | ||
| 325 | for h in range(0x10000): | ||
| 326 | if not h16_is_finite(h): | ||
| 327 | self.assertIsNone(exact_fract_fraction(h)) | ||
| 328 | self.assertIsNone(oracle_fract_f16(h)) | ||
| 329 | continue | ||
| 330 | q = h16_to_fraction(h) | ||
| 331 | expected_float = struct.unpack("<e", struct.pack("<H", h))[0] | ||
| 332 | self.assertEqual(q, Fraction(expected_float)) | ||
| 333 | want = H_POS_ZERO if h == H_NEG_ZERO else h | ||
| 334 | self.assertEqual(fraction_to_h16(q), want) | ||
| 335 | |||
| 336 | def test_hand_worked_fract_f16_rows(self): | ||
| 337 | rows = [ | ||
| 338 | (H_POS_ZERO, H_POS_ZERO), | ||
| 339 | (H_NEG_ZERO, H_POS_ZERO), | ||
| 340 | (H_0P25, H_0P25), | ||
| 341 | (H_1P25, H_0P25), | ||
| 342 | (H_3P75, H_0P75), | ||
| 343 | (H_NEG_0P25, H_0P75), | ||
| 344 | (H_NEG_1P25, H_0P75), | ||
| 345 | (H_NEG_0P5, H_0P5), | ||
| 346 | (H_NEG_0P75, H_0P25), | ||
| 347 | (H_1P0, H_POS_ZERO), | ||
| 348 | (H_NEG_1P0, H_POS_ZERO), | ||
| 349 | (H_MAX, H_POS_ZERO), | ||
| 350 | (H_NEG_MAX, H_POS_ZERO), | ||
| 351 | (H_NEG_2PM10, 0x3BFE), | ||
| 352 | (H_NEG_3P2M12, 0x3BFE), | ||
| 353 | (H_NEG_2PM11, H_NEAR_ONE), | ||
| 354 | (H_NEG_3P2M13, H_NEAR_ONE), | ||
| 355 | (H_NEG_2PM12_P, H_NEAR_ONE), | ||
| 356 | (H_NEG_2PM12, H_NEAR_ONE), | ||
| 357 | (H_NEG_2PM12_M, H_NEAR_ONE), | ||
| 358 | (H_NEG_2PM13, H_NEAR_ONE), | ||
| 359 | (H_NEG_1E4, H_NEAR_ONE), | ||
| 360 | (H_NEG_SUB_1E5, H_NEAR_ONE), | ||
| 361 | (H_NEG_SUB_MAX, H_NEAR_ONE), | ||
| 362 | (H_NEG_SUB_MIN, H_NEAR_ONE), | ||
| 363 | (H_SUB_MIN, H_SUB_MIN), | ||
| 364 | (H_SUB_1E5, H_SUB_1E5), | ||
| 365 | (H_1E4, H_1E4), | ||
| 366 | ] | ||
| 367 | for h, want in rows: | ||
| 368 | with self.subTest(h=hex(h)): | ||
| 369 | self.assertEqual(oracle_fract_f16(h), want) | ||
| 370 | # Verify decimal conversions match our binary16 constants. | ||
| 371 | self.assertEqual(struct.unpack("<H", struct.pack("<e", -0.0001))[0], H_NEG_1E4) | ||
| 372 | self.assertEqual(struct.unpack("<H", struct.pack("<e", -1e-5))[0], H_NEG_SUB_1E5) | ||
| 373 | self.assertEqual(struct.unpack("<H", struct.pack("<e", 3.75))[0], H_3P75) | ||
| 374 | |||
| 375 | |||
| 376 | # ----------------------------------------------------------------------------- | ||
| 377 | # End-to-End Execution Tests | ||
| 378 | # ----------------------------------------------------------------------------- | ||
| 379 | |||
| 380 | class FractF16ExecutionTests(unittest.TestCase): | ||
| 381 | def test_finite_values_across_e32_e64_and_bare(self): | ||
| 382 | samples = [ | ||
| 383 | H_POS_ZERO, H_NEG_ZERO, | ||
| 384 | H_SUB_MIN, H_NEG_SUB_MIN, H_SUB_1E5, H_NEG_SUB_1E5, | ||
| 385 | H_SUB_MAX, H_NEG_SUB_MAX, H_NORM_MIN, H_NEG_NORM_MIN, | ||
| 386 | H_1E4, H_NEG_1E4, H_2PM13, H_NEG_2PM13, | ||
| 387 | H_NEG_2PM12_M, H_NEG_2PM12, H_NEG_2PM12_P, H_NEG_3P2M13, | ||
| 388 | H_NEG_2PM11, H_NEG_3P2M12, H_NEG_2PM10, | ||
| 389 | H_0P125, H_0P25, H_NEG_0P25, H_0P5, H_NEG_0P5, H_0P75, H_NEG_0P75, | ||
| 390 | H_NEAR_ONE, | ||
| 391 | H_1P0, H_NEG_1P0, H_1P25, H_NEG_1P25, H_1P5, H_NEG_1P5, H_1P75, H_NEG_1P75, | ||
| 392 | H_2P0, H_NEG_2P0, H_2P5, H_NEG_2P5, H_3P0, H_NEG_3P0, H_3P75, H_NEG_3P75, | ||
| 393 | H_1023P5, H_NEG_1023P5, H_1024, H_NEG_1024, H_MAX, H_NEG_MAX, | ||
| 394 | ] | ||
| 395 | for suffix in ("_e32", "_e64", ""): | ||
| 396 | for h in samples: | ||
| 397 | v1 = 0x55550000 | h | ||
| 398 | want = merge_half(OLD, oracle_fract_f16(h), 0) | ||
| 399 | with self.subTest(form="v_fract_f16" + suffix, h=hex(h)): | ||
| 400 | self.assertEqual(run_op(f"v_fract_f16{suffix} v0, v1", v1), want) | ||
| 401 | |||
| 402 | def test_tiny_negatives_and_subnormals_near_one_boundary(self): | ||
| 403 | # Crosses the exact binary16 rounding transition: -2^-10 and -3*2^-12 give 0x3bfe; | ||
| 404 | # -2^-11 .. -2^-24 (including -0.0001 and -1e-5) give 0x3bff (never 0x3c00 = 1.0). | ||
| 405 | cases = [ | ||
| 406 | (H_NEG_2PM10, 0x3BFE), | ||
| 407 | (H_NEG_3P2M12, 0x3BFE), | ||
| 408 | (H_NEG_2PM11, H_NEAR_ONE), | ||
| 409 | (H_NEG_3P2M13, H_NEAR_ONE), | ||
| 410 | (H_NEG_2PM12_P, H_NEAR_ONE), | ||
| 411 | (H_NEG_2PM12, H_NEAR_ONE), | ||
| 412 | (H_NEG_2PM12_M, H_NEAR_ONE), | ||
| 413 | (H_NEG_2PM13, H_NEAR_ONE), | ||
| 414 | (H_NEG_1E4, H_NEAR_ONE), | ||
| 415 | (H_NEG_SUB_1E5, H_NEAR_ONE), | ||
| 416 | (H_NEG_SUB_MAX, H_NEAR_ONE), | ||
| 417 | (H_NEG_SUB_MIN, H_NEAR_ONE), | ||
| 418 | ] | ||
| 419 | for h, want in cases: | ||
| 420 | with self.subTest(h=hex(h)): | ||
| 421 | self.assertEqual(oracle_fract_f16(h), want) | ||
| 422 | self.assertEqual(run_op("v_fract_f16_e32 v0, v1", 0xCAFE0000 | h), merge_half(OLD, want, 0)) | ||
| 423 | self.assertEqual(run_op("v_fract_f16_e64 v0, v1 op_sel:[0,1]", 0xCAFE0000 | h), | ||
| 424 | merge_half(OLD, want, 1)) | ||
| 425 | |||
| 426 | def test_exact_integers_and_signed_zero_give_positive_zero(self): | ||
| 427 | # GLSL.std.450 Fract(-0.0) in spirv_mini_interp returns +0.0 (copysign == +1), matching hardware. | ||
| 428 | self.assertEqual(si._fract(-0.0), 0.0) | ||
| 429 | self.assertEqual(math.copysign(1.0, si._fract(-0.0)), 1.0) | ||
| 430 | for h in (H_POS_ZERO, H_NEG_ZERO, H_1P0, H_NEG_1P0, H_2P0, H_NEG_2P0, | ||
| 431 | H_3P0, H_NEG_3P0, H_1024, H_NEG_1024, H_MAX, H_NEG_MAX): | ||
| 432 | with self.subTest(h=hex(h)): | ||
| 433 | got = run_op("v_fract_f16_e32 v0, v1", 0xABCD0000 | h) | ||
| 434 | self.assertEqual(got, merge_half(OLD, H_POS_ZERO, 0)) | ||
| 435 | self.assertNotEqual(got & 0xFFFF, H_NEG_ZERO) | ||
| 436 | got_hi = run_op("v_fract_f16_e64 v0, v1 op_sel:[1,1]", (h << 16) | 0x1111) | ||
| 437 | self.assertEqual(got_hi, merge_half(OLD, H_POS_ZERO, 1)) | ||
| 438 | |||
| 439 | def test_runtime_memory_inputs_via_s_buffer_load(self): | ||
| 440 | # Loaded at runtime through s_buffer_load_dwordx4 so constant folding cannot bypass Fract. | ||
| 441 | lanes_lo = [H_NEG_1E4, H_NEG_SUB_1E5, H_NEG_ZERO, H_3P75] | ||
| 442 | lanes_hi = [H_NEG_MAX, H_NEG_0P25, H_1P25, H_POS_INF] | ||
| 443 | packed = [(hi << 16) | lo for lo, hi in zip(lanes_lo, lanes_hi)] | ||
| 444 | mem = {0x1000 + 4 * i: w for i, w in enumerate(packed)} | ||
| 445 | for idx, (lo, hi) in enumerate(zip(lanes_lo, lanes_hi)): | ||
| 446 | reg = f"v{idx + 1}" | ||
| 447 | lines_head = [ | ||
| 448 | "s_buffer_load_dwordx4 s[4:7], s[0:3], 0", | ||
| 449 | "s_waitcnt lgkmcnt(0)", | ||
| 450 | "v_mov_b32_e32 v1, s4", | ||
| 451 | "v_mov_b32_e32 v2, s5", | ||
| 452 | "v_mov_b32_e32 v3, s6", | ||
| 453 | "v_mov_b32_e32 v4, s7", | ||
| 454 | f"v_mov_b32_e32 v0, {OLD:#x}", | ||
| 455 | ] | ||
| 456 | got_lo = run_ps(lines_head + [f"v_fract_f16_e32 v0, {reg}"], push_constants=PUSH_ADDR, memory=mem) | ||
| 457 | self.assertEqual(got_lo, merge_half(OLD, oracle_fract_f16(lo), 0)) | ||
| 458 | got_hi = run_ps(lines_head + [f"v_fract_f16_e64 v0, {reg} op_sel:[1,1]"], | ||
| 459 | push_constants=PUSH_ADDR, memory=mem) | ||
| 460 | want_hi = oracle_fract_f16(hi) | ||
| 461 | if want_hi is None: | ||
| 462 | self.assertEqual(got_hi & 0xFFFF, OLD & 0xFFFF) | ||
| 463 | self.assertTrue(h16_is_nan(got_hi >> 16), hex(got_hi)) | ||
| 464 | else: | ||
| 465 | self.assertEqual(got_hi, merge_half(OLD, want_hi, 1)) | ||
| 466 | |||
| 467 | def test_inf_and_nan_produce_nan_and_preserve_untouched_half(self): | ||
| 468 | # Verify spirv_mini_interp Fract on +-inf/NaN and translator's OpFOrdEqual guard. | ||
| 469 | self.assertTrue(math.isnan(si._fract(float("inf")))) | ||
| 470 | self.assertTrue(math.isnan(si._fract(float("-inf")))) | ||
| 471 | self.assertTrue(math.isnan(si._fract(float("nan")))) | ||
| 472 | |||
| 473 | for h in (H_POS_INF, H_NEG_INF, H_QNAN, H_NEG_QNAN, H_SNAN, H_NEG_SNAN): | ||
| 474 | for suffix in ("_e32", "_e64", ""): | ||
| 475 | with self.subTest(h=hex(h), form=suffix or "bare"): | ||
| 476 | got = run_op(f"v_fract_f16{suffix} v0, v1", 0xCAFE0000 | h) | ||
| 477 | self.assertEqual(got & 0xFFFF0000, OLD & 0xFFFF0000) | ||
| 478 | self.assertTrue(h16_is_nan(got & 0xFFFF), f"expected NaN in low half, got {got:#010x}") | ||
| 479 | for src_hi, dst_hi in itertools.product((0, 1), repeat=2): | ||
| 480 | v1 = ((h << 16) | H_0P25) if src_hi else ((H_0P25 << 16) | h) | ||
| 481 | with self.subTest(h=hex(h), src_hi=src_hi, dst_hi=dst_hi): | ||
| 482 | got = run_op(f"v_fract_f16_e64 v0, v1 op_sel:[{src_hi},{dst_hi}]", v1) | ||
| 483 | if dst_hi: | ||
| 484 | self.assertEqual(got & 0xFFFF, OLD & 0xFFFF) | ||
| 485 | self.assertTrue(h16_is_nan(got >> 16), hex(got)) | ||
| 486 | else: | ||
| 487 | self.assertEqual(got & 0xFFFF0000, OLD & 0xFFFF0000) | ||
| 488 | self.assertTrue(h16_is_nan(got & 0xFFFF), hex(got)) | ||
| 489 | |||
| 490 | def test_op_sel_all_four_combinations(self): | ||
| 491 | pairs = [ | ||
| 492 | (H_NEG_1P25, H_0P25), # hi: 0.75, lo: 0.25 | ||
| 493 | (H_NEG_SUB_1E5, H_3P75), # hi: 0x3bff, lo: 0.75 | ||
| 494 | ] | ||
| 495 | for hi, lo in pairs: | ||
| 496 | v1 = (hi << 16) | lo | ||
| 497 | for src_hi, dst_hi in itertools.product((0, 1), repeat=2): | ||
| 498 | h_in = hi if src_hi else lo | ||
| 499 | line = f"v_fract_f16_e64 v0, v1 op_sel:[{src_hi},{dst_hi}]" | ||
| 500 | with self.subTest(line=line, v1=hex(v1)): | ||
| 501 | self.assertEqual(run_op(line, v1), merge_half(OLD, oracle_fract_f16(h_in), dst_hi)) | ||
| 502 | |||
| 503 | def test_vop3_source_modifiers(self): | ||
| 504 | cases = [ | ||
| 505 | ("v_fract_f16_e64 v0, -v1 op_sel:[0,0]", (H_NEG_1P25 << 16) | H_0P25, H_0P25, False, True, 0), | ||
| 506 | ("v_fract_f16_e64 v0, -v1 op_sel:[1,1]", (H_NEG_0P25 << 16) | H_1P25, H_NEG_0P25, False, True, 1), | ||
| 507 | ("v_fract_f16_e64 v0, -v1 op_sel:[0,0]", (H_0P25 << 16) | H_2PM13, H_2PM13, False, True, 0), | ||
| 508 | ("v_fract_f16_e64 v0, -v1 op_sel:[0,0]", H_POS_ZERO, H_POS_ZERO, False, True, 0), | ||
| 509 | ("v_fract_f16_e64 v0, -v1 op_sel:[0,0]", H_1P0, H_1P0, False, True, 0), | ||
| 510 | ("v_fract_f16_e64 v0, |v1| op_sel:[1,1]", (H_NEG_1P25 << 16) | H_0P25, H_NEG_1P25, True, False, 1), | ||
| 511 | ("v_fract_f16_e64 v0, |v1| op_sel:[1,0]", (H_NEG_2PM13 << 16) | H_0P5, H_NEG_2PM13, True, False, 0), | ||
| 512 | ("v_fract_f16_e64 v0, -|v1| op_sel:[1,0]", (H_NEG_1P25 << 16) | H_0P25, H_NEG_1P25, True, True, 0), | ||
| 513 | ("v_fract_f16_e64 v0, -|v1| op_sel:[0,1]", (H_0P5 << 16) | H_3P75, H_3P75, True, True, 1), | ||
| 514 | ("v_fract_f16_e64 v0, -|v1| op_sel:[0,0]", H_2PM13, H_2PM13, True, True, 0), | ||
| 515 | ] | ||
| 516 | for line, v1, h_in, abs_, neg, dst_hi in cases: | ||
| 517 | with self.subTest(line=line, v1=hex(v1)): | ||
| 518 | want = oracle_fract_f16(h_in, abs_=abs_, neg=neg) | ||
| 519 | self.assertEqual(run_op(line, v1), merge_half(OLD, want, dst_hi)) | ||
| 520 | |||
| 521 | # Source modifiers on inf/NaN preserve NaN output and keep untouched half. | ||
| 522 | for mod in ("-v1", "|v1|", "-|v1|"): | ||
| 523 | for h in (H_POS_INF, H_NEG_INF, H_QNAN): | ||
| 524 | with self.subTest(mod=mod, h=hex(h)): | ||
| 525 | got = run_op(f"v_fract_f16_e64 v0, {mod}", (H_0P25 << 16) | h) | ||
| 526 | self.assertEqual(got & 0xFFFF0000, OLD & 0xFFFF0000) | ||
| 527 | self.assertTrue(h16_is_nan(got & 0xFFFF), hex(got)) | ||
| 528 | |||
| 529 | def test_vop3_output_modifiers(self): | ||
| 530 | # (asm_suffix, input_h, dst_hi, kwargs_for_oracle) | ||
| 531 | cases = [ | ||
| 532 | # clamp without omod keeps [0, 1) and preserves 0x3c00 -> 0x3bff | ||
| 533 | ("clamp", H_0P75, 0, dict(clamp=True)), | ||
| 534 | ("clamp", H_NEG_0P25, 0, dict(clamp=True)), | ||
| 535 | ("clamp", H_NEG_2PM13, 0, dict(clamp=True)), | ||
| 536 | ("clamp", H_NEG_ZERO, 0, dict(clamp=True)), | ||
| 537 | # mul:2 / mul:4 / div:2 (true 1.0 stays 0x3c00 when omod is active) | ||
| 538 | ("mul:2", H_0P5, 0, dict(mul=2)), | ||
| 539 | ("mul:2", H_0P75, 0, dict(mul=2)), | ||
| 540 | ("mul:2", H_NEG_0P25, 0, dict(mul=2)), | ||
| 541 | ("mul:2", H_NEG_2PM13, 0, dict(mul=2)), | ||
| 542 | ("mul:4", H_0P25, 0, dict(mul=4)), | ||
| 543 | ("mul:4", H_0P5, 0, dict(mul=4)), | ||
| 544 | ("mul:4", H_NEG_1P25, 0, dict(mul=4)), | ||
| 545 | ("div:2", H_0P5, 0, dict(div=2)), | ||
| 546 | ("div:2", H_NEG_1P25, 0, dict(div=2)), | ||
| 547 | ("div:2", H_0P25, 0, dict(div=2)), | ||
| 548 | ("div:2", H_NEG_2PM13, 0, dict(div=2)), | ||
| 549 | # combined omod + clamp | ||
| 550 | ("mul:2 clamp", H_0P25, 0, dict(mul=2, clamp=True)), | ||
| 551 | ("mul:2 clamp", H_0P5, 0, dict(mul=2, clamp=True)), | ||
| 552 | ("mul:2 clamp", H_0P75, 0, dict(mul=2, clamp=True)), | ||
| 553 | ("mul:2 clamp", H_NEG_0P25, 0, dict(mul=2, clamp=True)), | ||
| 554 | ("mul:4 clamp", H_0P5, 0, dict(mul=4, clamp=True)), | ||
| 555 | ("op_sel:[1,1] mul:2 clamp", H_NEG_1P25, 1, dict(mul=2, clamp=True)), | ||
| 556 | ("op_sel:[1,1] mul:4 clamp", H_0P125, 1, dict(mul=4, clamp=True)), | ||
| 557 | ] | ||
| 558 | for suffix, h_in, dst_hi, kw in cases: | ||
| 559 | v1 = ((h_in << 16) | H_0P25) if "op_sel:[1,1]" in suffix else ((H_3P75 << 16) | h_in) | ||
| 560 | line = f"v_fract_f16_e64 v0, v1 {suffix}" | ||
| 561 | want = oracle_fract_f16(h_in, **kw) | ||
| 562 | with self.subTest(line=line, h_in=hex(h_in)): | ||
| 563 | self.assertEqual(run_op(line, v1), merge_half(OLD, want, dst_hi)) | ||
| 564 | |||
| 565 | # Verify explicit exact values for the critical omod transitions. | ||
| 566 | self.assertEqual(run_op("v_fract_f16_e64 v0, v1 mul:2", H_0P5), merge_half(OLD, H_1P0, 0)) | ||
| 567 | self.assertEqual(run_op("v_fract_f16_e64 v0, v1 mul:2 clamp", H_0P75), merge_half(OLD, H_1P0, 0)) | ||
| 568 | self.assertEqual(run_op("v_fract_f16_e64 v0, v1 mul:4", H_0P5), merge_half(OLD, H_2P0, 0)) | ||
| 569 | self.assertEqual(run_op("v_fract_f16_e64 v0, v1 div:2", H_0P5), merge_half(OLD, H_0P25, 0)) | ||
| 570 | |||
| 571 | def test_inline_f16_constants(self): | ||
| 572 | for lit, h in (("0.5", H_0P5), ("-0.5", H_NEG_0P5), ("1.0", H_1P0), ("-1.0", H_NEG_1P0)): | ||
| 573 | want = oracle_fract_f16(h) | ||
| 574 | for form in ("_e32", "_e64", ""): | ||
| 575 | with self.subTest(lit=lit, form=form or "bare"): | ||
| 576 | self.assertEqual(run_op(f"v_fract_f16{form} v0, {lit}"), merge_half(OLD, want, 0)) | ||
| 577 | # op_sel:[0,1] writes the inline constant's fract into high half; low half preserved. | ||
| 578 | self.assertEqual(run_op(f"v_fract_f16_e64 v0, {lit} op_sel:[0,1]"), merge_half(OLD, want, 1)) | ||
| 579 | # Inline float constants place +0.0 in the high half (docs/design.md / src_h). | ||
| 580 | self.assertEqual(run_op(f"v_fract_f16_e64 v0, {lit} op_sel:[1,0]"), merge_half(OLD, H_POS_ZERO, 0)) | ||
| 581 | |||
| 582 | self.assertEqual(run_op("v_fract_f16_e64 v0, -0.5 mul:2"), merge_half(OLD, H_1P0, 0)) | ||
| 583 | self.assertEqual(run_op("v_fract_f16_e64 v0, -0.5 div:2"), merge_half(OLD, H_0P25, 0)) | ||
| 584 | |||
| 585 | def test_sgpr_sources_and_destination_aliasing(self): | ||
| 586 | s4 = (H_NEG_1P25 << 16) | H_0P25 | ||
| 587 | self.assertEqual(run_op("v_fract_f16_e32 v0, s4", s4=s4), merge_half(OLD, H_0P25, 0)) | ||
| 588 | self.assertEqual(run_op("v_fract_f16_e64 v0, s4 op_sel:[0,0]", s4=s4), merge_half(OLD, H_0P25, 0)) | ||
| 589 | self.assertEqual(run_op("v_fract_f16_e64 v0, s4 op_sel:[1,0]", s4=s4), merge_half(OLD, H_0P75, 0)) | ||
| 590 | self.assertEqual(run_op("v_fract_f16_e64 v0, s4 op_sel:[0,1]", s4=s4), merge_half(OLD, H_0P25, 1)) | ||
| 591 | self.assertEqual(run_op("v_fract_f16_e64 v0, s4 op_sel:[1,1]", s4=s4), merge_half(OLD, H_0P75, 1)) | ||
| 592 | self.assertEqual(run_op("v_fract_f16_e64 v0, -s4 op_sel:[1,0]", s4=s4), merge_half(OLD, H_0P25, 0)) | ||
| 593 | self.assertEqual(run_op("v_fract_f16_e64 v0, |s4| op_sel:[1,1]", s4=s4), merge_half(OLD, H_0P25, 1)) | ||
| 594 | |||
| 595 | # Destination aliasing: dst == src (v0, v0) keeps the untouched half of v0. | ||
| 596 | v0_init = (H_3P75 << 16) | H_NEG_0P25 | ||
| 597 | self.assertEqual( | ||
| 598 | run_ps([f"v_mov_b32 v0, {v0_init:#x}", "v_fract_f16_e32 v0, v0"]), | ||
| 599 | (H_3P75 << 16) | H_0P75, | ||
| 600 | ) | ||
| 601 | self.assertEqual( | ||
| 602 | run_ps([f"v_mov_b32 v0, {v0_init:#x}", "v_fract_f16 v0, v0"]), | ||
| 603 | (H_3P75 << 16) | H_0P75, | ||
| 604 | ) | ||
| 605 | for src_hi, dst_hi in itertools.product((0, 1), repeat=2): | ||
| 606 | h_in = H_3P75 if src_hi else H_NEG_0P25 | ||
| 607 | want_h = oracle_fract_f16(h_in) | ||
| 608 | with self.subTest(alias_op_sel=(src_hi, dst_hi)): | ||
| 609 | self.assertEqual( | ||
| 610 | run_ps([ | ||
| 611 | f"v_mov_b32 v0, {v0_init:#x}", | ||
| 612 | f"v_fract_f16_e64 v0, v0 op_sel:[{src_hi},{dst_hi}]", | ||
| 613 | ]), | ||
| 614 | merge_half(v0_init, want_h, dst_hi), | ||
| 615 | ) | ||
| 616 | |||
| 617 | def test_exec_masking_single_lane_and_workgroup(self): | ||
| 618 | # Single-lane pixel shader: inactive lane preserves pre-existing v0; re-enabling executes. | ||
| 619 | self.assertEqual(run_ps([ | ||
| 620 | f"v_mov_b32 v1, {H_1P5:#x}", | ||
| 621 | f"v_mov_b32 v0, {OLD:#x}", | ||
| 622 | "s_mov_b32 exec_lo, 0", | ||
| 623 | "v_fract_f16_e32 v0, v1", | ||
| 624 | "v_fract_f16_e64 v0, v1 op_sel:[0,1]", | ||
| 625 | "s_mov_b32 exec_lo, 1", | ||
| 626 | ]), OLD) | ||
| 627 | |||
| 628 | self.assertEqual(run_ps([ | ||
| 629 | f"v_mov_b32 v1, {(H_NEG_1P25 << 16) | H_2P5:#x}", | ||
| 630 | f"v_mov_b32 v0, {OLD:#x}", | ||
| 631 | "s_mov_b32 exec_lo, 0", | ||
| 632 | "v_fract_f16_e64 v0, v1 op_sel:[0,0]", | ||
| 633 | "v_fract_f16_e64 v0, v1 op_sel:[1,1]", | ||
| 634 | "s_mov_b32 exec_lo, 1", | ||
| 635 | "v_fract_f16_e64 v0, v1 op_sel:[1,0]", | ||
| 636 | ]), merge_half(OLD, H_0P75, 0)) | ||
| 637 | |||
| 638 | # Multi-lane 8-thread compute shader: even lanes active, odd lanes masked off keep OLD. | ||
| 639 | lane_inputs = [ | ||
| 640 | (H_NEG_1P25 << 16) | H_0P25, | ||
| 641 | (H_3P75 << 16) | H_NEG_0P25, | ||
| 642 | (H_NEG_SUB_1E5 << 16) | H_1P25, | ||
| 643 | (H_2P5 << 16) | H_NEG_1E4, | ||
| 644 | (H_NEG_ZERO << 16) | H_NEG_0P5, | ||
| 645 | (H_1P5 << 16) | H_NEG_MAX, | ||
| 646 | (H_NEG_MAX << 16) | H_NEG_2PM12, | ||
| 647 | (H_0P75 << 16) | H_3P75, | ||
| 648 | ] | ||
| 649 | lane_olds = [0xAA00BB00 + 0x00110001 * i for i in range(8)] | ||
| 650 | for dst_hi, op_line in ( | ||
| 651 | (0, "v_fract_f16_e32 v2, v1"), | ||
| 652 | (1, "v_fract_f16_e64 v2, v1 op_sel:[1,1]"), | ||
| 653 | ): | ||
| 654 | mem = _Heap( | ||
| 655 | {0x100 + 4 * i: w for i, w in enumerate(lane_inputs)} | ||
| 656 | | {0x200 + 4 * i: w for i, w in enumerate(lane_olds)} | ||
| 657 | ) | ||
| 658 | run_cs([ | ||
| 659 | "v_lshlrev_b32_e32 v5, 2, v0", | ||
| 660 | "v_add_nc_u32_e32 v6, 0x100, v5", | ||
| 661 | "v_add_nc_u32_e32 v7, 0x200, v5", | ||
| 662 | "buffer_load_dword v1, v6, s[0:3], 0 offen", | ||
| 663 | "buffer_load_dword v2, v7, s[0:3], 0 offen", | ||
| 664 | "v_and_b32_e32 v3, 1, v0", | ||
| 665 | "v_cmp_eq_u32_e32 vcc_lo, 0, v3", | ||
| 666 | "s_and_saveexec_b32 s6, vcc_lo", | ||
| 667 | op_line, | ||
| 668 | "s_mov_b32 exec_lo, s6", | ||
| 669 | "buffer_store_dword v2, v5, s[0:3], 0 offen", | ||
| 670 | ], group_size=8, memory=mem) | ||
| 671 | |||
| 672 | got = [mem.get(4 * i) for i in range(8)] | ||
| 673 | want = [] | ||
| 674 | for lane, (inp, old_w) in enumerate(zip(lane_inputs, lane_olds)): | ||
| 675 | if lane & 1: | ||
| 676 | want.append(old_w) | ||
| 677 | else: | ||
| 678 | h_in = (inp >> 16) if dst_hi else (inp & 0xFFFF) | ||
| 679 | want.append(merge_half(old_w, oracle_fract_f16(h_in), dst_hi)) | ||
| 680 | with self.subTest(op_line=op_line): | ||
| 681 | self.assertEqual(got, want) | ||
| 682 | |||
| 683 | def test_negative_control_sabotaged_spirv(self): | ||
| 684 | # Input -1.25: true fract = 0.75 (0x3a00); Trunc gives -1.0 (0xbc00); Floor gives -2.0 (0xc000). | ||
| 685 | spv = translate_ps([ | ||
| 686 | f"v_mov_b32 v1, {H_NEG_1P25:#x}", | ||
| 687 | f"v_mov_b32 v0, {OLD:#x}", | ||
| 688 | "v_fract_f16_e32 v0, v1", | ||
| 689 | ]) | ||
| 690 | expected = merge_half(OLD, H_0P75, 0) | ||
| 691 | self.assertEqual(si.run_fragment(spv)["%out_mrt0"][0], expected) | ||
| 692 | |||
| 693 | for replacement, sabotaged_half in (("Trunc", H_NEG_1P0), ("Floor", H_NEG_2P0)): | ||
| 694 | sabotaged, n = re.subn(r"\bFract\b", replacement, spv, count=1) | ||
| 695 | self.assertEqual(n, 1) | ||
| 696 | got = si.run_fragment(sabotaged)["%out_mrt0"][0] | ||
| 697 | with self.subTest(replacement=replacement): | ||
| 698 | self.assertNotEqual(got, expected) | ||
| 699 | self.assertEqual(got, merge_half(OLD, sabotaged_half, 0)) | ||
| 700 | |||
| 701 | |||
| 702 | if __name__ == "__main__": | ||
| 703 | unittest.main() | ||
diff --git a/tests/semantic/test_valu_permlane16.py b/tests/semantic/test_valu_permlane16.py new file mode 100644 index 000000000..3256b9d8d --- /dev/null +++ b/tests/semantic/test_valu_permlane16.py | |||
| @@ -0,0 +1,814 @@ | |||
| 1 | """Semantic value and translation tests for RDNA2 cross-lane permutes: | ||
| 2 | v_permlane16_b32 D = vS[(l & ~15) | sel[l & 15]] | ||
| 3 | v_permlanex16_b32 D = vS[((l & ~15) ^ 16) | sel[l & 15]] | ||
| 4 | |||
| 5 | where the 4-bit lane selector nibbles `sel[0..7]` come from `src1` (bits `[4*k+3 : 4*k]`) and | ||
| 6 | `sel[8..15]` come from `src2` (bits `[4*(k-8)+3 : 4*(k-8)]`), applied independently inside each | ||
| 7 | 32-lane row (`[0..15]` and `[16..31]`, and in wave64 `[32..47]` and `[48..63]`). Only lanes active | ||
| 8 | in `EXEC` write `vD`; inactive destination lanes preserve their prior `vD`. | ||
| 9 | |||
| 10 | Executed end-to-end through `tools/rdna2spirv.py` and `tests/semantic/spirv_mini_interp.py` | ||
| 11 | (`run_workgroup`) across 32 lanes (wave32) and 64 lanes (wave64 on both one 64-wide subgroup and | ||
| 12 | two 32-wide subgroups), as well as partial waves (20 and 40 lanes), and checked against | ||
| 13 | hand-computed constants and an independent plain-Python RDNA2 ISA reference model. Standard library | ||
| 14 | only; zero game data; hand-written RDNA2 disassembly listings only. | ||
| 15 | |||
| 16 | Documented findings (observed in `tools/rdna2spirv.py`; no shared files modified): | ||
| 17 | 1. `op_sel:[fi, bound_ctrl]` and inactive source lanes (`tools/rdna2spirv.py` lines 4608-4632): | ||
| 18 | In RDNA2 ISA (measured on RDNA2 gfx1036 and RDNA3.5 gfx1150; see `docs/shader_validation.md` | ||
| 19 | and `tools/crosslane_fuzz.py`), when a source lane is inactive in `EXEC` (`EXEC[src] == 0`): | ||
| 20 | - `fi=1` (`op_sel:[1,0]`, `op_sel:[1,1]`): reads the inactive source lane's pre-existing `vS`. | ||
| 21 | - `fi=0, bound_ctrl=0` (`op_sel:[0,0]` or omitted): keeps the destination lane's prior `vD`. | ||
| 22 | - `fi=0, bound_ctrl=1` (`op_sel:[0,1]`): writes `0` to the destination lane. | ||
| 23 | `tools/rdna2spirv.py` lines 4608-4632 do not inspect `mods` (`op_sel:[fi, bound_ctrl]`) and emit | ||
| 24 | `self.g_shuffle(r, v, src)` unconditionally without checking the source lane's `%active` bit. | ||
| 25 | Therefore: | ||
| 26 | - When all accessed source lanes are active in `EXEC`, all four `op_sel` modes (`[0,0]`, | ||
| 27 | `[1,0]`, `[0,1]`, `[1,1]`) and omitted `op_sel` match the RDNA2 ISA. | ||
| 28 | - When a source lane is inactive in `EXEC` and `fi=1` (`op_sel:[1,0]`, `op_sel:[1,1]`), the | ||
| 29 | translation matches the RDNA2 ISA (reading the inactive source lane's pre-existing `vS`). | ||
| 30 | - When a source lane is inactive in `EXEC` and `fi=0` (`op_sel:[0,0]`/omitted, | ||
| 31 | `op_sel:[0,1]`), the translator currently reads `vS[src]` instead of keeping `vD` or | ||
| 32 | writing `0`. Those inactive-source `fi=0` cases are tested in the plain-Python ISA | ||
| 33 | reference tests (`OracleTests`) and excluded from passing end-to-end assertions rather | ||
| 34 | than relaxing expected values; structural SPIR-V translation is verified in | ||
| 35 | `EmulationAndFindingTests`. | ||
| 36 | 2. `--wave64-emulate` (`tools/rdna2spirv.py` lines 2671-2810, 2890-2895, 4608-4632): | ||
| 37 | With `WAVE64_EMULATE = True`, wave64 compute/mesh shaders lower `g_shuffle` and `sub_lane` | ||
| 38 | through `%x_buf` Workgroup-memory exchanges, `OpControlBarrier`, and a round loop (`OpLoopMerge` | ||
| 39 | with a backward branch). `tests/semantic/spirv_mini_interp.py` rejects `Workgroup` barriers and | ||
| 40 | non-forward branches (`UnsupportedConstruct`), so `--wave64-emulate` is covered by translation | ||
| 41 | and structural SPIR-V invariants here (and rejected cleanly by `run_workgroup`). | ||
| 42 | 3. Wave64 native on two 32-wide subgroups (`subgroup_size = 32`): | ||
| 43 | Because `v_permlane16_b32` and `v_permlanex16_b32` never cross the 32-lane row boundary | ||
| 44 | (`0..31` vs `32..63`), both instructions stay exact across all 64 lanes even on two 32-wide | ||
| 45 | subgroups without `--wave64-emulate`. | ||
| 46 | """ | ||
| 47 | import gc | ||
| 48 | import os | ||
| 49 | import re | ||
| 50 | import struct | ||
| 51 | import sys | ||
| 52 | import tempfile | ||
| 53 | import unittest | ||
| 54 | import warnings | ||
| 55 | |||
| 56 | HERE = os.path.dirname(os.path.abspath(__file__)) | ||
| 57 | ROOT = os.path.dirname(os.path.dirname(HERE)) | ||
| 58 | TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") | ||
| 59 | |||
| 60 | sys.dont_write_bytecode = True | ||
| 61 | if TOOLS_DIR not in sys.path: | ||
| 62 | sys.path.insert(0, TOOLS_DIR) | ||
| 63 | if HERE not in sys.path: | ||
| 64 | sys.path.insert(0, HERE) | ||
| 65 | |||
| 66 | import rdna2spirv # noqa: E402 | ||
| 67 | import spirv_mini_interp as si # noqa: E402 | ||
| 68 | |||
| 69 | MASK32 = 0xFFFFFFFF | ||
| 70 | ALL32 = 0xFFFFFFFF | ||
| 71 | ALL64 = 0xFFFFFFFFFFFFFFFF | ||
| 72 | OLD_SENTINEL = 0xCAFE0000 | ||
| 73 | HEAP_FILL = 0xEEEEEEEE | ||
| 74 | # V# in s[0:3]: base 0, stride 0, num_records 0x10000 bytes (OOB_SELECT = 3). | ||
| 75 | VSHARP = [0, 0, 0x10000, 0x31016FAC] | ||
| 76 | INPUT_BASE = 0x8000 | ||
| 77 | |||
| 78 | ID_S1 = 0x76543210 | ||
| 79 | ID_S2 = 0xFEDCBA98 | ||
| 80 | REV8_S1 = 0x01234567 | ||
| 81 | REV8_S2 = 0x89ABCDEF | ||
| 82 | REV16_S1 = 0x89ABCDEF | ||
| 83 | REV16_S2 = 0x01234567 | ||
| 84 | PAIR_SWAP_S1 = 0x10325476 | ||
| 85 | PAIR_SWAP_S2 = 0x98BADCFE | ||
| 86 | ASYM_S1 = 0x3A0F5C91 | ||
| 87 | ASYM_S2 = 0xE27B48D6 | ||
| 88 | |||
| 89 | |||
| 90 | def ref_permlane(x16: bool, src_vals: list[int], dst_old: list[int], s1: int, s2: int, | ||
| 91 | exec_mask: int, fi: int = 0, bound_ctrl: int = 0) -> list[int]: | ||
| 92 | """Independent RDNA2 ISA reference model for v_permlane16_b32 / v_permlanex16_b32.""" | ||
| 93 | lanes = len(src_vals) | ||
| 94 | assert len(dst_old) == lanes and lanes in (32, 64) | ||
| 95 | out = [] | ||
| 96 | for lane in range(lanes): | ||
| 97 | if not ((exec_mask >> lane) & 1): | ||
| 98 | out.append(dst_old[lane] & MASK32) | ||
| 99 | continue | ||
| 100 | within = lane & 15 | ||
| 101 | sel_word = s2 if within >= 8 else s1 | ||
| 102 | nib = (sel_word >> (4 * (lane & 7))) & 0xF | ||
| 103 | half = lane & ~15 | ||
| 104 | row = (half ^ 16) if x16 else half | ||
| 105 | src_lane = row | nib | ||
| 106 | if ((exec_mask >> src_lane) & 1) or fi: | ||
| 107 | out.append(src_vals[src_lane] & MASK32) | ||
| 108 | elif bound_ctrl: | ||
| 109 | out.append(0) | ||
| 110 | else: | ||
| 111 | out.append(dst_old[lane] & MASK32) | ||
| 112 | return out | ||
| 113 | |||
| 114 | |||
| 115 | class _Heap(dict): | ||
| 116 | def get(self, key, default=None): | ||
| 117 | return super().get(key, HEAP_FILL) | ||
| 118 | |||
| 119 | |||
| 120 | _TMP_DIR = None | ||
| 121 | _DISASM_DIR = None | ||
| 122 | _FSSM_DIR = None | ||
| 123 | |||
| 124 | |||
| 125 | def _make_fssm(threads: int, rsrc2: int = 0x8088) -> bytes: | ||
| 126 | header = bytearray(0x148) | ||
| 127 | struct.pack_into("<4I", header, 0x138, rsrc2, threads, 1, 1) | ||
| 128 | return bytes(header) | ||
| 129 | |||
| 130 | |||
| 131 | def setUpModule(): | ||
| 132 | global _TMP_DIR, _DISASM_DIR, _FSSM_DIR | ||
| 133 | _TMP_DIR = tempfile.TemporaryDirectory() | ||
| 134 | _DISASM_DIR = os.path.join(_TMP_DIR.name, "disasm") | ||
| 135 | _FSSM_DIR = os.path.join(_TMP_DIR.name, "fssm") | ||
| 136 | os.mkdir(_DISASM_DIR) | ||
| 137 | os.mkdir(_FSSM_DIR) | ||
| 138 | |||
| 139 | |||
| 140 | def tearDownModule(): | ||
| 141 | global _TMP_DIR, _DISASM_DIR, _FSSM_DIR | ||
| 142 | if _TMP_DIR is not None: | ||
| 143 | gc.collect() | ||
| 144 | _TMP_DIR.cleanup() | ||
| 145 | _TMP_DIR = None | ||
| 146 | _DISASM_DIR = None | ||
| 147 | _FSSM_DIR = None | ||
| 148 | |||
| 149 | |||
| 150 | def translate_cs(name: str, lines: list[str], threads: int, emulate: bool = False) -> tuple[str, object]: | ||
| 151 | assert name.startswith("cs_"), f"compute shader name must start with cs_: {name!r}" | ||
| 152 | if _TMP_DIR is None: | ||
| 153 | setUpModule() | ||
| 154 | with open(os.path.join(_FSSM_DIR, name + ".fssm"), "wb") as f: | ||
| 155 | f.write(_make_fssm(threads)) | ||
| 156 | src_path = os.path.join(_DISASM_DIR, name + ".s") | ||
| 157 | asm = f"; {name}\n" + "".join(f"\t{ln}\n" for ln in lines) + "\ts_endpgm\n" | ||
| 158 | with open(src_path, "w", encoding="utf-8", newline="") as f: | ||
| 159 | f.write(asm) | ||
| 160 | old_emu = rdna2spirv.WAVE64_EMULATE | ||
| 161 | rdna2spirv.WAVE64_EMULATE = emulate | ||
| 162 | try: | ||
| 163 | with warnings.catch_warnings(): | ||
| 164 | warnings.simplefilter("ignore", ResourceWarning) | ||
| 165 | spv = rdna2spirv.translate(src_path) | ||
| 166 | gen = rdna2spirv.translate.last_gen | ||
| 167 | gc.collect() | ||
| 168 | finally: | ||
| 169 | rdna2spirv.WAVE64_EMULATE = old_emu | ||
| 170 | return spv, gen | ||
| 171 | |||
| 172 | |||
| 173 | def run_cs(name: str, lines: list[str], threads: int, subgroup_size: int, | ||
| 174 | init_inputs: list[int] | None = None, out_slots: int = 1) -> list[int]: | ||
| 175 | """Translate and run a compute shader; return `threads * out_slots` 32-bit output words.""" | ||
| 176 | spv, _ = translate_cs(name, lines, threads, emulate=False) | ||
| 177 | mem = _Heap() | ||
| 178 | if init_inputs is not None: | ||
| 179 | for i, val in enumerate(init_inputs): | ||
| 180 | mem[INPUT_BASE + 4 * i] = val & MASK32 | ||
| 181 | si.run_workgroup( | ||
| 182 | spv, threads, subgroup_size, | ||
| 183 | inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i % subgroup_size}, | ||
| 184 | push_constants=VSHARP + [0] * 28, | ||
| 185 | memory=mem, | ||
| 186 | ) | ||
| 187 | out_bytes = 4 * threads * out_slots | ||
| 188 | stray = sorted(a for a in mem if a < INPUT_BASE and (a % 4 != 0 or a >= out_bytes)) | ||
| 189 | if stray: | ||
| 190 | raise AssertionError(f"{name}: unexpected stores outside out[0..{threads * out_slots - 1}]: {stray}") | ||
| 191 | return [mem.get(4 * k) for k in range(threads * out_slots)] | ||
| 192 | |||
| 193 | |||
| 194 | def exec_mask_lines(mask: int, wave: int) -> list[str]: | ||
| 195 | lines = [f"s_mov_b32 exec_lo, {mask & MASK32:#x}"] | ||
| 196 | if wave == 64: | ||
| 197 | lines.append(f"s_mov_b32 exec_hi, {(mask >> 32) & MASK32:#x}") | ||
| 198 | return lines | ||
| 199 | |||
| 200 | |||
| 201 | def restore_exec_lines(wave: int) -> list[str]: | ||
| 202 | return ["s_mov_b64 exec, -1"] if wave == 64 else ["s_mov_b32 exec_lo, -1"] | ||
| 203 | |||
| 204 | |||
| 205 | def store_slots_lines(regs: list[str], threads: int) -> list[str]: | ||
| 206 | """Emit buffer_store_dword for each VGPR in `regs` at `4 * (slot * threads + v0)`.""" | ||
| 207 | lines = ["v_lshlrev_b32_e32 v21, 2, v0"] | ||
| 208 | for slot, reg in enumerate(regs): | ||
| 209 | if slot == 0: | ||
| 210 | lines.append(f"buffer_store_dword {reg}, v21, s[0:3], 0 offen") | ||
| 211 | else: | ||
| 212 | lines.append(f"buffer_store_dword {reg}, v21, s[0:3], 0 offen offset:{4 * slot * threads}") | ||
| 213 | return lines | ||
| 214 | |||
| 215 | |||
| 216 | class OracleTests(unittest.TestCase): | ||
| 217 | """Cross-check hand-worked constants and ISA semantics against ref_permlane.""" | ||
| 218 | |||
| 219 | def test_hand_worked_identity_and_half_swap(self): | ||
| 220 | vals32 = [100 + l for l in range(32)] | ||
| 221 | old32 = [OLD_SENTINEL | l for l in range(32)] | ||
| 222 | # v_permlane16_b32 identity leaves all 32 lanes unchanged. | ||
| 223 | self.assertEqual(ref_permlane(False, vals32, old32, ID_S1, ID_S2, ALL32), vals32) | ||
| 224 | # v_permlanex16_b32 swaps [0..15] and [16..31]. | ||
| 225 | self.assertEqual( | ||
| 226 | ref_permlane(True, vals32, old32, ID_S1, ID_S2, ALL32), | ||
| 227 | [100 + (l ^ 16) for l in range(32)], | ||
| 228 | ) | ||
| 229 | |||
| 230 | # Wave64 swaps within each 32-lane row: [0..15]<->[16..31] and [32..47]<->[48..63]. | ||
| 231 | vals64 = [500 + l for l in range(64)] | ||
| 232 | old64 = [OLD_SENTINEL | l for l in range(64)] | ||
| 233 | got64 = ref_permlane(True, vals64, old64, ID_S1, ID_S2, ALL64) | ||
| 234 | self.assertEqual((got64[0], got64[15], got64[16], got64[31]), (516, 531, 500, 515)) | ||
| 235 | self.assertEqual((got64[32], got64[47], got64[48], got64[63]), (548, 563, 532, 547)) | ||
| 236 | |||
| 237 | def test_hand_worked_nibble_patterns_and_exec_opsel_rules(self): | ||
| 238 | vals32 = [1000 + l for l in range(32)] | ||
| 239 | old32 = [OLD_SENTINEL | l for l in range(32)] | ||
| 240 | |||
| 241 | # Broadcast 0 from s1 (lanes 0..7) and 15 from s2 (lanes 8..15). | ||
| 242 | got_bcast = ref_permlane(False, vals32, old32, 0x00000000, 0xFFFFFFFF, ALL32) | ||
| 243 | self.assertEqual(got_bcast[0:8], [1000] * 8) | ||
| 244 | self.assertEqual(got_bcast[8:16], [1015] * 8) | ||
| 245 | self.assertEqual(got_bcast[16:24], [1016] * 8) | ||
| 246 | self.assertEqual(got_bcast[24:32], [1031] * 8) | ||
| 247 | |||
| 248 | # Full 16-lane reversal: s1=0x89abcdef (lanes 0..7 -> 15..8), s2=0x01234567 (lanes 8..15 -> 7..0). | ||
| 249 | got_rev16 = ref_permlane(False, vals32, old32, REV16_S1, REV16_S2, ALL32) | ||
| 250 | self.assertEqual(got_rev16[0:16], [1000 + (15 - l) for l in range(16)]) | ||
| 251 | self.assertEqual(got_rev16[16:32], [1016 + (15 - l) for l in range(16)]) | ||
| 252 | |||
| 253 | # Sub-half 8-lane reversal: s1=0x01234567 (0..7 -> 7..0), s2=0x89abcdef (8..15 -> 15..8). | ||
| 254 | got_rev8 = ref_permlane(True, vals32, old32, REV8_S1, REV8_S2, ALL32) | ||
| 255 | self.assertEqual(got_rev8[0:8], [1016 + (7 - l) for l in range(8)]) | ||
| 256 | self.assertEqual(got_rev8[8:16], [1016 + (15 - l) for l in range(8)]) | ||
| 257 | |||
| 258 | # op_sel:[fi, bound_ctrl] when lane 0 is INACTIVE in EXEC (0xFFFFFFFE): | ||
| 259 | # lanes 1..15 broadcast local lane 0 (inactive in half 0!), lanes 16..31 broadcast local lane 16 (active!). | ||
| 260 | exec_no_0 = ALL32 ^ 1 | ||
| 261 | # fi=0, bound_ctrl=0 -> lanes 1..15 keep old32, lane 0 keeps old32[0], lanes 16..31 read 1016. | ||
| 262 | r00 = ref_permlane(False, vals32, old32, 0, 0, exec_no_0, fi=0, bound_ctrl=0) | ||
| 263 | self.assertEqual(r00[0], old32[0]) | ||
| 264 | self.assertEqual(r00[1:16], old32[1:16]) | ||
| 265 | self.assertEqual(r00[16:32], [1016] * 16) | ||
| 266 | |||
| 267 | # fi=0, bound_ctrl=1 -> lanes 1..15 write 0, lane 0 keeps old32[0], lanes 16..31 read 1016. | ||
| 268 | r01 = ref_permlane(False, vals32, old32, 0, 0, exec_no_0, fi=0, bound_ctrl=1) | ||
| 269 | self.assertEqual(r01[0], old32[0]) | ||
| 270 | self.assertEqual(r01[1:16], [0] * 15) | ||
| 271 | self.assertEqual(r01[16:32], [1016] * 16) | ||
| 272 | |||
| 273 | # fi=1, bound_ctrl=0 or 1 -> lanes 1..15 read inactive lane 0's vals32[0], lane 0 keeps old32[0]. | ||
| 274 | for bc in (0, 1): | ||
| 275 | r1x = ref_permlane(False, vals32, old32, 0, 0, exec_no_0, fi=1, bound_ctrl=bc) | ||
| 276 | self.assertEqual(r1x[0], old32[0]) | ||
| 277 | self.assertEqual(r1x[1:16], [1000] * 15) | ||
| 278 | self.assertEqual(r1x[16:32], [1016] * 16) | ||
| 279 | |||
| 280 | |||
| 281 | class Wave32ExecutionTests(unittest.TestCase): | ||
| 282 | """End-to-end 32-lane execution for v_permlane16_b32 and v_permlanex16_b32.""" | ||
| 283 | |||
| 284 | def _run_batch(self, specs: list[tuple[bool, int, int, str, str]], init_vals: list[int], | ||
| 285 | old_vals: list[int], exec_mask: int = ALL32) -> list[list[int]]: | ||
| 286 | """Run a list of (x16, s1, s2, src_form, extra_mods) batched into one shader.""" | ||
| 287 | lines = [ | ||
| 288 | "v_lshlrev_b32_e32 v20, 2, v0", | ||
| 289 | f"v_add_nc_u32_e32 v20, {INPUT_BASE:#x}, v20", | ||
| 290 | "buffer_load_dword v1, v20, s[0:3], 0 offen", | ||
| 291 | ] | ||
| 292 | regs = [] | ||
| 293 | for idx, _ in enumerate(specs): | ||
| 294 | dst = f"v{2 + idx}" | ||
| 295 | regs.append(dst) | ||
| 296 | lines.append(f"v_or_b32_e32 {dst}, {OLD_SENTINEL:#x}, v0") | ||
| 297 | lines.extend(exec_mask_lines(exec_mask, 32)) | ||
| 298 | for idx, (x16, s1, s2, src_expr, extra) in enumerate(specs): | ||
| 299 | dst = f"v{2 + idx}" | ||
| 300 | op = "v_permlanex16_b32" if x16 else "v_permlane16_b32" | ||
| 301 | if src_expr == "sgpr": | ||
| 302 | lines += [f"s_mov_b32 s4, {s1:#x}", f"s_mov_b32 s5, {s2:#x}", | ||
| 303 | f"{op} {dst}, v1, s4, s5{extra}"] | ||
| 304 | elif src_expr == "lit_sgpr": | ||
| 305 | lines += [f"s_mov_b32 s5, {s2:#x}", f"{op} {dst}, v1, {s1:#x}, s5{extra}"] | ||
| 306 | elif src_expr == "sgpr_lit": | ||
| 307 | lines += [f"s_mov_b32 s4, {s1:#x}", f"{op} {dst}, v1, s4, {s2:#x}{extra}"] | ||
| 308 | elif src_expr == "inline": | ||
| 309 | lines.append(f"{op} {dst}, v1, {s1}, {s2}{extra}") | ||
| 310 | elif src_expr == "same_sgpr": | ||
| 311 | assert s1 == s2 | ||
| 312 | lines += [f"s_mov_b32 s4, {s1:#x}", f"{op} {dst}, v1, s4, s4{extra}"] | ||
| 313 | elif src_expr == "e64_sgpr": | ||
| 314 | lines += [f"s_mov_b32 s4, {s1:#x}", f"s_mov_b32 s5, {s2:#x}", | ||
| 315 | f"{op}_e64 {dst}, v1, s4, s5{extra}"] | ||
| 316 | else: | ||
| 317 | raise ValueError(src_expr) | ||
| 318 | lines.extend(restore_exec_lines(32)) | ||
| 319 | lines.extend(store_slots_lines(regs, 32)) | ||
| 320 | flat = run_cs("cs_w32_permlane_batch", lines, 32, 32, init_inputs=init_vals, out_slots=len(specs)) | ||
| 321 | return [flat[slot * 32:(slot + 1) * 32] for slot in range(len(specs))] | ||
| 322 | |||
| 323 | def test_half_isolation_vs_cross_half_swap_and_nibble_selectors(self): | ||
| 324 | init_vals = [(0x10000000 + l * 0x010101) & MASK32 for l in range(32)] | ||
| 325 | old_vals = [OLD_SENTINEL | l for l in range(32)] | ||
| 326 | specs = [ | ||
| 327 | # Identity (SGPR+SGPR, literal+SGPR, SGPR+literal, _e64) | ||
| 328 | (False, ID_S1, ID_S2, "sgpr", ""), | ||
| 329 | (True, ID_S1, ID_S2, "sgpr", ""), | ||
| 330 | (False, ID_S1, ID_S2, "lit_sgpr", ""), | ||
| 331 | (True, ID_S1, ID_S2, "sgpr_lit", ""), | ||
| 332 | (True, ID_S1, ID_S2, "e64_sgpr", ""), | ||
| 333 | # Broadcasts with inline constants (0, -1, 15, -16) and same-SGPR | ||
| 334 | (False, 0, 0, "inline", ""), | ||
| 335 | (True, 0, 0, "inline", ""), | ||
| 336 | (False, -1, -1, "inline", ""), | ||
| 337 | (True, 0, -1, "inline", ""), | ||
| 338 | (False, -16, 15, "inline", ""), # -16 = 0xfffffff0, 15 = 0x0000000f | ||
| 339 | (True, 0x55555555, 0x55555555, "same_sgpr", ""), | ||
| 340 | # 8-lane reversal vs full 16-lane reversal | ||
| 341 | (False, REV8_S1, REV8_S2, "sgpr", ""), | ||
| 342 | (True, REV8_S1, REV8_S2, "sgpr", ""), | ||
| 343 | (False, REV16_S1, REV16_S2, "sgpr", ""), | ||
| 344 | (True, REV16_S1, REV16_S2, "sgpr", ""), | ||
| 345 | # Pairwise swap & asymmetric non-bijective permutation | ||
| 346 | (False, PAIR_SWAP_S1, PAIR_SWAP_S2, "sgpr", ""), | ||
| 347 | (True, ASYM_S1, ASYM_S2, "sgpr", ""), | ||
| 348 | ] | ||
| 349 | results = self._run_batch(specs, init_vals, old_vals) | ||
| 350 | for idx, (x16, s1, s2, form, _) in enumerate(specs): | ||
| 351 | s1_u = s1 & MASK32 | ||
| 352 | s2_u = s2 & MASK32 | ||
| 353 | want = ref_permlane(x16, init_vals, old_vals, s1_u, s2_u, ALL32) | ||
| 354 | with self.subTest(idx=idx, x16=x16, form=form, s1=hex(s1_u), s2=hex(s2_u)): | ||
| 355 | self.assertEqual(results[idx], want) | ||
| 356 | |||
| 357 | # Spot-check half-staying vs half-swapping explicitly: | ||
| 358 | self.assertEqual(results[0], init_vals) | ||
| 359 | self.assertEqual(results[1], init_vals[16:32] + init_vals[0:16]) | ||
| 360 | |||
| 361 | def test_all_16_nibble_broadcasts_for_both_ops(self): | ||
| 362 | init_vals = [0x9000 + l * 17 for l in range(32)] | ||
| 363 | old_vals = [OLD_SENTINEL | l for l in range(32)] | ||
| 364 | specs = [] | ||
| 365 | for nib in range(16): | ||
| 366 | sel = 0x11111111 * nib | ||
| 367 | specs.append((False, sel, sel, "same_sgpr", "")) | ||
| 368 | specs.append((True, sel, sel, "same_sgpr", "")) | ||
| 369 | # Batch 16 specs at a time to stay well within VGPR file (v2..v17). | ||
| 370 | for base in (0, 16): | ||
| 371 | chunk = specs[base:base + 16] | ||
| 372 | results = self._run_batch(chunk, init_vals, old_vals) | ||
| 373 | for idx, (x16, s1, s2, _, _) in enumerate(chunk): | ||
| 374 | want = ref_permlane(x16, init_vals, old_vals, s1, s2, ALL32) | ||
| 375 | with self.subTest(x16=x16, nib=s1 & 0xF): | ||
| 376 | self.assertEqual(results[idx], want) | ||
| 377 | |||
| 378 | def test_butterfly_32lane_sum_reduction(self): | ||
| 379 | # Real compiler idiom: xor 1, 2, 4, 8 via v_permlane16_b32 then xor 16 via v_permlanex16_b32. | ||
| 380 | init_vals = [3 * l + 5 for l in range(32)] | ||
| 381 | expected_sum = sum(init_vals) | ||
| 382 | got = run_cs("cs_w32_permlane_butterfly", [ | ||
| 383 | "v_lshlrev_b32_e32 v20, 2, v0", | ||
| 384 | f"v_add_nc_u32_e32 v20, {INPUT_BASE:#x}, v20", | ||
| 385 | "buffer_load_dword v1, v20, s[0:3], 0 offen", | ||
| 386 | # xor 1: s1=0x67452301, s2=0xefcdab89 | ||
| 387 | "s_mov_b32 s5, 0xefcdab89", | ||
| 388 | "v_permlane16_b32 v2, v1, 0x67452301, s5", | ||
| 389 | "v_add_nc_u32_e32 v1, v1, v2", | ||
| 390 | # xor 2: s1=0x54761032, s2=0xdcfe98ba | ||
| 391 | "s_mov_b32 s5, 0xdcfe98ba", | ||
| 392 | "v_permlane16_b32 v2, v1, 0x54761032, s5", | ||
| 393 | "v_add_nc_u32_e32 v1, v1, v2", | ||
| 394 | # xor 4: s1=0x32107654, s2=0xba98fedc | ||
| 395 | "s_mov_b32 s5, 0xba98fedc", | ||
| 396 | "v_permlane16_b32 v2, v1, 0x32107654, s5", | ||
| 397 | "v_add_nc_u32_e32 v1, v1, v2", | ||
| 398 | # xor 8: s1=0xfedcba98, s2=0x76543210 | ||
| 399 | "s_mov_b32 s5, 0x76543210", | ||
| 400 | "v_permlane16_b32 v2, v1, 0xfedcba98, s5", | ||
| 401 | "v_add_nc_u32_e32 v1, v1, v2", | ||
| 402 | # xor 16: identity nibbles via v_permlanex16_b32 | ||
| 403 | "s_mov_b32 s4, 0x76543210", | ||
| 404 | "s_mov_b32 s5, 0xfedcba98", | ||
| 405 | "v_permlanex16_b32 v2, v1, s4, s5", | ||
| 406 | "v_add_nc_u32_e32 v1, v1, v2", | ||
| 407 | "v_lshlrev_b32_e32 v21, 2, v0", | ||
| 408 | "buffer_store_dword v1, v21, s[0:3], 0 offen", | ||
| 409 | ], 32, 32, init_inputs=init_vals) | ||
| 410 | self.assertEqual(got, [expected_sum] * 32) | ||
| 411 | |||
| 412 | def test_exec_destination_masking_and_all_op_sel_with_active_sources(self): | ||
| 413 | # Active lanes in each 16-lane half are {0, 2, 4, 6, 8, 9, 10, 11}; | ||
| 414 | # selectors ONLY read from active lanes {0, 2, 4, 6, 8, 9, 10, 11}, so all 4 op_sel modes match ISA. | ||
| 415 | exec_mask = 0x0F550F55 | ||
| 416 | s1_sel = 0x64206420 # nibbles in {0, 2, 4, 6} (all active) | ||
| 417 | s2_sel = 0xBA98BA98 # nibbles in {8, 9, 10, 11} (all active) | ||
| 418 | init_vals = [0x100 + l for l in range(32)] | ||
| 419 | old_vals = [OLD_SENTINEL | l for l in range(32)] | ||
| 420 | specs = [] | ||
| 421 | for x16 in (False, True): | ||
| 422 | for mods in ("", " op_sel:[0,0]", " op_sel:[1,0]", " op_sel:[0,1]", " op_sel:[1,1]"): | ||
| 423 | specs.append((x16, s1_sel, s2_sel, "sgpr", mods)) | ||
| 424 | results = self._run_batch(specs, init_vals, old_vals, exec_mask=exec_mask) | ||
| 425 | for idx, (x16, s1, s2, _, mods) in enumerate(specs): | ||
| 426 | want = ref_permlane(x16, init_vals, old_vals, s1, s2, exec_mask) | ||
| 427 | with self.subTest(x16=x16, mods=mods or "default"): | ||
| 428 | self.assertEqual(results[idx], want) | ||
| 429 | |||
| 430 | def test_op_sel_fi1_reads_inactive_source_lanes(self): | ||
| 431 | # Lanes 0, 16 are OFF in EXEC; active lanes modify v1 to 9999 AFTER pre-filling v1, | ||
| 432 | # then v_permlane16_b32 / v_permlanex16_b32 with op_sel:[1,0] and op_sel:[1,1] broadcast | ||
| 433 | # local lane 0 (inactive lane 0 / inactive lane 16!). Active lanes must see the inactive | ||
| 434 | # lanes' pre-existing values (2000 and 2016), while inactive lanes 0 and 16 keep OLD. | ||
| 435 | exec_mask = ALL32 ^ ((1 << 0) | (1 << 16)) | ||
| 436 | init_vals = [2000 + l for l in range(32)] | ||
| 437 | old_vals = [OLD_SENTINEL | l for l in range(32)] | ||
| 438 | updated_vals = [init_vals[l] if not ((exec_mask >> l) & 1) else 9999 for l in range(32)] | ||
| 439 | |||
| 440 | lines = [ | ||
| 441 | "v_lshlrev_b32_e32 v20, 2, v0", | ||
| 442 | f"v_add_nc_u32_e32 v20, {INPUT_BASE:#x}, v20", | ||
| 443 | "buffer_load_dword v1, v20, s[0:3], 0 offen", | ||
| 444 | f"v_or_b32_e32 v2, {OLD_SENTINEL:#x}, v0", | ||
| 445 | f"v_or_b32_e32 v3, {OLD_SENTINEL:#x}, v0", | ||
| 446 | f"v_or_b32_e32 v4, {OLD_SENTINEL:#x}, v0", | ||
| 447 | f"v_or_b32_e32 v5, {OLD_SENTINEL:#x}, v0", | ||
| 448 | *exec_mask_lines(exec_mask, 32), | ||
| 449 | "v_mov_b32_e32 v1, 9999", # inactive lanes 0 & 16 keep 2000 & 2016 | ||
| 450 | "v_permlane16_b32 v2, v1, 0, 0 op_sel:[1,0]", | ||
| 451 | "v_permlane16_b32 v3, v1, 0, 0 op_sel:[1,1]", | ||
| 452 | "v_permlanex16_b32 v4, v1, 0, 0 op_sel:[1,0]", | ||
| 453 | "v_permlanex16_b32 v5, v1, 0, 0 op_sel:[1,1]", | ||
| 454 | *restore_exec_lines(32), | ||
| 455 | *store_slots_lines(["v2", "v3", "v4", "v5"], 32), | ||
| 456 | ] | ||
| 457 | flat = run_cs("cs_w32_permlane_fi1", lines, 32, 32, init_inputs=init_vals, out_slots=4) | ||
| 458 | for slot, x16 in enumerate((False, False, True, True)): | ||
| 459 | got = flat[slot * 32:(slot + 1) * 32] | ||
| 460 | want = ref_permlane(x16, updated_vals, old_vals, 0, 0, exec_mask, fi=1, bound_ctrl=slot & 1) | ||
| 461 | self.assertEqual(got, want) | ||
| 462 | self.assertEqual(flat[0], OLD_SENTINEL | 0) | ||
| 463 | self.assertEqual(flat[1], 2000) | ||
| 464 | self.assertEqual(flat[16], OLD_SENTINEL | 16) | ||
| 465 | self.assertEqual(flat[17], 2016) | ||
| 466 | # Slot 2 (permlanex16 op_sel:[1,0]): active lanes 1..15 read inactive lane 16 (2016). | ||
| 467 | self.assertEqual(flat[2 * 32 + 1], 2016) | ||
| 468 | self.assertEqual(flat[2 * 32 + 17], 2000) | ||
| 469 | |||
| 470 | def test_destination_aliasing_v1_and_v0(self): | ||
| 471 | init_vals = [300 + l for l in range(32)] | ||
| 472 | # 1. Alias v1, v1 (with EXEC mask & fi=1 reading inactive lane 0 before overwrite) | ||
| 473 | exec_mask = ALL32 ^ (1 << 0) | ||
| 474 | got_v1 = run_cs("cs_w32_permlane_alias_v1", [ | ||
| 475 | "v_lshlrev_b32_e32 v20, 2, v0", | ||
| 476 | f"v_add_nc_u32_e32 v20, {INPUT_BASE:#x}, v20", | ||
| 477 | "buffer_load_dword v1, v20, s[0:3], 0 offen", | ||
| 478 | "v_mov_b32_e32 v2, v1", | ||
| 479 | *exec_mask_lines(exec_mask, 32), | ||
| 480 | "s_mov_b32 s4, 0x00000000", | ||
| 481 | "s_mov_b32 s5, 0x00000000", | ||
| 482 | "v_permlane16_b32 v1, v1, s4, s5 op_sel:[1,0]", | ||
| 483 | "v_permlanex16_b32 v2, v2, 0x76543210, 0xfedcba98 op_sel:[1,0]", | ||
| 484 | *restore_exec_lines(32), | ||
| 485 | *store_slots_lines(["v1", "v2"], 32), | ||
| 486 | ], 32, 32, init_inputs=init_vals, out_slots=2) | ||
| 487 | self.assertEqual(got_v1[:32], ref_permlane(False, init_vals, init_vals, 0, 0, exec_mask, fi=1)) | ||
| 488 | self.assertEqual(got_v1[32:], ref_permlane(True, init_vals, init_vals, ID_S1, ID_S2, exec_mask, fi=1)) | ||
| 489 | |||
| 490 | # 2. Alias v0, v0 directly (save output byte offset 4 * v0 in v21 first) | ||
| 491 | got_v0_16 = run_cs("cs_w32_permlane16_alias_v0", [ | ||
| 492 | "v_lshlrev_b32_e32 v21, 2, v0", | ||
| 493 | f"s_mov_b32 s4, {REV16_S1:#x}", | ||
| 494 | f"s_mov_b32 s5, {REV16_S2:#x}", | ||
| 495 | "v_permlane16_b32 v0, v0, s4, s5", | ||
| 496 | "buffer_store_dword v0, v21, s[0:3], 0 offen", | ||
| 497 | ], 32, 32) | ||
| 498 | self.assertEqual(got_v0_16, ref_permlane(False, list(range(32)), list(range(32)), REV16_S1, REV16_S2, ALL32)) | ||
| 499 | |||
| 500 | got_v0_x16 = run_cs("cs_w32_permlanex16_alias_v0", [ | ||
| 501 | "v_lshlrev_b32_e32 v21, 2, v0", | ||
| 502 | f"s_mov_b32 s4, {REV16_S1:#x}", | ||
| 503 | f"s_mov_b32 s5, {REV16_S2:#x}", | ||
| 504 | "v_permlanex16_b32 v0, v0, s4, s5", | ||
| 505 | "buffer_store_dword v0, v21, s[0:3], 0 offen", | ||
| 506 | ], 32, 32) | ||
| 507 | self.assertEqual(got_v0_x16, ref_permlane(True, list(range(32)), list(range(32)), REV16_S1, REV16_S2, ALL32)) | ||
| 508 | |||
| 509 | def test_partial_wave_20_lanes_avoids_missing_lanes(self): | ||
| 510 | # 20 threads on a 32-wide subgroup: lanes 20..31 do not exist. | ||
| 511 | # 1. All 20 existing lanes active (0xFFFFF): selectors in {0..3} read existing active lanes 0..3 / 16..19. | ||
| 512 | exec_20 = 0xFFFFF | ||
| 513 | got_all20 = run_cs("cs_w32_partial20_all", [ | ||
| 514 | "v_add_nc_u32_e32 v1, 700, v0", | ||
| 515 | f"v_or_b32_e32 v2, {OLD_SENTINEL:#x}, v0", | ||
| 516 | f"v_or_b32_e32 v3, {OLD_SENTINEL:#x}, v0", | ||
| 517 | *exec_mask_lines(exec_20, 32), | ||
| 518 | "v_permlane16_b32 v2, v1, 0x32103210, 0x01230123", | ||
| 519 | "v_permlanex16_b32 v3, v1, 0x32103210, 0x01230123", | ||
| 520 | *restore_exec_lines(32), | ||
| 521 | *store_slots_lines(["v2", "v3"], 20), | ||
| 522 | ], 20, 32, out_slots=2) | ||
| 523 | vals_padded = [700 + l for l in range(20)] + [0] * 12 | ||
| 524 | old_padded = [OLD_SENTINEL | l for l in range(20)] + [0] * 12 | ||
| 525 | self.assertEqual(got_all20[:20], ref_permlane(False, vals_padded, old_padded, 0x32103210, 0x01230123, exec_20)[:20]) | ||
| 526 | self.assertEqual(got_all20[20:40], ref_permlane(True, vals_padded, old_padded, 0x32103210, 0x01230123, exec_20)[:20]) | ||
| 527 | |||
| 528 | # 2. EXEC = 0xFFFF (lanes 16..19 inactive): permlane16 reads [0..15] and preserves OLD on 16..19; | ||
| 529 | # permlanex16 op_sel:[1,0] (fi=1) reads inactive lanes 16..19 while inactive lanes 16..19 discard UNDEF | ||
| 530 | # shuffles from missing lanes 20..31 and keep OLD. | ||
| 531 | exec_16 = 0xFFFF | ||
| 532 | got_masked = run_cs("cs_w32_partial20_masked", [ | ||
| 533 | "v_add_nc_u32_e32 v1, 700, v0", | ||
| 534 | f"v_or_b32_e32 v2, {OLD_SENTINEL:#x}, v0", | ||
| 535 | f"v_or_b32_e32 v3, {OLD_SENTINEL:#x}, v0", | ||
| 536 | *exec_mask_lines(exec_16, 32), | ||
| 537 | "v_permlane16_b32 v2, v1, 0x01234567, 0x89abcdef", | ||
| 538 | "v_permlanex16_b32 v3, v1, 0x32103210, 0x01230123 op_sel:[1,0]", | ||
| 539 | *restore_exec_lines(32), | ||
| 540 | *store_slots_lines(["v2", "v3"], 20), | ||
| 541 | ], 20, 32, out_slots=2) | ||
| 542 | self.assertEqual(got_masked[:20], ref_permlane(False, vals_padded, old_padded, REV8_S1, REV8_S2, exec_16)[:20]) | ||
| 543 | self.assertEqual(got_masked[20:40], ref_permlane(True, vals_padded, old_padded, 0x32103210, 0x01230123, exec_16, fi=1)[:20]) | ||
| 544 | |||
| 545 | |||
| 546 | class Wave64ExecutionTests(unittest.TestCase): | ||
| 547 | """End-to-end 64-lane execution across one 64-wide subgroup AND two 32-wide subgroups.""" | ||
| 548 | |||
| 549 | def test_wave64_halves_selectors_exec_and_fi1_on_subgroup_64_and_32(self): | ||
| 550 | init_vals = [0x4000 + l * 31 for l in range(64)] | ||
| 551 | old_vals = [OLD_SENTINEL | l for l in range(64)] | ||
| 552 | # Asymmetric 64-bit EXEC: active lanes in each 16-lane quarter are {0, 2, 4, 6, 8, 9, 10, 11}. | ||
| 553 | exec_active_only = 0x0F550F550F550F55 | ||
| 554 | # Inactive source lane 0 and lane 32 (one in each 32-lane row) for fi=1 test. | ||
| 555 | exec_no_0_32 = ALL64 ^ ((1 << 0) | (1 << 32)) | ||
| 556 | updated_fi1 = [init_vals[l] if not ((exec_no_0_32 >> l) & 1) else (8800 + l) for l in range(64)] | ||
| 557 | |||
| 558 | lines = [ | ||
| 559 | "s_mov_b64 exec, -1", | ||
| 560 | "v_lshlrev_b32_e32 v20, 2, v0", | ||
| 561 | f"v_add_nc_u32_e32 v20, {INPUT_BASE:#x}, v20", | ||
| 562 | "buffer_load_dword v1, v20, s[0:3], 0 offen", | ||
| 563 | "v_mov_b32_e32 v10, v1", | ||
| 564 | # Slot 0: v_permlane16_b32 identity (stays in [0..15], [16..31], [32..47], [48..63]) | ||
| 565 | f"s_mov_b32 s4, {ID_S1:#x}", | ||
| 566 | f"s_mov_b32 s5, {ID_S2:#x}", | ||
| 567 | "v_permlane16_b32 v2, v1, s4, s5", | ||
| 568 | # Slot 1: v_permlanex16_b32 identity (swaps [0..15]<->[16..31] and [32..47]<->[48..63]) | ||
| 569 | "v_permlanex16_b32 v3, v1, s4, s5", | ||
| 570 | # Slot 2: v_permlane16_b32 asymmetric non-bijective selectors | ||
| 571 | f"s_mov_b32 s6, {ASYM_S1:#x}", | ||
| 572 | f"s_mov_b32 s7, {ASYM_S2:#x}", | ||
| 573 | "v_permlane16_b32 v4, v1, s6, s7", | ||
| 574 | # Slot 3: v_permlanex16_b32_e64 full 16-lane reversal | ||
| 575 | f"s_mov_b32 s8, {REV16_S2:#x}", | ||
| 576 | f"v_permlanex16_b32_e64 v5, v1, {REV16_S1:#x}, s8", | ||
| 577 | # Slot 4: 64-bit EXEC destination masking with active sources (v6 pre-loaded with OLD) | ||
| 578 | f"v_or_b32_e32 v6, {OLD_SENTINEL:#x}, v0", | ||
| 579 | "s_mov_b32 s9, 0xba98ba98", | ||
| 580 | *exec_mask_lines(exec_active_only, 64), | ||
| 581 | "v_permlanex16_b32 v6, v1, 0x64206420, s9", | ||
| 582 | *restore_exec_lines(64), | ||
| 583 | # Slot 5: fi=1 reading inactive source lane 0 (in low 32) and lane 32 (in high 32) | ||
| 584 | f"v_or_b32_e32 v7, {OLD_SENTINEL:#x}, v0", | ||
| 585 | *exec_mask_lines(exec_no_0_32, 64), | ||
| 586 | "v_add_nc_u32_e32 v10, 8800, v0", | ||
| 587 | "v_permlane16_b32 v7, v10, 0, 0 op_sel:[1,0]", | ||
| 588 | # Slot 6: fi=1 permlanex16 reading inactive lane 32 from lanes 48..63 & lane 0 from 16..31 | ||
| 589 | *restore_exec_lines(64), | ||
| 590 | f"v_or_b32_e32 v8, {OLD_SENTINEL:#x}, v0", | ||
| 591 | *exec_mask_lines(exec_no_0_32, 64), | ||
| 592 | "v_permlanex16_b32 v8, v10, 0, 0 op_sel:[1,1]", | ||
| 593 | *restore_exec_lines(64), | ||
| 594 | *store_slots_lines(["v2", "v3", "v4", "v5", "v6", "v7", "v8"], 64), | ||
| 595 | ] | ||
| 596 | |||
| 597 | expected_slots = [ | ||
| 598 | ref_permlane(False, init_vals, old_vals, ID_S1, ID_S2, ALL64), | ||
| 599 | ref_permlane(True, init_vals, old_vals, ID_S1, ID_S2, ALL64), | ||
| 600 | ref_permlane(False, init_vals, old_vals, ASYM_S1, ASYM_S2, ALL64), | ||
| 601 | ref_permlane(True, init_vals, old_vals, REV16_S1, REV16_S2, ALL64), | ||
| 602 | ref_permlane(True, init_vals, old_vals, 0x64206420, 0xBA98BA98, exec_active_only), | ||
| 603 | ref_permlane(False, updated_fi1, old_vals, 0, 0, exec_no_0_32, fi=1, bound_ctrl=0), | ||
| 604 | ref_permlane(True, updated_fi1, old_vals, 0, 0, exec_no_0_32, fi=1, bound_ctrl=1), | ||
| 605 | ] | ||
| 606 | |||
| 607 | for subgroup_size in (64, 32): | ||
| 608 | with self.subTest(subgroup_size=subgroup_size): | ||
| 609 | flat = run_cs(f"cs_w64_permlane_sg{subgroup_size}", lines, 64, subgroup_size, | ||
| 610 | init_inputs=init_vals, out_slots=7) | ||
| 611 | for slot, want in enumerate(expected_slots): | ||
| 612 | got = flat[slot * 64:(slot + 1) * 64] | ||
| 613 | self.assertEqual(got, want, f"subgroup={subgroup_size}, slot={slot}") | ||
| 614 | |||
| 615 | def test_wave64_destination_aliasing_v0_and_v1(self): | ||
| 616 | for subgroup_size in (64, 32): | ||
| 617 | with self.subTest(subgroup_size=subgroup_size): | ||
| 618 | got = run_cs(f"cs_w64_permlane_alias_sg{subgroup_size}", [ | ||
| 619 | "s_mov_b64 exec, -1", | ||
| 620 | "v_lshlrev_b32_e32 v21, 2, v0", | ||
| 621 | "v_add_nc_u32_e32 v1, 500, v0", | ||
| 622 | f"s_mov_b32 s4, {PAIR_SWAP_S1:#x}", | ||
| 623 | f"s_mov_b32 s5, {PAIR_SWAP_S2:#x}", | ||
| 624 | "v_permlane16_b32 v1, v1, s4, s5", | ||
| 625 | "v_permlanex16_b32 v0, v0, s4, s5", | ||
| 626 | "buffer_store_dword v1, v21, s[0:3], 0 offen", | ||
| 627 | f"buffer_store_dword v0, v21, s[0:3], 0 offen offset:{4 * 64}", | ||
| 628 | ], 64, subgroup_size, out_slots=2) | ||
| 629 | self.assertEqual( | ||
| 630 | got[:64], | ||
| 631 | ref_permlane(False, [500 + l for l in range(64)], [0] * 64, PAIR_SWAP_S1, PAIR_SWAP_S2, ALL64), | ||
| 632 | ) | ||
| 633 | self.assertEqual( | ||
| 634 | got[64:], | ||
| 635 | ref_permlane(True, list(range(64)), list(range(64)), PAIR_SWAP_S1, PAIR_SWAP_S2, ALL64), | ||
| 636 | ) | ||
| 637 | |||
| 638 | def test_wave64_partial_wave_40_lanes(self): | ||
| 639 | # 40 threads in a 64-wide subgroup: lanes 32..39 exist in quarter [32..47]; lanes 40..63 do not. | ||
| 640 | # Active lanes 0..31 run v_permlanex16_b32 across [0..15] <-> [16..31], and lanes 32..39 run | ||
| 641 | # v_permlane16_b32 within [32..39]; inactive lanes 32..39 on permlanex16 discard UNDEF from [48..63]. | ||
| 642 | exec_low32 = 0x00000000FFFFFFFF | ||
| 643 | got = run_cs("cs_w64_partial40_permlane", [ | ||
| 644 | "s_mov_b64 exec, -1", | ||
| 645 | "v_add_nc_u32_e32 v1, 200, v0", | ||
| 646 | f"v_or_b32_e32 v2, {OLD_SENTINEL:#x}, v0", | ||
| 647 | f"v_or_b32_e32 v3, {OLD_SENTINEL:#x}, v0", | ||
| 648 | "v_permlane16_b32 v2, v1, 0x32107654, 0x32107654", | ||
| 649 | *exec_mask_lines(exec_low32, 64), | ||
| 650 | "v_permlanex16_b32 v3, v1, 0x01234567, 0x89abcdef", | ||
| 651 | *restore_exec_lines(64), | ||
| 652 | *store_slots_lines(["v2", "v3"], 40), | ||
| 653 | ], 40, 64, out_slots=2) | ||
| 654 | vals64 = [200 + l for l in range(40)] + [0] * 24 | ||
| 655 | old64 = [OLD_SENTINEL | l for l in range(40)] + [0] * 24 | ||
| 656 | self.assertEqual(got[:40], ref_permlane(False, vals64, old64, 0x32107654, 0x32107654, ALL64)[:40]) | ||
| 657 | self.assertEqual(got[40:], ref_permlane(True, vals64, old64, REV8_S1, REV8_S2, exec_low32)[:40]) | ||
| 658 | |||
| 659 | |||
| 660 | class EmulationAndFindingTests(unittest.TestCase): | ||
| 661 | """Translation / structural SPIR-V checks for --wave64-emulate and documented op_sel finding.""" | ||
| 662 | |||
| 663 | def test_wave64_emulate_lowers_permlane_through_x_buf_without_subgroup_ops(self): | ||
| 664 | base = [ | ||
| 665 | "s_mov_b64 exec, -1", | ||
| 666 | "v_add_nc_u32_e32 v1, 100, v0", | ||
| 667 | f"s_mov_b32 s4, {ID_S1:#x}", | ||
| 668 | f"s_mov_b32 s5, {ID_S2:#x}", | ||
| 669 | ] | ||
| 670 | tail = [ | ||
| 671 | "v_lshlrev_b32_e32 v21, 2, v0", | ||
| 672 | "buffer_store_dword v2, v21, s[0:3], 0 offen", | ||
| 673 | ] | ||
| 674 | spv_16, gen_16 = translate_cs("cs_w64_emu_perm16", base + ["v_permlane16_b32 v2, v1, s4, s5"] + tail, | ||
| 675 | 64, emulate=True) | ||
| 676 | spv_x16, gen_x16 = translate_cs("cs_w64_emu_permx16", base + ["v_permlanex16_b32 v2, v1, s4, s5"] + tail, | ||
| 677 | 64, emulate=True) | ||
| 678 | for spv, gen in ((spv_16, gen_16), (spv_x16, gen_x16)): | ||
| 679 | self.assertTrue(gen.wave64 and gen.emulate) | ||
| 680 | self.assertNotIn("OpGroupNonUniform", spv) | ||
| 681 | self.assertNotIn("%sg_lane", spv) | ||
| 682 | self.assertIn("%x_buf = OpVariable", spv) | ||
| 683 | self.assertGreaterEqual(spv.count("OpControlBarrier"), 2) | ||
| 684 | # Nibble extraction (width = 4) and 16-lane half mask (0xFFFFFFF0) | ||
| 685 | self.assertRegex(spv, r"OpBitFieldUExtract %uint %\w+ %\w+ %c4\b") | ||
| 686 | self.assertIn("OpBitwiseAnd %uint %", spv) | ||
| 687 | self.assertIn("%cfffffff0", spv) | ||
| 688 | # spirv_mini_interp.py deliberately rejects the emulated Workgroup/loop scheduler. | ||
| 689 | with self.assertRaises(si.UnsupportedConstruct): | ||
| 690 | si.run_workgroup( | ||
| 691 | spv, 64, 32, | ||
| 692 | inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i % 32}, | ||
| 693 | push_constants=VSHARP + [0] * 28, memory={}, | ||
| 694 | ) | ||
| 695 | |||
| 696 | # v_permlanex16_b32 XORs the masked half base with 16 (%c10); v_permlane16_b32 does not. | ||
| 697 | xor16_pat = r"OpBitwiseAnd %uint %\w+ %cfffffff0\n\s*%\w+ = OpBitwiseXor %uint %\w+ %c10\b" | ||
| 698 | self.assertIsNone(re.search(xor16_pat, spv_16)) | ||
| 699 | self.assertIsNotNone(re.search(xor16_pat, spv_x16)) | ||
| 700 | |||
| 701 | # Wave32 shaders are unaffected by WAVE64_EMULATE=True. | ||
| 702 | w32_lines = ["v_permlanex16_b32 v2, v0, 0x76543210, 0xfedcba98", | ||
| 703 | "v_lshlrev_b32_e32 v21, 2, v0", "buffer_store_dword v2, v21, s[0:3], 0 offen"] | ||
| 704 | spv_w32_plain, _ = translate_cs("cs_w32_emu_nop", w32_lines, 32, emulate=False) | ||
| 705 | spv_w32_emu, gen_w32_emu = translate_cs("cs_w32_emu_nop", w32_lines, 32, emulate=True) | ||
| 706 | self.assertFalse(gen_w32_emu.wave64 or gen_w32_emu.emulate) | ||
| 707 | self.assertEqual(spv_w32_plain, spv_w32_emu) | ||
| 708 | |||
| 709 | def test_op_sel_fi0_translates_cleanly_while_inactive_src_handling_is_excluded(self): | ||
| 710 | # Documented finding (tools/rdna2spirv.py lines 4608-4632): op_sel:[0,0] and op_sel:[0,1] | ||
| 711 | # are accepted by shader_ir/rdna2spirv without raising Unsupported, and lower to | ||
| 712 | # OpGroupNonUniformShuffle without inspecting mods or source %active; inactive-source fi=0 | ||
| 713 | # value assertions stay excluded from Wave32ExecutionTests / Wave64ExecutionTests. | ||
| 714 | for op in ("v_permlane16_b32", "v_permlanex16_b32"): | ||
| 715 | for opsel in ("op_sel:[0,0]", "op_sel:[0,1]"): | ||
| 716 | with self.subTest(op=op, opsel=opsel): | ||
| 717 | spv, gen = translate_cs("cs_w32_opsel_fi0", [ | ||
| 718 | "v_mov_b32_e32 v1, v0", | ||
| 719 | "s_mov_b32 exec_lo, 0xfffffffe", | ||
| 720 | f"{op} v2, v1, 0, 0 {opsel}", | ||
| 721 | "s_mov_b32 exec_lo, -1", | ||
| 722 | "v_lshlrev_b32_e32 v21, 2, v0", | ||
| 723 | "buffer_store_dword v2, v21, s[0:3], 0 offen", | ||
| 724 | ], 32) | ||
| 725 | self.assertFalse(gen.wave64) | ||
| 726 | self.assertIn("OpGroupNonUniformShuffle %uint %c3", spv) | ||
| 727 | self.assertRegex(spv, r"OpBitFieldUExtract %uint %\w+ %\w+ %c4\b") | ||
| 728 | |||
| 729 | |||
| 730 | class NegativeControls(unittest.TestCase): | ||
| 731 | """Sabotage the translated SPIR-V like a translator regression; multi-lane execution must detect it.""" | ||
| 732 | |||
| 733 | def _run(self, spv: str, threads: int, subgroup_size: int) -> list[int]: | ||
| 734 | mem = _Heap() | ||
| 735 | si.run_workgroup( | ||
| 736 | spv, threads, subgroup_size, | ||
| 737 | inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i % subgroup_size}, | ||
| 738 | push_constants=VSHARP + [0] * 28, | ||
| 739 | memory=mem, | ||
| 740 | ) | ||
| 741 | return [mem.get(4 * k) for k in range(threads)] | ||
| 742 | |||
| 743 | def test_sabotage_permlanex16_xor16_dropped(self): | ||
| 744 | spv, _ = translate_cs("cs_w64_neg_x16", [ | ||
| 745 | "s_mov_b64 exec, -1", | ||
| 746 | "v_add_nc_u32_e32 v1, 100, v0", | ||
| 747 | f"v_permlanex16_b32 v2, v1, {ID_S1:#x}, {ID_S2:#x}", | ||
| 748 | "v_lshlrev_b32_e32 v21, 2, v0", | ||
| 749 | "buffer_store_dword v2, v21, s[0:3], 0 offen", | ||
| 750 | ], 64) | ||
| 751 | want = ref_permlane(True, [100 + l for l in range(64)], [0] * 64, ID_S1, ID_S2, ALL64) | ||
| 752 | self.assertEqual(self._run(spv, 64, 64), want) | ||
| 753 | |||
| 754 | bad, n = re.subn(r"(%\w+) = OpBitwiseXor %uint (%\w+) %c10\b", r"\1 = OpCopyObject %uint \2", spv) | ||
| 755 | self.assertEqual(n, 1) | ||
| 756 | got_bad = self._run(bad, 64, 64) | ||
| 757 | self.assertNotEqual(got_bad, want) | ||
| 758 | self.assertEqual(got_bad, [100 + l for l in range(64)]) # collapsed to permlane16 | ||
| 759 | |||
| 760 | def test_sabotage_half_base_dropped_or_shuffle_removed(self): | ||
| 761 | spv, _ = translate_cs("cs_w32_neg_perm16", [ | ||
| 762 | "v_add_nc_u32_e32 v1, 200, v0", | ||
| 763 | f"v_or_b32_e32 v2, {OLD_SENTINEL:#x}, v0", | ||
| 764 | f"s_mov_b32 exec_lo, {0x0F550F55:#x}", | ||
| 765 | "s_mov_b32 s4, 0x64206420", | ||
| 766 | "s_mov_b32 s5, 0xba98ba98", | ||
| 767 | "v_permlane16_b32 v2, v1, s4, s5", | ||
| 768 | "s_mov_b32 exec_lo, -1", | ||
| 769 | "v_lshlrev_b32_e32 v21, 2, v0", | ||
| 770 | "buffer_store_dword v2, v21, s[0:3], 0 offen", | ||
| 771 | ], 32) | ||
| 772 | want = ref_permlane(False, [200 + l for l in range(32)], [OLD_SENTINEL | l for l in range(32)], | ||
| 773 | 0x64206420, 0xBA98BA98, 0x0F550F55) | ||
| 774 | self.assertEqual(self._run(spv, 32, 32), want) | ||
| 775 | |||
| 776 | # 1. Dropping the 0xFFFFFFF0 half-base mask sends lanes 16..31 into [0..15]. | ||
| 777 | bad_half, n1 = re.subn(r"OpBitwiseAnd %uint (%\w+) %cfffffff0\b", r"OpBitwiseAnd %uint \1 %c0", spv) | ||
| 778 | self.assertEqual(n1, 1) | ||
| 779 | self.assertNotEqual(self._run(bad_half, 32, 32), want) | ||
| 780 | |||
| 781 | # 2. Swapping the hi8 OpSelect arms swaps s1 (lanes 0..7) and s2 (lanes 8..15). | ||
| 782 | bad_sel, n2 = re.subn( | ||
| 783 | r"(%\w+ = OpUGreaterThanEqual %bool %\w+ %c8\n(?:.*\n){0,5}?\s*%\w+ = OpSelect %uint %\w+ )(%\w+) (%\w+)", | ||
| 784 | r"\1\3 \2", | ||
| 785 | spv, | ||
| 786 | ) | ||
| 787 | self.assertEqual(n2, 1) | ||
| 788 | self.assertNotEqual(self._run(bad_sel, 32, 32), want) | ||
| 789 | |||
| 790 | # 3. Replacing OpGroupNonUniformShuffle with OpCopyObject turns permute into own-lane copy. | ||
| 791 | bad_shuf, n3 = re.subn( | ||
| 792 | r"(%\w+) = OpGroupNonUniformShuffle %uint %c3 (%\w+) %\w+", | ||
| 793 | r"\1 = OpCopyObject %uint \2", | ||
| 794 | spv, | ||
| 795 | ) | ||
| 796 | self.assertEqual(n3, 1) | ||
| 797 | self.assertNotEqual(self._run(bad_shuf, 32, 32), want) | ||
| 798 | |||
| 799 | # 4. Dropping the destination EXEC OpSelect overwrites inactive destination lanes. | ||
| 800 | bad_exec, n4 = re.subn( | ||
| 801 | r"(%\w+ = OpGroupNonUniformShuffle %uint %c3 %\w+ %\w+\n(?:.*\n){0,4}?\s*" | ||
| 802 | r"%\w+ = OpLoad %bool %active\n\s*" | ||
| 803 | r"(%\w+) = OpSelect %uint %\w+ (%\w+)) %\w+", | ||
| 804 | r"\1 \3", | ||
| 805 | spv, | ||
| 806 | ) | ||
| 807 | self.assertEqual(n4, 1) | ||
| 808 | got_bad_exec = self._run(bad_exec, 32, 32) | ||
| 809 | self.assertNotEqual(got_bad_exec, want) | ||
| 810 | self.assertNotEqual(got_bad_exec[1], OLD_SENTINEL | 1) | ||
| 811 | |||
| 812 | |||
| 813 | if __name__ == "__main__": | ||
| 814 | unittest.main() | ||
diff --git a/tests/semantic/test_valu_rcp_fdiv.py b/tests/semantic/test_valu_rcp_fdiv.py new file mode 100644 index 000000000..e7f649ae0 --- /dev/null +++ b/tests/semantic/test_valu_rcp_fdiv.py | |||
| @@ -0,0 +1,824 @@ | |||
| 1 | """Semantic value tests for OpFDiv in spirv_mini_interp and RDNA2 reciprocal VALU ops: | ||
| 2 | - OpFDiv (scalar %float and vector %v2float) directly in tests/semantic/spirv_mini_interp.py | ||
| 3 | - v_rcp_f32: D.f32 = 1.0 / S0.f32 | ||
| 4 | - v_rcp_iflag_f32: D.f32 = 1.0 / S0.f32 (no FP flags) | ||
| 5 | - v_rcp_f16: D.f16 = 1.0 / S0.f16 (preserves the untouched 16-bit half of D) | ||
| 6 | |||
| 7 | Per the SPIR-V specification and tests/semantic/README.md, OpFDiv by zero (+-0.0) is undefined and raises | ||
| 8 | spirv_mini_interp.UnsupportedConstruct("OpFDiv by zero (undefined in SPIR-V)"). Accordingly, finite non-zero, | ||
| 9 | subnormal, +-inf, and NaN operands are value-checked against independent Fraction-based binary32/binary16 | ||
| 10 | oracles, while +-0.0 divisors/inputs are verified to raise UnsupportedConstruct. | ||
| 11 | |||
| 12 | NaN payloads are not pinned because values passing through Python floats lose exact NaN payload bits; NaN | ||
| 13 | results are asserted as binary32/binary16 NaNs. Standard library only; hand-written RDNA2 listings only. | ||
| 14 | """ | ||
| 15 | from fractions import Fraction | ||
| 16 | import gc | ||
| 17 | import itertools | ||
| 18 | import math | ||
| 19 | import os | ||
| 20 | import re | ||
| 21 | import struct | ||
| 22 | import sys | ||
| 23 | import tempfile | ||
| 24 | import unittest | ||
| 25 | import warnings | ||
| 26 | |||
| 27 | HERE = os.path.dirname(os.path.abspath(__file__)) | ||
| 28 | ROOT = os.path.dirname(os.path.dirname(HERE)) | ||
| 29 | TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") | ||
| 30 | |||
| 31 | sys.dont_write_bytecode = True | ||
| 32 | if TOOLS_DIR not in sys.path: | ||
| 33 | sys.path.insert(0, TOOLS_DIR) | ||
| 34 | if HERE not in sys.path: | ||
| 35 | sys.path.insert(0, HERE) | ||
| 36 | |||
| 37 | import rdna2spirv # noqa: E402 | ||
| 38 | import spirv_mini_interp as si # noqa: E402 | ||
| 39 | |||
| 40 | MASK32 = 0xFFFFFFFF | ||
| 41 | STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("<I", 0) + bytes(4) | ||
| 42 | VSHARP = [0, 0, 0xFFFFFFFF, 0x31016FAC] | ||
| 43 | OLD = 0xBEEF1234 | ||
| 44 | |||
| 45 | # Representative binary16 encodings. | ||
| 46 | H_POS_ZERO = 0x0000 | ||
| 47 | H_NEG_ZERO = 0x8000 | ||
| 48 | H_SUB_MIN = 0x0001 # 2^-24 | ||
| 49 | H_NEG_SUB_MIN = 0x8001 # -2^-24 | ||
| 50 | H_SUB_2M16 = 0x0100 # 2^-16 (1/x = 65536 >= 65520 -> +inf) | ||
| 51 | H_SUB_2M15 = 0x0200 # 2^-15 (1/x = 32768 = 0x7800) | ||
| 52 | H_SUB_MAX = 0x03FF # 1023 * 2^-24 | ||
| 53 | H_NORM_MIN = 0x0400 # 2^-14 (1/x = 16384 = 0x7400) | ||
| 54 | H_0P25 = 0x3400 # 0.25 | ||
| 55 | H_NEG_0P25 = 0xB400 # -0.25 | ||
| 56 | H_0P5 = 0x3800 # 0.5 | ||
| 57 | H_NEG_0P5 = 0xB800 # -0.5 | ||
| 58 | H_0P75 = 0x3A00 # 0.75 | ||
| 59 | H_1P0 = 0x3C00 # 1.0 | ||
| 60 | H_NEG_1P0 = 0xBC00 # -1.0 | ||
| 61 | H_NEG_1P25 = 0xBD00 # -1.25 | ||
| 62 | H_1P5 = 0x3E00 # 1.5 | ||
| 63 | H_2P0 = 0x4000 # 2.0 | ||
| 64 | H_NEG_2P0 = 0xC000 # -2.0 | ||
| 65 | H_3P0 = 0x4200 # 3.0 | ||
| 66 | H_NEG_3P0 = 0xC200 # -3.0 | ||
| 67 | H_4P0 = 0x4400 # 4.0 | ||
| 68 | H_NEG_4P0 = 0xC400 # -4.0 | ||
| 69 | H_8P0 = 0x4800 # 8.0 | ||
| 70 | H_16P0 = 0x4C00 # 16.0 | ||
| 71 | H_1024 = 0x6400 # 1024.0 | ||
| 72 | H_MAX = 0x7BFF # 65504.0 | ||
| 73 | H_NEG_MAX = 0xFBFF # -65504.0 | ||
| 74 | H_POS_INF = 0x7C00 # +inf | ||
| 75 | H_NEG_INF = 0xFC00 # -inf | ||
| 76 | H_QNAN = 0x7E01 # +qNaN | ||
| 77 | H_NEG_QNAN = 0xFE01 # -qNaN | ||
| 78 | H_SNAN = 0x7C01 # +sNaN | ||
| 79 | |||
| 80 | |||
| 81 | def f32_bits(x: float) -> int: | ||
| 82 | try: | ||
| 83 | return struct.unpack("<I", struct.pack("<f", x))[0] | ||
| 84 | except OverflowError: | ||
| 85 | return 0x7F800000 if x > 0 else 0xFF800000 | ||
| 86 | |||
| 87 | |||
| 88 | def is_f32_nan_bits(bits: int) -> bool: | ||
| 89 | return (bits & 0x7F800000) == 0x7F800000 and (bits & 0x007FFFFF) != 0 | ||
| 90 | |||
| 91 | |||
| 92 | def is_f16_nan(half: int) -> bool: | ||
| 93 | return (half & 0x7FFF) > 0x7C00 | ||
| 94 | |||
| 95 | |||
| 96 | def merge_half(old: int, half: int, dst_hi: int) -> int: | ||
| 97 | h = half & 0xFFFF | ||
| 98 | return ((h << 16) | (old & 0xFFFF)) if dst_hi else ((old & 0xFFFF0000) | h) | ||
| 99 | |||
| 100 | |||
| 101 | # ----------------------------------------------------------------------------- | ||
| 102 | # Independent Exact-Rational Binary32 / Binary16 Reference Oracles | ||
| 103 | # ----------------------------------------------------------------------------- | ||
| 104 | |||
| 105 | def _rne_int(q: Fraction) -> int: | ||
| 106 | n = q.numerator // q.denominator | ||
| 107 | rem = q - n | ||
| 108 | if rem > Fraction(1, 2) or (rem == Fraction(1, 2) and (n & 1)): | ||
| 109 | n += 1 | ||
| 110 | return n | ||
| 111 | |||
| 112 | |||
| 113 | def f32_to_fraction(bits: int) -> Fraction: | ||
| 114 | bits &= MASK32 | ||
| 115 | sign = -1 if (bits >> 31) else 1 | ||
| 116 | exp = (bits >> 23) & 0xFF | ||
| 117 | man = bits & 0x7FFFFF | ||
| 118 | if exp == 0xFF: | ||
| 119 | raise ValueError(f"non-finite f32 bits {bits:#010x}") | ||
| 120 | if exp == 0: | ||
| 121 | return sign * Fraction(man, 1 << 23) * Fraction(2) ** -126 | ||
| 122 | return sign * Fraction((1 << 23) | man, 1 << 23) * Fraction(2) ** (exp - 127) | ||
| 123 | |||
| 124 | |||
| 125 | def round_fraction_to_f32(val: Fraction, neg_zero: bool = False) -> int: | ||
| 126 | if val == 0: | ||
| 127 | return 0x80000000 if neg_zero else 0x00000000 | ||
| 128 | sign = 0x80000000 if val < 0 else 0 | ||
| 129 | a = abs(val) | ||
| 130 | e = a.numerator.bit_length() - a.denominator.bit_length() | ||
| 131 | if Fraction(2) ** e > a: | ||
| 132 | e -= 1 | ||
| 133 | if e < -126: | ||
| 134 | n = _rne_int(a / Fraction(2) ** -149) | ||
| 135 | if n == 0: | ||
| 136 | return sign | ||
| 137 | if n < (1 << 23): | ||
| 138 | return sign | n | ||
| 139 | return sign | (1 << 23) | ||
| 140 | n = _rne_int(a / Fraction(2) ** (e - 23)) | ||
| 141 | if n == (1 << 24): | ||
| 142 | n >>= 1 | ||
| 143 | e += 1 | ||
| 144 | if e > 127: | ||
| 145 | return sign | 0x7F800000 | ||
| 146 | return sign | ((e + 127) << 23) | (n & 0x7FFFFF) | ||
| 147 | |||
| 148 | |||
| 149 | def f16_to_fraction(half: int) -> Fraction: | ||
| 150 | half &= 0xFFFF | ||
| 151 | sign = -1 if (half >> 15) else 1 | ||
| 152 | exp = (half >> 10) & 0x1F | ||
| 153 | man = half & 0x3FF | ||
| 154 | if exp == 0x1F: | ||
| 155 | raise ValueError(f"non-finite f16 bits {half:#06x}") | ||
| 156 | if exp == 0: | ||
| 157 | return sign * Fraction(man, 1 << 10) * Fraction(2) ** -14 | ||
| 158 | return sign * Fraction((1 << 10) | man, 1 << 10) * Fraction(2) ** (exp - 15) | ||
| 159 | |||
| 160 | |||
| 161 | def round_fraction_to_f16(val: Fraction, neg_zero: bool = False) -> int: | ||
| 162 | if val == 0: | ||
| 163 | return 0x8000 if neg_zero else 0x0000 | ||
| 164 | sign = 0x8000 if val < 0 else 0 | ||
| 165 | a = abs(val) | ||
| 166 | e = a.numerator.bit_length() - a.denominator.bit_length() | ||
| 167 | if Fraction(2) ** e > a: | ||
| 168 | e -= 1 | ||
| 169 | if e < -14: | ||
| 170 | n = _rne_int(a / Fraction(2) ** -24) | ||
| 171 | return sign | n | ||
| 172 | n = _rne_int(a / Fraction(2) ** (e - 10)) | ||
| 173 | if n == (1 << 11): | ||
| 174 | n >>= 1 | ||
| 175 | e += 1 | ||
| 176 | if e > 15: | ||
| 177 | return sign | 0x7C00 | ||
| 178 | return sign | ((e + 15) << 10) | (n & 0x3FF) | ||
| 179 | |||
| 180 | |||
| 181 | def ref_rcp_f32(x_bits: int, *, scale: Fraction = Fraction(1), clamp: bool = False) -> int: | ||
| 182 | """Reference oracle for non-zero f32 reciprocal (with optional output scale/clamp).""" | ||
| 183 | bits = x_bits & MASK32 | ||
| 184 | sign = bits & 0x80000000 | ||
| 185 | absu = bits & 0x7FFFFFFF | ||
| 186 | if absu == 0: | ||
| 187 | raise ValueError("division by zero is undefined in SPIR-V") | ||
| 188 | if absu > 0x7F800000: | ||
| 189 | if clamp: | ||
| 190 | raise ValueError("clamp of NaN is undefined in GLSL.std.450") | ||
| 191 | return 0x7FC00000 | ||
| 192 | if absu == 0x7F800000: | ||
| 193 | # 1 / (+-inf) = +-0.0; omod preserves sign of zero, clamp orders -0 below +0 -> +0. | ||
| 194 | return 0 if clamp else sign | ||
| 195 | # Match OpFDiv(1, x) rounded to binary32 before clamp_mods (scale, then FClamp [0, 1]). | ||
| 196 | r_bits = round_fraction_to_f32(Fraction(1) / f32_to_fraction(bits)) | ||
| 197 | if (r_bits & 0x7FFFFFFF) == 0x7F800000: | ||
| 198 | r_sign = r_bits & 0x80000000 | ||
| 199 | if clamp: | ||
| 200 | return 0 if r_sign else 0x3F800000 | ||
| 201 | return r_bits | ||
| 202 | val = f32_to_fraction(r_bits) * scale | ||
| 203 | if clamp: | ||
| 204 | if val <= 0: | ||
| 205 | return 0x00000000 | ||
| 206 | if val >= 1: | ||
| 207 | return 0x3F800000 | ||
| 208 | return round_fraction_to_f32(val) | ||
| 209 | |||
| 210 | |||
| 211 | def ref_rcp_f16(h_bits: int, *, scale: Fraction = Fraction(1), clamp: bool = False) -> int: | ||
| 212 | """Reference oracle for non-zero f16 reciprocal (f32 OpFDiv + clamp_mods + f16_bits).""" | ||
| 213 | h = h_bits & 0xFFFF | ||
| 214 | sign = (h & 0x8000) << 16 | ||
| 215 | absh = h & 0x7FFF | ||
| 216 | if absh == 0: | ||
| 217 | raise ValueError("division by zero is undefined in SPIR-V") | ||
| 218 | if absh > 0x7C00: | ||
| 219 | if clamp: | ||
| 220 | raise ValueError("clamp of NaN is undefined in GLSL.std.450") | ||
| 221 | return (h & 0x8000) | 0x7E00 | ||
| 222 | if absh == 0x7C00: | ||
| 223 | return 0 if clamp else (h & 0x8000) | ||
| 224 | # Widening f16 -> f32 is exact, then f32 OpFDiv + omod/clamp, then f16 nearest-even narrowing. | ||
| 225 | r_bits = round_fraction_to_f32(Fraction(1) / f16_to_fraction(h)) | ||
| 226 | r_sign = r_bits & 0x80000000 | ||
| 227 | if (r_bits & 0x7FFFFFFF) == 0x7F800000: | ||
| 228 | if clamp: | ||
| 229 | return 0 if r_sign else 0x3C00 | ||
| 230 | return (r_sign >> 16) | 0x7C00 | ||
| 231 | val = f32_to_fraction(r_bits) * scale | ||
| 232 | if clamp: | ||
| 233 | if val <= 0: | ||
| 234 | return 0x0000 | ||
| 235 | if val >= 1: | ||
| 236 | return 0x3C00 | ||
| 237 | r_f32 = round_fraction_to_f32(val, neg_zero=bool(sign)) | ||
| 238 | return round_fraction_to_f16(f32_to_fraction(r_f32), neg_zero=bool(r_f32 & 0x80000000)) | ||
| 239 | |||
| 240 | |||
| 241 | RCP_F32_HAND_WORKED = ( | ||
| 242 | ("pos_one", 0x3F800000, 0x3F800000), | ||
| 243 | ("neg_one", 0xBF800000, 0xBF800000), | ||
| 244 | ("pos_two", 0x40000000, 0x3F000000), | ||
| 245 | ("neg_two", 0xC0000000, 0xBF000000), | ||
| 246 | ("pos_four", 0x40800000, 0x3E800000), | ||
| 247 | ("neg_quarter", 0xBE800000, 0xC0800000), | ||
| 248 | ("pos_2p20", 0x49800000, 0x35800000), | ||
| 249 | ("neg_2pm20", 0xB5800000, 0xC9800000), | ||
| 250 | ("pos_1p5", 0x3FC00000, 0x3F2AAAAB), | ||
| 251 | ("neg_3p0", 0xC0400000, 0xBEAAAAAB), | ||
| 252 | ("pos_0p3", 0x3E99999A, 0x40555555), | ||
| 253 | ("subnorm_2m128_to_inf", 0x00200000, 0x7F800000), | ||
| 254 | ("neg_subnorm_min_to_ninf", 0x80000001, 0xFF800000), | ||
| 255 | ("2p127_to_subnorm", 0x7F000000, 0x00400000), | ||
| 256 | ("pos_inf", 0x7F800000, 0x00000000), | ||
| 257 | ("neg_inf", 0xFF800000, 0x80000000), | ||
| 258 | ) | ||
| 259 | |||
| 260 | RCP_F16_HAND_WORKED = ( | ||
| 261 | ("pos_one", H_1P0, H_1P0), | ||
| 262 | ("neg_one", H_NEG_1P0, H_NEG_1P0), | ||
| 263 | ("pos_two", H_2P0, H_0P5), | ||
| 264 | ("neg_two", H_NEG_2P0, H_NEG_0P5), | ||
| 265 | ("pos_four", H_4P0, H_0P25), | ||
| 266 | ("neg_quarter", H_NEG_0P25, H_NEG_4P0), | ||
| 267 | ("pos_1p5", H_1P5, 0x3955), | ||
| 268 | ("pos_3p0", H_3P0, 0x3555), | ||
| 269 | ("neg_3p0", H_NEG_3P0, 0xB555), | ||
| 270 | ("sub_min_overflow", H_SUB_MIN, H_POS_INF), | ||
| 271 | ("neg_sub_min_overflow", H_NEG_SUB_MIN, H_NEG_INF), | ||
| 272 | ("sub_2m16_overflow", H_SUB_2M16, H_POS_INF), | ||
| 273 | ("sub_2m15", H_SUB_2M15, 0x7800), | ||
| 274 | ("sub_max", H_SUB_MAX, 0x7401), | ||
| 275 | ("norm_min", H_NORM_MIN, 0x7400), | ||
| 276 | ("f16_max", H_MAX, 0x0100), | ||
| 277 | ("neg_f16_max", H_NEG_MAX, 0x8100), | ||
| 278 | ("pos_inf", H_POS_INF, H_POS_ZERO), | ||
| 279 | ("neg_inf", H_NEG_INF, H_NEG_ZERO), | ||
| 280 | ) | ||
| 281 | |||
| 282 | |||
| 283 | # ----------------------------------------------------------------------------- | ||
| 284 | # Translation & Execution Helpers | ||
| 285 | # ----------------------------------------------------------------------------- | ||
| 286 | |||
| 287 | _TMP_DIR = None | ||
| 288 | _PS_PATH = None | ||
| 289 | _CS_PATH = None | ||
| 290 | _CS_FSSM = None | ||
| 291 | |||
| 292 | |||
| 293 | def _make_fssm(rsrc2: int, group: tuple[int, int, int]) -> bytes: | ||
| 294 | header = bytearray(0x148) | ||
| 295 | struct.pack_into("<4I", header, 0x138, rsrc2, *group) | ||
| 296 | return bytes(header) | ||
| 297 | |||
| 298 | |||
| 299 | def setUpModule(): | ||
| 300 | global _TMP_DIR, _PS_PATH, _CS_PATH, _CS_FSSM | ||
| 301 | _TMP_DIR = tempfile.TemporaryDirectory() | ||
| 302 | disasm_dir = os.path.join(_TMP_DIR.name, "disasm") | ||
| 303 | fssm_dir = os.path.join(_TMP_DIR.name, "fssm") | ||
| 304 | os.mkdir(disasm_dir) | ||
| 305 | os.mkdir(fssm_dir) | ||
| 306 | _PS_PATH = os.path.join(disasm_dir, "ps_valu_rcp_fdiv.s") | ||
| 307 | _CS_PATH = os.path.join(disasm_dir, "cs_valu_rcp_fdiv.s") | ||
| 308 | _CS_FSSM = os.path.join(fssm_dir, "cs_valu_rcp_fdiv.fssm") | ||
| 309 | with open(os.path.join(_TMP_DIR.name, "ps_valu_rcp_fdiv.dxbc"), "wb") as f: | ||
| 310 | f.write(STUB_DXBC) | ||
| 311 | |||
| 312 | |||
| 313 | def tearDownModule(): | ||
| 314 | global _TMP_DIR, _PS_PATH, _CS_PATH, _CS_FSSM | ||
| 315 | if _TMP_DIR is not None: | ||
| 316 | gc.collect() | ||
| 317 | _TMP_DIR.cleanup() | ||
| 318 | _TMP_DIR = None | ||
| 319 | _PS_PATH = None | ||
| 320 | _CS_PATH = None | ||
| 321 | _CS_FSSM = None | ||
| 322 | |||
| 323 | |||
| 324 | def translate_ps(lines: list[str]) -> str: | ||
| 325 | if _TMP_DIR is None: | ||
| 326 | setUpModule() | ||
| 327 | asm = ( | ||
| 328 | "; test_valu_rcp_fdiv\n" | ||
| 329 | + "".join(f"\t{ln}\n" for ln in lines) | ||
| 330 | + "\texp mrt0 v0, v0, v0, v0 done vm\n" | ||
| 331 | + "\ts_endpgm\n" | ||
| 332 | ) | ||
| 333 | with open(_PS_PATH, "w", encoding="utf-8", newline="") as f: | ||
| 334 | f.write(asm) | ||
| 335 | with warnings.catch_warnings(): | ||
| 336 | warnings.simplefilter("ignore", ResourceWarning) | ||
| 337 | spv = rdna2spirv.translate(_PS_PATH) | ||
| 338 | gc.collect() | ||
| 339 | return spv | ||
| 340 | |||
| 341 | |||
| 342 | def run_ps_v0(lines: list[str]) -> int: | ||
| 343 | return si.run_fragment(translate_ps(lines))["%out_mrt0"][0] | ||
| 344 | |||
| 345 | |||
| 346 | def run_op(line: str, v1: int, old: int = OLD, s4: int = 0) -> int: | ||
| 347 | return run_ps_v0([ | ||
| 348 | f"s_mov_b32 s4, {s4:#x}", | ||
| 349 | f"v_mov_b32 v1, {v1:#x}", | ||
| 350 | f"v_mov_b32 v0, {old:#x}", | ||
| 351 | line, | ||
| 352 | ]) | ||
| 353 | |||
| 354 | |||
| 355 | def run_cs(lines: list[str], group_size: int, subgroup_size: int, memory: dict[int, int]) -> dict[int, int]: | ||
| 356 | if _TMP_DIR is None: | ||
| 357 | setUpModule() | ||
| 358 | with open(_CS_FSSM, "wb") as f: | ||
| 359 | f.write(_make_fssm(0x0088, (group_size, 1, 1))) | ||
| 360 | asm = "; test_cs_valu_rcp_fdiv\n" + "".join(f"\t{ln}\n" for ln in lines) + "\ts_endpgm\n" | ||
| 361 | with open(_CS_PATH, "w", encoding="utf-8", newline="") as f: | ||
| 362 | f.write(asm) | ||
| 363 | with warnings.catch_warnings(): | ||
| 364 | warnings.simplefilter("ignore", ResourceWarning) | ||
| 365 | spv = rdna2spirv.translate(_CS_PATH) | ||
| 366 | gc.collect() | ||
| 367 | return si.run_workgroup( | ||
| 368 | spv, group_size, subgroup_size, | ||
| 369 | inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0)}, | ||
| 370 | push_constants=VSHARP + [0] * 28, | ||
| 371 | memory=memory, | ||
| 372 | ) | ||
| 373 | |||
| 374 | |||
| 375 | # ----------------------------------------------------------------------------- | ||
| 376 | # 1. Reference Oracle Self-Tests | ||
| 377 | # ----------------------------------------------------------------------------- | ||
| 378 | |||
| 379 | class OracleSelfTests(unittest.TestCase): | ||
| 380 | def test_hand_worked_rcp_f32_and_f16_match_fraction_oracles(self): | ||
| 381 | for name, x_bits, want in RCP_F32_HAND_WORKED: | ||
| 382 | with self.subTest(kind="f32", name=name): | ||
| 383 | self.assertEqual(ref_rcp_f32(x_bits), want) | ||
| 384 | for name, h_bits, want in RCP_F16_HAND_WORKED: | ||
| 385 | with self.subTest(kind="f16", name=name): | ||
| 386 | self.assertEqual(ref_rcp_f16(h_bits), want) | ||
| 387 | |||
| 388 | |||
| 389 | # ----------------------------------------------------------------------------- | ||
| 390 | # 2. Direct OpFDiv Unit Tests in spirv_mini_interp.py | ||
| 391 | # ----------------------------------------------------------------------------- | ||
| 392 | |||
| 393 | FDIV_HEADER = """\ | ||
| 394 | OpCapability Shader | ||
| 395 | OpMemoryModel Logical GLSL450 | ||
| 396 | OpEntryPoint Fragment %main "main" %out | ||
| 397 | %void = OpTypeVoid | ||
| 398 | %fn = OpTypeFunction %void | ||
| 399 | %uint = OpTypeInt 32 0 | ||
| 400 | %float = OpTypeFloat 32 | ||
| 401 | %v2float = OpTypeVector %float 2 | ||
| 402 | %_ptr_Output_uint = OpTypePointer Output %uint | ||
| 403 | %out = OpVariable %_ptr_Output_uint Output | ||
| 404 | %_ptr_PC = OpTypePointer PushConstant %uint | ||
| 405 | %pc = OpVariable %_ptr_PC PushConstant | ||
| 406 | %c0 = OpConstant %uint 0 | ||
| 407 | %c1 = OpConstant %uint 1 | ||
| 408 | %c2 = OpConstant %uint 2 | ||
| 409 | %c3 = OpConstant %uint 3 | ||
| 410 | %f0 = OpConstant %float 0 | ||
| 411 | %f0p5 = OpConstant %float 0.5 | ||
| 412 | %f1 = OpConstant %float 1 | ||
| 413 | %f2 = OpConstant %float 2 | ||
| 414 | %f3 = OpConstant %float 3 | ||
| 415 | %f4 = OpConstant %float 4 | ||
| 416 | %f255 = OpConstant %float 255 | ||
| 417 | %u_neg0 = OpConstant %uint 2147483648 | ||
| 418 | %u_inf = OpConstant %uint 2139095040 | ||
| 419 | %u_ninf = OpConstant %uint 4286578688 | ||
| 420 | %u_qnan = OpConstant %uint 2143289344 | ||
| 421 | %u_snan = OpConstant %uint 2139095041 | ||
| 422 | %u_fltmax = OpConstant %uint 2139095039 | ||
| 423 | %u_nfltmax = OpConstant %uint 4286578687 | ||
| 424 | %main = OpFunction %void None %fn | ||
| 425 | %entry = OpLabel | ||
| 426 | %fm0 = OpBitcast %float %u_neg0 | ||
| 427 | %inf = OpBitcast %float %u_inf | ||
| 428 | %ninf = OpBitcast %float %u_ninf | ||
| 429 | %qnan = OpBitcast %float %u_qnan | ||
| 430 | %snan = OpBitcast %float %u_snan | ||
| 431 | %fltmax = OpBitcast %float %u_fltmax | ||
| 432 | %nfltmax = OpBitcast %float %u_nfltmax | ||
| 433 | %fm2 = OpFNegate %float %f2 | ||
| 434 | %fm3 = OpFNegate %float %f3 | ||
| 435 | %fm1 = OpFNegate %float %f1 | ||
| 436 | """ | ||
| 437 | FDIV_FOOTER = "OpReturn\nOpFunctionEnd\n" | ||
| 438 | |||
| 439 | |||
| 440 | def run_fdiv_scalar(num: str, den: str) -> int: | ||
| 441 | text = ( | ||
| 442 | FDIV_HEADER | ||
| 443 | + f"%r = OpFDiv %float {num} {den}\n" | ||
| 444 | + "%res = OpBitcast %uint %r\n" | ||
| 445 | + "OpStore %out %res\n" | ||
| 446 | + FDIV_FOOTER | ||
| 447 | ) | ||
| 448 | return si.run_fragment(text)["%out"][0] | ||
| 449 | |||
| 450 | |||
| 451 | def run_fdiv_vec2(n0: str, n1: str, d0: str, d1: str) -> tuple[int, int]: | ||
| 452 | hdr = FDIV_HEADER.replace( | ||
| 453 | 'OpEntryPoint Fragment %main "main" %out', | ||
| 454 | 'OpEntryPoint Fragment %main "main" %out %out1', | ||
| 455 | ).replace( | ||
| 456 | "%out = OpVariable %_ptr_Output_uint Output", | ||
| 457 | "%out = OpVariable %_ptr_Output_uint Output\n%out1 = OpVariable %_ptr_Output_uint Output", | ||
| 458 | ) | ||
| 459 | body = ( | ||
| 460 | f"%vn = OpCompositeConstruct %v2float {n0} {n1}\n" | ||
| 461 | + f"%vd = OpCompositeConstruct %v2float {d0} {d1}\n" | ||
| 462 | + "%vr = OpFDiv %v2float %vn %vd\n" | ||
| 463 | + "%r0 = OpCompositeExtract %float %vr 0\n" | ||
| 464 | + "%r1 = OpCompositeExtract %float %vr 1\n" | ||
| 465 | + "%b0 = OpBitcast %uint %r0\n" | ||
| 466 | + "%b1 = OpBitcast %uint %r1\n" | ||
| 467 | + "OpStore %out %b0\n" | ||
| 468 | + "OpStore %out1 %b1\n" | ||
| 469 | ) | ||
| 470 | res = si.run_fragment(hdr + body + FDIV_FOOTER) | ||
| 471 | return res["%out"][0], res["%out1"][0] | ||
| 472 | |||
| 473 | |||
| 474 | class OpFDivInterpreterTests(unittest.TestCase): | ||
| 475 | def test_scalar_finite_signed_zero_inf_and_overflow(self): | ||
| 476 | cases = ( | ||
| 477 | ("%f1", "%f4", f32_bits(0.25)), | ||
| 478 | ("%fm3", "%f2", f32_bits(-1.5)), | ||
| 479 | ("%f3", "%f255", 0x3C40C0C1), | ||
| 480 | # Signed zero dividends keep exact IEEE sign rules. | ||
| 481 | ("%f0", "%f2", 0x00000000), | ||
| 482 | ("%f0", "%fm2", 0x80000000), | ||
| 483 | ("%fm0", "%f2", 0x80000000), | ||
| 484 | ("%fm0", "%fm2", 0x00000000), | ||
| 485 | # Division by +-inf -> +-0.0. | ||
| 486 | ("%f1", "%inf", 0x00000000), | ||
| 487 | ("%fm1", "%inf", 0x80000000), | ||
| 488 | ("%f1", "%ninf", 0x80000000), | ||
| 489 | ("%fm1", "%ninf", 0x00000000), | ||
| 490 | ("%f0", "%ninf", 0x80000000), | ||
| 491 | ("%fm0", "%inf", 0x80000000), | ||
| 492 | ("%fm0", "%ninf", 0x00000000), | ||
| 493 | # +-inf divided by finite non-zero -> +-inf. | ||
| 494 | ("%inf", "%f2", 0x7F800000), | ||
| 495 | ("%inf", "%fm2", 0xFF800000), | ||
| 496 | ("%ninf", "%f2", 0xFF800000), | ||
| 497 | ("%ninf", "%fm2", 0x7F800000), | ||
| 498 | # Binary32 overflow -> +-inf. | ||
| 499 | ("%fltmax", "%f0p5", 0x7F800000), | ||
| 500 | ("%nfltmax", "%f0p5", 0xFF800000), | ||
| 501 | ) | ||
| 502 | for num, den, want in cases: | ||
| 503 | with self.subTest(num=num, den=den): | ||
| 504 | self.assertEqual(run_fdiv_scalar(num, den), want) | ||
| 505 | |||
| 506 | def test_scalar_inf_over_inf_and_nan_propagation(self): | ||
| 507 | nan_cases = ( | ||
| 508 | ("%inf", "%inf"), | ||
| 509 | ("%inf", "%ninf"), | ||
| 510 | ("%ninf", "%inf"), | ||
| 511 | ("%ninf", "%ninf"), | ||
| 512 | ("%qnan", "%f2"), | ||
| 513 | ("%f2", "%qnan"), | ||
| 514 | ("%qnan", "%inf"), | ||
| 515 | ("%inf", "%qnan"), | ||
| 516 | ("%f0", "%qnan"), | ||
| 517 | ("%snan", "%f2"), | ||
| 518 | ("%f2", "%snan"), | ||
| 519 | ) | ||
| 520 | for num, den in nan_cases: | ||
| 521 | with self.subTest(num=num, den=den): | ||
| 522 | got = run_fdiv_scalar(num, den) | ||
| 523 | self.assertTrue(is_f32_nan_bits(got), f"expected NaN for {num}/{den}, got {got:#010x}") | ||
| 524 | |||
| 525 | def test_vector_v2float_division(self): | ||
| 526 | self.assertEqual(run_fdiv_vec2("%f1", "%fm3", "%f4", "%fm2"), (f32_bits(0.25), f32_bits(1.5))) | ||
| 527 | self.assertEqual(run_fdiv_vec2("%f1", "%fm0", "%ninf", "%ninf"), (0x80000000, 0x00000000)) | ||
| 528 | g0, g1 = run_fdiv_vec2("%f1", "%inf", "%ninf", "%ninf") | ||
| 529 | self.assertEqual(g0, 0x80000000) | ||
| 530 | self.assertTrue(is_f32_nan_bits(g1), f"expected NaN in lane 1, got {g1:#010x}") | ||
| 531 | |||
| 532 | def test_zero_divisor_and_non_float_are_rejected(self): | ||
| 533 | for num, den in ( | ||
| 534 | ("%f1", "%f0"), | ||
| 535 | ("%f1", "%fm0"), | ||
| 536 | ("%fm1", "%f0"), | ||
| 537 | ("%fm1", "%fm0"), | ||
| 538 | ("%f0", "%f0"), | ||
| 539 | ("%fm0", "%fm0"), | ||
| 540 | ("%inf", "%f0"), | ||
| 541 | ("%qnan", "%f0"), | ||
| 542 | ("%qnan", "%fm0"), | ||
| 543 | ): | ||
| 544 | with self.subTest(num=num, den=den): | ||
| 545 | with self.assertRaises(si.UnsupportedConstruct): | ||
| 546 | run_fdiv_scalar(num, den) | ||
| 547 | |||
| 548 | for n0, n1, d0, d1 in ( | ||
| 549 | ("%f1", "%f2", "%f0", "%f2"), | ||
| 550 | ("%f1", "%f2", "%f2", "%fm0"), | ||
| 551 | ): | ||
| 552 | with self.subTest(vec=(n0, n1, d0, d1)): | ||
| 553 | with self.assertRaises(si.UnsupportedConstruct): | ||
| 554 | run_fdiv_vec2(n0, n1, d0, d1) | ||
| 555 | |||
| 556 | with self.assertRaises(si.UnsupportedConstruct): | ||
| 557 | si.run_fragment( | ||
| 558 | FDIV_HEADER + "%res = OpFDiv %uint %c2 %c1\nOpStore %out %res\n" + FDIV_FOOTER | ||
| 559 | ) | ||
| 560 | |||
| 561 | |||
| 562 | # ----------------------------------------------------------------------------- | ||
| 563 | # 3. End-to-End v_rcp_f32 & v_rcp_iflag_f32 Value Tests | ||
| 564 | # ----------------------------------------------------------------------------- | ||
| 565 | |||
| 566 | class RcpF32AndIflagExecutionTests(unittest.TestCase): | ||
| 567 | OPS = ("v_rcp_f32", "v_rcp_iflag_f32") | ||
| 568 | |||
| 569 | def test_hand_worked_and_edge_values_across_encodings(self): | ||
| 570 | for op in self.OPS: | ||
| 571 | for suffix in ("_e32", "_e64", ""): | ||
| 572 | for name, x_bits, want in RCP_F32_HAND_WORKED: | ||
| 573 | with self.subTest(op=op + suffix, case=name): | ||
| 574 | got = run_op(f"{op}{suffix} v0, v1", x_bits) | ||
| 575 | self.assertEqual(got, want) | ||
| 576 | |||
| 577 | def test_nan_inputs_preserve_nan(self): | ||
| 578 | for op in self.OPS: | ||
| 579 | for suffix in ("_e32", "_e64"): | ||
| 580 | for x_bits in (0x7FC00000, 0xFFC00001, 0x7F800001, 0xFF800001): | ||
| 581 | with self.subTest(op=op + suffix, x=hex(x_bits)): | ||
| 582 | got = run_op(f"{op}{suffix} v0, v1", x_bits) | ||
| 583 | self.assertTrue(is_f32_nan_bits(got), f"expected NaN, got {got:#010x}") | ||
| 584 | |||
| 585 | def test_zero_inputs_raise_unsupported_construct(self): | ||
| 586 | for op in self.OPS: | ||
| 587 | for suffix in ("_e32", "_e64"): | ||
| 588 | for x_bits in (0x00000000, 0x80000000): | ||
| 589 | with self.subTest(op=op + suffix, x=hex(x_bits)): | ||
| 590 | with self.assertRaises(si.UnsupportedConstruct): | ||
| 591 | run_op(f"{op}{suffix} v0, v1", x_bits) | ||
| 592 | with self.subTest(op=op, mod="-|0|"): | ||
| 593 | with self.assertRaises(si.UnsupportedConstruct): | ||
| 594 | run_op(f"{op}_e64 v0, -|0|", 0) | ||
| 595 | |||
| 596 | def test_vop3_output_and_source_modifiers(self): | ||
| 597 | cases = ( | ||
| 598 | # (insn_suffix_and_src, v1_bits, scale, clamp) | ||
| 599 | ("v1 clamp", f32_bits(0.5), Fraction(1), True), | ||
| 600 | ("v1 clamp", f32_bits(-0.5), Fraction(1), True), | ||
| 601 | ("v1 clamp", f32_bits(4.0), Fraction(1), True), | ||
| 602 | ("v1 mul:2", f32_bits(4.0), Fraction(2), False), | ||
| 603 | ("v1 mul:2", f32_bits(-0.5), Fraction(2), False), | ||
| 604 | ("v1 mul:4", f32_bits(4.0), Fraction(4), False), | ||
| 605 | ("v1 mul:4", f32_bits(-2.0), Fraction(4), False), | ||
| 606 | ("v1 div:2", f32_bits(2.0), Fraction(1, 2), False), | ||
| 607 | ("v1 div:2", f32_bits(-0.5), Fraction(1, 2), False), | ||
| 608 | # omod applies before clamp: 1/0.5 * 0.5 = 1.0; 1/4.0 * 2 = 0.5; 1/0.5 * 2 -> clamped 1.0 | ||
| 609 | ("v1 mul:2 clamp", f32_bits(0.5), Fraction(2), True), | ||
| 610 | ("v1 mul:2 clamp", f32_bits(4.0), Fraction(2), True), | ||
| 611 | ("v1 mul:2 clamp", f32_bits(-0.5), Fraction(2), True), | ||
| 612 | ("v1 clamp div:2", f32_bits(0.5), Fraction(1, 2), True), | ||
| 613 | ("v1 clamp div:2", f32_bits(-0.5), Fraction(1, 2), True), | ||
| 614 | ) | ||
| 615 | for op in self.OPS: | ||
| 616 | for args, x_bits, scale, clamp in cases: | ||
| 617 | with self.subTest(op=op, args=args, x=hex(x_bits)): | ||
| 618 | got = run_op(f"{op}_e64 v0, {args}", x_bits) | ||
| 619 | want = ref_rcp_f32(x_bits, scale=scale, clamp=clamp) | ||
| 620 | self.assertEqual(got, want) | ||
| 621 | |||
| 622 | # Source modifiers (-v1, |v1|, -|v1|) alone and combined with output modifiers. | ||
| 623 | src_cases = ( | ||
| 624 | ("-v1", f32_bits(2.0), f32_bits(-0.5)), | ||
| 625 | ("|v1|", f32_bits(-4.0), f32_bits(0.25)), | ||
| 626 | ("-|v1|", f32_bits(-2.0), f32_bits(-0.5)), | ||
| 627 | ("-|v1|", f32_bits(2.0), f32_bits(-0.5)), | ||
| 628 | ("-v1 clamp", f32_bits(-0.5), f32_bits(1.0)), | ||
| 629 | ("|v1| mul:2", f32_bits(-0.5), f32_bits(4.0)), | ||
| 630 | ("-|v1| mul:2 clamp", f32_bits(0.5), f32_bits(0.0)), | ||
| 631 | ("-|v1| div:2", f32_bits(-0.5), f32_bits(-1.0)), | ||
| 632 | ) | ||
| 633 | for op in self.OPS: | ||
| 634 | for args, x_bits, want in src_cases: | ||
| 635 | with self.subTest(op=op, args=args, x=hex(x_bits)): | ||
| 636 | self.assertEqual(run_op(f"{op}_e64 v0, {args}", x_bits), want) | ||
| 637 | |||
| 638 | def test_inline_constants_literals_sgprs_and_aliasing(self): | ||
| 639 | for op in self.OPS: | ||
| 640 | # Inline float constants, VOP3 constant modifiers, and 32-bit literal. | ||
| 641 | self.assertEqual(run_op(f"{op}_e32 v0, 0.5", 0), f32_bits(2.0)) | ||
| 642 | self.assertEqual(run_op(f"{op}_e32 v0, -0.5", 0), f32_bits(-2.0)) | ||
| 643 | self.assertEqual(run_op(f"{op}_e32 v0, 4.0", 0), f32_bits(0.25)) | ||
| 644 | self.assertEqual(run_op(f"{op}_e64 v0, -|2.0|", 0), f32_bits(-0.5)) | ||
| 645 | self.assertEqual(run_op(f"{op}_e64 v0, neg(0x3f800000)", 0), f32_bits(-1.0)) | ||
| 646 | self.assertEqual(run_op(f"{op}_e32 v0, 0x40400000", 0), 0x3EAAAAAB) | ||
| 647 | |||
| 648 | # SGPR source and modified SGPR source. | ||
| 649 | self.assertEqual(run_op(f"{op}_e32 v0, s4", 0, s4=f32_bits(-4.0)), f32_bits(-0.25)) | ||
| 650 | self.assertEqual(run_op(f"{op}_e64 v0, |s4| mul:2", 0, s4=f32_bits(-4.0)), f32_bits(0.5)) | ||
| 651 | |||
| 652 | # In-place aliasing: dst == src. | ||
| 653 | self.assertEqual(run_ps_v0(["v_mov_b32 v0, 0x40000000", f"{op}_e32 v0, v0"]), f32_bits(0.5)) | ||
| 654 | self.assertEqual(run_ps_v0(["v_mov_b32 v0, 0xc0800000", f"{op}_e64 v0, -v0 mul:4"]), f32_bits(1.0)) | ||
| 655 | |||
| 656 | |||
| 657 | # ----------------------------------------------------------------------------- | ||
| 658 | # 4. End-to-End v_rcp_f16 Value Tests | ||
| 659 | # ----------------------------------------------------------------------------- | ||
| 660 | |||
| 661 | class RcpF16ExecutionTests(unittest.TestCase): | ||
| 662 | def test_hand_worked_values_across_e32_e64_and_bare(self): | ||
| 663 | for suffix in ("_e32", "_e64", ""): | ||
| 664 | for name, h_bits, want_half in RCP_F16_HAND_WORKED: | ||
| 665 | with self.subTest(suffix=suffix, case=name): | ||
| 666 | got = run_op(f"v_rcp_f16{suffix} v0, v1", 0xCAFE0000 | h_bits) | ||
| 667 | self.assertEqual(got, merge_half(OLD, want_half, 0)) | ||
| 668 | |||
| 669 | def test_nan_preserves_nan_and_other_half(self): | ||
| 670 | for suffix in ("_e32", "_e64"): | ||
| 671 | for h in (H_QNAN, H_NEG_QNAN, H_SNAN): | ||
| 672 | with self.subTest(suffix=suffix, h=hex(h)): | ||
| 673 | got = run_op(f"v_rcp_f16{suffix} v0, v1", 0xCAFE0000 | h) | ||
| 674 | self.assertEqual(got & 0xFFFF0000, OLD & 0xFFFF0000) | ||
| 675 | self.assertTrue(is_f16_nan(got & 0xFFFF), f"expected NaN in low half, got {got:#010x}") | ||
| 676 | |||
| 677 | def test_zero_inputs_raise_unsupported_construct(self): | ||
| 678 | for line, v1 in ( | ||
| 679 | ("v_rcp_f16_e32 v0, v1", (H_1P0 << 16) | H_POS_ZERO), | ||
| 680 | ("v_rcp_f16_e32 v0, v1", (H_1P0 << 16) | H_NEG_ZERO), | ||
| 681 | ("v_rcp_f16_e64 v0, v1 op_sel:[1,0]", (H_POS_ZERO << 16) | H_1P0), | ||
| 682 | ("v_rcp_f16_e64 v0, v1 op_sel:[1,1]", (H_NEG_ZERO << 16) | H_1P0), | ||
| 683 | ): | ||
| 684 | with self.subTest(line=line, v1=hex(v1)): | ||
| 685 | with self.assertRaises(si.UnsupportedConstruct): | ||
| 686 | run_op(line, v1) | ||
| 687 | |||
| 688 | def test_op_sel_all_combinations(self): | ||
| 689 | # v1 = (hi: -4.0, lo: 0.5) -> rcp(hi) = -0.25, rcp(lo) = 2.0. | ||
| 690 | v1 = (H_NEG_4P0 << 16) | H_0P5 | ||
| 691 | for src_hi, dst_hi in itertools.product((0, 1), repeat=2): | ||
| 692 | h_in = H_NEG_4P0 if src_hi else H_0P5 | ||
| 693 | line = f"v_rcp_f16_e64 v0, v1 op_sel:[{src_hi},{dst_hi}]" | ||
| 694 | with self.subTest(line=line): | ||
| 695 | self.assertEqual(run_op(line, v1), merge_half(OLD, ref_rcp_f16(h_in), dst_hi)) | ||
| 696 | |||
| 697 | def test_vop3_source_and_output_modifiers(self): | ||
| 698 | v1 = (H_NEG_0P5 << 16) | H_4P0 | ||
| 699 | self.assertEqual(run_op("v_rcp_f16_e64 v0, -v1 op_sel:[0,0]", v1), merge_half(OLD, H_NEG_0P25, 0)) | ||
| 700 | self.assertEqual(run_op("v_rcp_f16_e64 v0, |v1| op_sel:[1,1]", v1), merge_half(OLD, H_2P0, 1)) | ||
| 701 | self.assertEqual(run_op("v_rcp_f16_e64 v0, -|v1| op_sel:[1,0]", v1), merge_half(OLD, H_NEG_2P0, 0)) | ||
| 702 | |||
| 703 | # Output modifiers scale first, then clamp to [0.0, 1.0], then pack to f16 keeping the other half. | ||
| 704 | self.assertEqual(run_op("v_rcp_f16_e64 v0, v1 mul:2", v1), merge_half(OLD, H_0P5, 0)) | ||
| 705 | self.assertEqual(run_op("v_rcp_f16_e64 v0, v1 mul:4", v1), merge_half(OLD, H_1P0, 0)) | ||
| 706 | self.assertEqual(run_op("v_rcp_f16_e64 v0, v1 div:2", v1), merge_half(OLD, 0x3000, 0)) # 0.125 | ||
| 707 | self.assertEqual(run_op("v_rcp_f16_e64 v0, v1 op_sel:[1,1] mul:2", v1), merge_half(OLD, H_NEG_4P0, 1)) | ||
| 708 | self.assertEqual(run_op("v_rcp_f16_e64 v0, v1 op_sel:[1,1] clamp", v1), merge_half(OLD, H_POS_ZERO, 1)) | ||
| 709 | self.assertEqual(run_op("v_rcp_f16_e64 v0, |v1| op_sel:[1,0] mul:2 clamp", v1), merge_half(OLD, H_1P0, 0)) | ||
| 710 | self.assertEqual(run_op("v_rcp_f16_e64 v0, |v1| op_sel:[1,1] clamp div:2", v1), merge_half(OLD, H_1P0, 1)) | ||
| 711 | |||
| 712 | def test_inline_constants_sgpr_and_aliasing(self): | ||
| 713 | self.assertEqual(run_op("v_rcp_f16_e32 v0, 0.5", 0), merge_half(OLD, H_2P0, 0)) | ||
| 714 | self.assertEqual(run_op("v_rcp_f16_e32 v0, -0.5", 0), merge_half(OLD, H_NEG_2P0, 0)) | ||
| 715 | self.assertEqual(run_op("v_rcp_f16_e64 v0, -1.0", 0), merge_half(OLD, H_NEG_1P0, 0)) | ||
| 716 | self.assertEqual(run_op("v_rcp_f16_e64 v0, -|0x4000|", 0), merge_half(OLD, H_NEG_0P5, 0)) | ||
| 717 | |||
| 718 | s4 = (H_NEG_4P0 << 16) | H_0P5 | ||
| 719 | self.assertEqual(run_op("v_rcp_f16_e32 v0, s4", 0, s4=s4), merge_half(OLD, H_2P0, 0)) | ||
| 720 | self.assertEqual(run_op("v_rcp_f16_e64 v0, s4 op_sel:[1,1]", 0, s4=s4), merge_half(OLD, H_NEG_0P25, 1)) | ||
| 721 | |||
| 722 | # In-place aliasing: dst == src reading one half and writing the other keeps the original unread half. | ||
| 723 | v0_init = (H_0P5 << 16) | H_4P0 | ||
| 724 | self.assertEqual( | ||
| 725 | run_ps_v0([f"v_mov_b32 v0, {v0_init:#x}", "v_rcp_f16_e64 v0, v0 op_sel:[1,0]"]), | ||
| 726 | (H_0P5 << 16) | H_2P0, | ||
| 727 | ) | ||
| 728 | self.assertEqual( | ||
| 729 | run_ps_v0([f"v_mov_b32 v0, {v0_init:#x}", "v_rcp_f16_e32 v0, v0"]), | ||
| 730 | (H_0P5 << 16) | H_0P25, | ||
| 731 | ) | ||
| 732 | |||
| 733 | |||
| 734 | # ----------------------------------------------------------------------------- | ||
| 735 | # 5. EXEC Masking & Negative Control Tests | ||
| 736 | # ----------------------------------------------------------------------------- | ||
| 737 | |||
| 738 | class RcpExecMaskingTests(unittest.TestCase): | ||
| 739 | def test_single_lane_exec_masking(self): | ||
| 740 | for line in ( | ||
| 741 | "v_rcp_f32_e32 v0, v1", | ||
| 742 | "v_rcp_iflag_f32_e32 v0, v1", | ||
| 743 | "v_rcp_f16_e32 v0, v1", | ||
| 744 | "v_rcp_f16_e64 v0, v1 op_sel:[1,1]", | ||
| 745 | ): | ||
| 746 | with self.subTest(line=line): | ||
| 747 | got = run_ps_v0([ | ||
| 748 | f"v_mov_b32 v1, {(H_2P0 << 16) | H_4P0:#x}", | ||
| 749 | f"v_mov_b32 v0, {OLD:#x}", | ||
| 750 | "s_mov_b32 exec_lo, 0", | ||
| 751 | line, | ||
| 752 | "s_mov_b32 exec_lo, 1", | ||
| 753 | ]) | ||
| 754 | self.assertEqual(got, OLD) | ||
| 755 | |||
| 756 | # Disabled ops leave v0 unchanged; re-enabling EXEC executes the subsequent op. | ||
| 757 | got_toggled = run_ps_v0([ | ||
| 758 | f"v_mov_b32 v1, {(H_0P5 << 16) | H_4P0:#x}", | ||
| 759 | f"v_mov_b32 v0, {OLD:#x}", | ||
| 760 | "s_mov_b32 exec_lo, 0", | ||
| 761 | "v_rcp_f16_e64 v0, v1 op_sel:[0,0]", | ||
| 762 | "v_rcp_f16_e64 v0, v1 op_sel:[1,1]", | ||
| 763 | "s_mov_b32 exec_lo, 1", | ||
| 764 | "v_rcp_f16_e64 v0, v1 op_sel:[1,0]", | ||
| 765 | ]) | ||
| 766 | self.assertEqual(got_toggled, merge_half(OLD, H_2P0, 0)) | ||
| 767 | |||
| 768 | def test_multilane_compute_exec_masking(self): | ||
| 769 | # 4 lanes in wave32: disable odd lanes (lane & 1 != 0) before executing v_rcp_*. | ||
| 770 | # Active even lanes (0, 2) compute the reciprocal; inactive odd lanes (1, 3) keep OLD. | ||
| 771 | cases = ( | ||
| 772 | ("v_rcp_f32_e32 v3, v2", f32_bits(4.0), f32_bits(0.25)), | ||
| 773 | ("v_rcp_iflag_f32_e64 v3, v2 mul:2", f32_bits(4.0), f32_bits(0.5)), | ||
| 774 | ("v_rcp_f16_e64 v3, v2 op_sel:[1,1]", (H_0P5 << 16) | H_4P0, merge_half(OLD, H_2P0, 1)), | ||
| 775 | ) | ||
| 776 | for insn, src_word, active_want in cases: | ||
| 777 | with self.subTest(insn=insn): | ||
| 778 | mem = {} | ||
| 779 | lines = [ | ||
| 780 | "v_lshlrev_b32 v4, 2, v0", # lane byte offset = lane * 4 | ||
| 781 | f"v_mov_b32 v2, {src_word:#x}", | ||
| 782 | f"v_mov_b32 v3, {OLD:#x}", | ||
| 783 | "v_and_b32 v5, v0, 1", | ||
| 784 | "v_cmpx_eq_u32 v5, 0", # keep even lanes active | ||
| 785 | insn, | ||
| 786 | "s_mov_b32 exec_lo, -1", | ||
| 787 | "buffer_store_dword v3, v4, s[0:3], 0 offen", | ||
| 788 | ] | ||
| 789 | run_cs(lines, group_size=4, subgroup_size=32, memory=mem) | ||
| 790 | self.assertEqual( | ||
| 791 | [mem[4 * i] for i in range(4)], | ||
| 792 | [active_want, OLD, active_want, OLD], | ||
| 793 | ) | ||
| 794 | |||
| 795 | |||
| 796 | class NegativeControlTests(unittest.TestCase): | ||
| 797 | def test_sabotaged_spirv_is_detected(self): | ||
| 798 | cases = ( | ||
| 799 | ("v_rcp_f32_e32 v0, v1", f32_bits(4.0), f32_bits(0.25)), | ||
| 800 | ("v_rcp_iflag_f32_e64 v0, v1 mul:2", f32_bits(4.0), f32_bits(0.5)), | ||
| 801 | ("v_rcp_f16_e64 v0, v1 op_sel:[0,1]", (H_1P0 << 16) | H_4P0, merge_half(OLD, H_0P25, 1)), | ||
| 802 | ) | ||
| 803 | for line, v1_bits, want in cases: | ||
| 804 | with self.subTest(line=line): | ||
| 805 | spv = translate_ps([f"v_mov_b32 v0, {OLD:#x}", f"v_mov_b32 v1, {v1_bits:#x}", line]) | ||
| 806 | self.assertEqual(si.run_fragment(spv)["%out_mrt0"][0], want) | ||
| 807 | bad, n = re.subn(r"OpFDiv %float %f1\b", "OpFMul %float %f1", spv, count=1) | ||
| 808 | self.assertEqual(n, 1) | ||
| 809 | self.assertNotEqual(si.run_fragment(bad)["%out_mrt0"][0], want) | ||
| 810 | |||
| 811 | # Sabotaging FClamp on v_rcp_iflag_f32_e64 clamp changes clamped 1/0.5 = 2.0 -> 1.0. | ||
| 812 | spv_clamp = translate_ps([ | ||
| 813 | f"v_mov_b32 v0, {OLD:#x}", | ||
| 814 | f"v_mov_b32 v1, {f32_bits(0.5):#x}", | ||
| 815 | "v_rcp_iflag_f32_e64 v0, v1 clamp", | ||
| 816 | ]) | ||
| 817 | self.assertEqual(si.run_fragment(spv_clamp)["%out_mrt0"][0], f32_bits(1.0)) | ||
| 818 | bad_clamp, n = re.subn(r"OpExtInst %float %glsl FClamp (%\w+) %f0 %f1", r"OpCopyObject %float \1", spv_clamp) | ||
| 819 | self.assertEqual(n, 1) | ||
| 820 | self.assertEqual(si.run_fragment(bad_clamp)["%out_mrt0"][0], f32_bits(2.0)) | ||
| 821 | |||
| 822 | |||
| 823 | if __name__ == "__main__": | ||
| 824 | unittest.main() | ||
diff --git a/tests/test_anim_rigs.py b/tests/test_anim_rigs.py new file mode 100644 index 000000000..7ae94fb61 --- /dev/null +++ b/tests/test_anim_rigs.py | |||
| @@ -0,0 +1,134 @@ | |||
| 1 | """Synthetic tests for tools/anim_rigs.py. | ||
| 2 | |||
| 3 | python -I tests/test_anim_rigs.py | ||
| 4 | |||
| 5 | Every byte here is built by the test: a fake RPF9 data area with two rig dictionaries and one clip dictionary | ||
| 6 | (the builders of tests/test_anim_clips.py), and a small rig-set JSON in the shape `anim_index.py --rigs` writes. | ||
| 7 | No game file or game asset name is used. | ||
| 8 | """ | ||
| 9 | import json | ||
| 10 | import os | ||
| 11 | import struct | ||
| 12 | import subprocess | ||
| 13 | import sys | ||
| 14 | import tempfile | ||
| 15 | import unittest | ||
| 16 | |||
| 17 | ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | ||
| 18 | TOOL = os.path.join(ROOT, "tools", "anim_rigs.py") | ||
| 19 | sys.path.insert(0, os.path.join(ROOT, "tools")) | ||
| 20 | sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) | ||
| 21 | |||
| 22 | import anim_rigs # noqa: E402 | ||
| 23 | from anim_index import joaat32 # noqa: E402 | ||
| 24 | from test_anim_clips import Page, two_sequence_dictionary, write_rpf # noqa: E402 | ||
| 25 | |||
| 26 | KIND_A, KIND_B = joaat32("kind_a"), joaat32("kind_b") | ||
| 27 | |||
| 28 | |||
| 29 | def rig_block(page, tables, version=2): | ||
| 30 | """`RIG` + version, u32 length, 8 filler bytes, then each table {kind, 0xC + 8n, n, word} + n items.""" | ||
| 31 | body = bytearray(b"\x11" * 8) | ||
| 32 | for kind, items in tables: | ||
| 33 | body += struct.pack("<4I", kind, 0xC + 8 * len(items), len(items), 0x0300) | ||
| 34 | body += b"".join(struct.pack("<II", h, 0x0300 + i) for i, h in enumerate(items)) | ||
| 35 | return page.alloc(MAGIC_V(version) + struct.pack("<I", len(body)) + bytes(body)) | ||
| 36 | |||
| 37 | |||
| 38 | def MAGIC_V(version): | ||
| 39 | return b"RIG" + bytes([version]) | ||
| 40 | |||
| 41 | |||
| 42 | def rig_dictionary(name, rigs): | ||
| 43 | """rigs: {rig path: [(kind, [item hashes])]}. The root's own +0x70 holds `RIG` + version like the real ones.""" | ||
| 44 | p = Page() | ||
| 45 | pm = p.alloc(bytes(16)) | ||
| 46 | p.b[pm + 8], p.b[pm + 9] = 1, 0 | ||
| 47 | p.ptr(8, pm) | ||
| 48 | p.string(0x38, name) | ||
| 49 | struct.pack_into("<I", p.b, 0x68, joaat32(name)) | ||
| 50 | p.b[0x70:0x74] = MAGIC_V(2) | ||
| 51 | items = [] | ||
| 52 | for path, tables in rigs.items(): | ||
| 53 | value = p.alloc(bytes(0x90)) | ||
| 54 | p.ptr(value + 0x20, rig_block(p, tables)) | ||
| 55 | items.append((joaat32(path), value)) | ||
| 56 | p.atmap(0x48, items) | ||
| 57 | return bytes(p.b) | ||
| 58 | |||
| 59 | |||
| 60 | RIGS = { | ||
| 61 | "src@one": {"anim/rig/x/a": [(KIND_A, [1, 2, 3])], "anim/rig/x/b": [(KIND_A, [4]), (KIND_B, [5, 6])]}, | ||
| 62 | "src@two": {"anim/rig/y/c": [(KIND_B, [7, 8])], "anim/rig/y/unused": [(KIND_A, [9])]}, | ||
| 63 | } | ||
| 64 | RIGSETS = {"rbf0": {"rigsets": [ | ||
| 65 | {"key": "anim/rigset/ped/p", "entries": [ | ||
| 66 | {"source": "src@one", "rig": "anim/rig/x/a", "group": "pose"}, | ||
| 67 | {"source": "src@one", "rig": "anim/rig/x/b", "group": "deformation"}, | ||
| 68 | {"source": "src@two", "rig": "anim/rig/y/c", "group": "facial"}]}, | ||
| 69 | {"key": "anim/rigset/object/o", "entries": [ | ||
| 70 | {"source": "src@two", "rig": "anim/rig/x/a", "group": "pose"}, # rig is in the other dictionary | ||
| 71 | {"source": "src@none", "rig": "anim/rig/z/q", "group": "pose"}, # no dictionary has this name | ||
| 72 | {"source": "src@one", "rig": "anim/rig/x/missing", "group": "pose"}]}, | ||
| 73 | ]}} | ||
| 74 | |||
| 75 | |||
| 76 | class RigDictionaryTest(unittest.TestCase): | ||
| 77 | def setUp(self): | ||
| 78 | self.tmp = tempfile.TemporaryDirectory() | ||
| 79 | self.rpf = os.path.join(self.tmp.name, "synthetic.rpf") | ||
| 80 | self.rigs = os.path.join(self.tmp.name, "rigs.json") | ||
| 81 | with open(self.rigs, "w", encoding="utf-8") as f: | ||
| 82 | json.dump(RIGSETS, f) | ||
| 83 | streams = [rig_dictionary(name, rigs) for name, rigs in RIGS.items()] + [two_sequence_dictionary()] | ||
| 84 | self.offsets = write_rpf(self.rpf, streams) | ||
| 85 | |||
| 86 | def tearDown(self): | ||
| 87 | self.tmp.cleanup() | ||
| 88 | |||
| 89 | def test_scan_reads_only_rig_dictionaries(self): | ||
| 90 | dicts, summary = anim_rigs.scan(self.rpf) | ||
| 91 | self.assertEqual([d["name"] for d in dicts], ["src@one", "src@two"]) | ||
| 92 | self.assertEqual([d["offset"] for d in dicts], self.offsets[:2]) | ||
| 93 | c = summary["counts"] | ||
| 94 | self.assertEqual((c["rig_dictionaries"], c["rig_dictionary_hash_matches_name"], c["entries"], | ||
| 95 | c["entries_with_block"], c["entries_key_high_zero"], c["block_version:2"]), (2, 2, 4, 4, 4, 4)) | ||
| 96 | self.assertEqual((c["tables"], c[f"table_kind:0x{KIND_A:08x}"], c[f"table_kind:0x{KIND_B:08x}"]), (5, 3, 2)) | ||
| 97 | self.assertEqual((c[f"table_items:0x{KIND_A:08x}"], c[f"table_items:0x{KIND_B:08x}"]), (5, 4)) | ||
| 98 | |||
| 99 | def test_entry_keys_and_tables(self): | ||
| 100 | dicts, _ = anim_rigs.scan(self.rpf) | ||
| 101 | one = {e["key"]: e["tables"] for e in dicts[0]["entries"]} | ||
| 102 | self.assertEqual(one, {joaat32("anim/rig/x/a"): [(KIND_A, 3)], | ||
| 103 | joaat32("anim/rig/x/b"): [(KIND_A, 1), (KIND_B, 2)]}) | ||
| 104 | |||
| 105 | def test_join_rbf0(self): | ||
| 106 | dicts, _ = anim_rigs.scan(self.rpf) | ||
| 107 | self.assertEqual(anim_rigs.join_rbf0(dicts, RIGSETS), { | ||
| 108 | "distinct_rigs": 6, "in_another_dictionary": 1, "key_missing": 1, "keys": 4, | ||
| 109 | "keys_named_by_an_entry": 3, "no_dictionary_named_source": 1, "resolved": 3}) | ||
| 110 | |||
| 111 | def test_bad_block_is_reported_not_raised(self): | ||
| 112 | page = bytearray(rig_dictionary("src@bad", {"anim/rig/b": [(KIND_A, [1])]})) | ||
| 113 | at = page.rfind(b"RIG\x02") | ||
| 114 | page[at:at + 3] = b"XYZ" | ||
| 115 | rpf = os.path.join(self.tmp.name, "bad.rpf") | ||
| 116 | write_rpf(rpf, [bytes(page)]) | ||
| 117 | dicts, summary = anim_rigs.scan(rpf) | ||
| 118 | self.assertEqual(summary["counts"]["rig_dictionaries_unparsed"], 1) | ||
| 119 | self.assertIn("no RIG block", dicts[0]["error"]) | ||
| 120 | |||
| 121 | def test_cli_writes_counts_only(self): | ||
| 122 | out = os.path.join(self.tmp.name, "out.json") | ||
| 123 | r = subprocess.run([sys.executable, "-I", TOOL, self.rpf, out, "--rigs", self.rigs], | ||
| 124 | capture_output=True, text=True) | ||
| 125 | self.assertEqual(r.returncode, 0, r.stderr) | ||
| 126 | with open(out, encoding="utf-8") as f: | ||
| 127 | doc = json.load(f) | ||
| 128 | self.assertEqual(doc["summary"]["rbf0_join"]["resolved"], 3) | ||
| 129 | self.assertEqual([row["entries"] for row in doc["rig_dictionaries"]], [2, 2]) | ||
| 130 | self.assertNotIn("tables", json.dumps(doc["rig_dictionaries"])) | ||
| 131 | |||
| 132 | |||
| 133 | if __name__ == "__main__": | ||
| 134 | unittest.main() | ||
diff --git a/tests/test_awc_names.py b/tests/test_awc_names.py index b73cacc86..766cdd12d 100644 --- a/tests/test_awc_names.py +++ b/tests/test_awc_names.py | |||
| @@ -188,6 +188,21 @@ class TestCli(unittest.TestCase): | |||
| 188 | with open(json_out, encoding="utf-8") as fh: | 188 | with open(json_out, encoding="utf-8") as fh: |
| 189 | self.assertEqual(json.load(fh)["summary"]["banks"]["streams"], 3) | 189 | self.assertEqual(json.load(fh)["summary"]["banks"]["streams"], 3) |
| 190 | 190 | ||
| 191 | def test_rejects_output_aliasing_conversation(self): | ||
| 192 | with tempfile.TemporaryDirectory() as tmp: | ||
| 193 | bank = write(os.path.join(tmp, "one.awc"), make_bank(["zz_rootau_abcd_01"])) | ||
| 194 | original = b"ZZ_ROOTAU_ABCD\x00ZZ_A\x00" | ||
| 195 | conv = write(os.path.join(tmp, "c.pso"), original) | ||
| 196 | alias = os.path.join(tmp, ".", "c.pso") | ||
| 197 | err = io.StringIO() | ||
| 198 | with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(err): | ||
| 199 | with self.assertRaises(SystemExit) as cm: | ||
| 200 | A.main([bank, "--conversations", conv, "--out", alias]) | ||
| 201 | self.assertEqual(cm.exception.code, 2) | ||
| 202 | self.assertIn("--out must not overwrite an input", err.getvalue()) | ||
| 203 | with open(conv, "rb") as f: | ||
| 204 | self.assertEqual(f.read(), original) | ||
| 205 | |||
| 191 | def test_hashdict_json_words(self): | 206 | def test_hashdict_json_words(self): |
| 192 | with tempfile.TemporaryDirectory() as tmp: | 207 | with tempfile.TemporaryDirectory() as tmp: |
| 193 | path = write(os.path.join(tmp, "hashes.json"), json.dumps({"0000abcd": "Some_Word"})) | 208 | path = write(os.path.join(tmp, "hashes.json"), json.dumps({"0000abcd": "Some_Word"})) |
diff --git a/tests/test_awc_opus.py b/tests/test_awc_opus.py index 76b26ff0c..aebdd0fd8 100644 --- a/tests/test_awc_opus.py +++ b/tests/test_awc_opus.py | |||
| @@ -393,8 +393,9 @@ class ExportBankTest(unittest.TestCase): | |||
| 393 | self.assertEqual(last["serial"], 3) | 393 | self.assertEqual(last["serial"], 3) |
| 394 | 394 | ||
| 395 | def test_stereo_plain_stream_length_is_per_channel(self): | 395 | def test_stereo_plain_stream_length_is_per_channel(self): |
| 396 | # A stereo format tag stores interleaved samples. Three 960-frame stereo packets carry | 396 | # A stereo format tag stores interleaved samples: 3840 counts = 1920 frames per channel. |
| 397 | # 2880 frames per channel; the declared 3840 is twice the real per-channel length. | 397 | # Three 960-frame packets carry 2880 frames per channel, so the declared 1920 trims |
| 398 | # 960 frames of payload; the point is the halving, not a realistic stream length. | ||
| 398 | packet = bytes([0x9C]) # CELT 20 ms, code 0, stereo bit: 960 frames per channel | 399 | packet = bytes([0x9C]) # CELT 20 ms, code 0, stereo bit: 960 frames per channel |
| 399 | opus = bytearray(3 * 2048) | 400 | opus = bytearray(3 * 2048) |
| 400 | for block in range(3): | 401 | for block in range(3): |
| @@ -414,8 +415,8 @@ class ExportBankTest(unittest.TestCase): | |||
| 414 | 415 | ||
| 415 | def test_declared_samples_are_48khz_frames_not_scaled_by_rate(self): | 416 | def test_declared_samples_are_48khz_frames_not_scaled_by_rate(self): |
| 416 | # Four 960-frame packets are 3840 frames; the tag declares 2880 real frames and a 32 kHz | 417 | # Four 960-frame packets are 3840 frames; the tag declares 2880 real frames and a 32 kHz |
| 417 | # source rate. Scaling by 48000/32000 would make the length 4320, so the last granule | 418 | # source rate. Scaling by 48000/32000 would make the target 4320, above the payload, so |
| 418 | # would stay at 312 + 3840 and the padding would not be trimmed. | 419 | # the old code kept all 3840 packet frames (granule 3840, 3528 after the pre-skip). |
| 419 | packet = bytes([0x08]) # SILK 20 ms, code 0: 960 frames | 420 | packet = bytes([0x08]) # SILK 20 ms, code 0: 960 frames |
| 420 | opus = bytearray(4 * 2048) | 421 | opus = bytearray(4 * 2048) |
| 421 | for block in range(4): | 422 | for block in range(4): |
| @@ -431,12 +432,13 @@ class ExportBankTest(unittest.TestCase): | |||
| 431 | pages = parse_ogg_pages(f.read()) | 432 | pages = parse_ogg_pages(f.read()) |
| 432 | self.assertEqual(pages[-1]["granule"], 312 + 2880) | 433 | self.assertEqual(pages[-1]["granule"], 312 + 2880) |
| 433 | 434 | ||
| 434 | def test_format_block_per_channel_frame_count_is_used(self): | 435 | def test_inconsistent_format_frame_count_falls_back(self): |
| 435 | # +0x0C is the per-channel Opus frame count and wins over dividing the +0 count: | 436 | # +0x0C is authoritative only when it agrees with the interleaved +0 count: |
| 436 | # 9999 interleaved samples / 2 would be 4999 frames and would not trim the padding. | 437 | # 1920 * 2 != 9999, so the block is malformed and +0 / channels (4999) is used |
| 438 | # instead of silently truncating the real audio. | ||
| 437 | packet = bytes([0x9C]) # CELT 20 ms, code 0, stereo bit: 960 frames per channel | 439 | packet = bytes([0x9C]) # CELT 20 ms, code 0, stereo bit: 960 frames per channel |
| 438 | opus = bytearray(3 * 2048) | 440 | opus = bytearray(6 * 2048) |
| 439 | for block in range(3): | 441 | for block in range(6): |
| 440 | struct.pack_into("<H", opus, block * 2048, len(packet)) | 442 | struct.pack_into("<H", opus, block * 2048, len(packet)) |
| 441 | opus[block * 2048 + 2:block * 2048 + 2 + len(packet)] = packet | 443 | opus[block * 2048 + 2:block * 2048 + 2 + len(packet)] = packet |
| 442 | fmt = bytearray(format_block(9999, 48000, 0x0B, 2)) | 444 | fmt = bytearray(format_block(9999, 48000, 0x0B, 2)) |
| @@ -449,8 +451,69 @@ class ExportBankTest(unittest.TestCase): | |||
| 449 | awc.export_bank(path, self.out) | 451 | awc.export_bank(path, self.out) |
| 450 | with open(os.path.join(self.out, "frames", "0000000B.ogg"), "rb") as f: | 452 | with open(os.path.join(self.out, "frames", "0000000B.ogg"), "rb") as f: |
| 451 | pages = parse_ogg_pages(f.read()) | 453 | pages = parse_ogg_pages(f.read()) |
| 454 | self.assertEqual(pages[-1]["granule"], 312 + 4999) | ||
| 455 | |||
| 456 | def test_consistent_format_frame_count_is_used(self): | ||
| 457 | # 3840 interleaved stereo samples = 1920 per channel, and +0x0C agrees. | ||
| 458 | packet = bytes([0x9C]) # CELT 20 ms, code 0, stereo bit: 960 frames per channel | ||
| 459 | opus = bytearray(3 * 2048) | ||
| 460 | for block in range(3): | ||
| 461 | struct.pack_into("<H", opus, block * 2048, len(packet)) | ||
| 462 | opus[block * 2048 + 2:block * 2048 + 2 + len(packet)] = packet | ||
| 463 | fmt = bytearray(format_block(3840, 48000, 0x0B, 2)) | ||
| 464 | struct.pack_into("<I", fmt, 12, 1920) | ||
| 465 | bank = build_bank([(12, bytes(fmt), bytes(opus))]) | ||
| 466 | path = os.path.join(self.tmp.name, "frames_ok.awc") | ||
| 467 | with open(path, "wb") as f: | ||
| 468 | f.write(bank) | ||
| 469 | |||
| 470 | awc.export_bank(path, self.out) | ||
| 471 | with open(os.path.join(self.out, "frames_ok", "0000000C.ogg"), "rb") as f: | ||
| 472 | pages = parse_ogg_pages(f.read()) | ||
| 452 | self.assertEqual(pages[-1]["granule"], 312 + 1920) | 473 | self.assertEqual(pages[-1]["granule"], 312 + 1920) |
| 453 | 474 | ||
| 475 | def test_eos_page_is_emitted_at_the_trim_point(self): | ||
| 476 | # 27 packets of 160 bytes / 960 frames: the 26th packet crosses the target | ||
| 477 | # (312 + 24000 = 24312) and would otherwise flush a full page first. The EOS | ||
| 478 | # page must carry the reaching packet and drop the 27th padding packet, not | ||
| 479 | # emit a later page whose granule is smaller than the previous one. | ||
| 480 | packet = bytes([0x08]) + bytes(159) # SILK 20 ms, 960 frames | ||
| 481 | packets = [packet] * 27 | ||
| 482 | path = os.path.join(self.tmp.name, "trim.ogg") | ||
| 483 | awc.write_ogg_opus(path, packets, 1, 21, 24000) | ||
| 484 | with open(path, "rb") as f: | ||
| 485 | pages = parse_ogg_pages(f.read()) | ||
| 486 | audio = pages[2:] | ||
| 487 | granules = [p["granule"] for p in audio] | ||
| 488 | self.assertEqual(granules, sorted(granules)) | ||
| 489 | self.assertEqual(audio[-1]["granule"], 312 + 24000) | ||
| 490 | self.assertEqual(audio[-1]["flags"] & 0x04, 0x04) | ||
| 491 | self.assertEqual(sum(1 for p in audio for value in p["lacing"] if value < 255), 26) | ||
| 492 | |||
| 493 | def test_pre_skip_larger_than_the_stream_is_clamped(self): | ||
| 494 | # Six 960-frame packets are 5760 samples; a pre-skip of 65535 would put the | ||
| 495 | # EOS granule below the pre-skip and make the stream undecodable. | ||
| 496 | packet = bytes([0x08]) | ||
| 497 | packets = [packet] * 6 | ||
| 498 | path = os.path.join(self.tmp.name, "preskip.ogg") | ||
| 499 | awc.write_ogg_opus(path, packets, 1, 23, 4800, pre_skip=65535) | ||
| 500 | with open(path, "rb") as f: | ||
| 501 | pages = parse_ogg_pages(f.read()) | ||
| 502 | self.assertEqual(struct.unpack_from("<H", pages[0]["body"], 10)[0], 5760) | ||
| 503 | self.assertGreaterEqual(pages[-1]["granule"], 5760) | ||
| 504 | with self.assertRaises(ValueError): | ||
| 505 | awc.write_ogg_opus(path, packets, 1, 24, 4800, pre_skip=65536) | ||
| 506 | |||
| 507 | def test_empty_packet_list_writes_an_eos_page(self): | ||
| 508 | # No audio packets is still a valid empty stream: the EOS flag must be present. | ||
| 509 | path = os.path.join(self.tmp.name, "empty.ogg") | ||
| 510 | self.assertEqual(awc.write_ogg_opus(path, [], 1, 25, 0), 0) | ||
| 511 | with open(path, "rb") as f: | ||
| 512 | pages = parse_ogg_pages(f.read()) | ||
| 513 | self.assertEqual(len(pages), 3) | ||
| 514 | self.assertEqual(pages[-1]["flags"] & 0x04, 0x04) | ||
| 515 | self.assertEqual(pages[-1]["granule"], 0) | ||
| 516 | |||
| 454 | def test_cli_pre_skip_override(self): | 517 | def test_cli_pre_skip_override(self): |
| 455 | bank, _, _ = self.make_bank() | 518 | bank, _, _ = self.make_bank() |
| 456 | subprocess.run([sys.executable, "-I", awc.__file__, bank, self.out, "--jobs", "1", "--pre-skip", "0"], | 519 | subprocess.run([sys.executable, "-I", awc.__file__, bank, self.out, "--jobs", "1", "--pre-skip", "0"], |
diff --git a/tests/test_bink_names.py b/tests/test_bink_names.py index 1a52eeb54..a78eb28e3 100644 --- a/tests/test_bink_names.py +++ b/tests/test_bink_names.py | |||
| @@ -194,6 +194,18 @@ class TestLoadPins(unittest.TestCase): | |||
| 194 | 194 | ||
| 195 | 195 | ||
| 196 | class TestCli(unittest.TestCase): | 196 | class TestCli(unittest.TestCase): |
| 197 | def test_rejects_negative_max_skip(self): | ||
| 198 | with tempfile.TemporaryDirectory() as tmp: | ||
| 199 | xml = os.path.join(tmp, "list.xml") | ||
| 200 | with open(xml, "w", encoding="utf-8") as f: | ||
| 201 | f.write(mount_xml([])) | ||
| 202 | err = io.StringIO() | ||
| 203 | with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(err): | ||
| 204 | with self.assertRaises(SystemExit) as cm: | ||
| 205 | names_mod.main([tmp, "--mount", xml, "--max-skip", "-1"]) | ||
| 206 | self.assertEqual(cm.exception.code, 2) | ||
| 207 | self.assertIn("--max-skip must be 0 or more", err.getvalue()) | ||
| 208 | |||
| 197 | def test_archive_end_to_end(self): | 209 | def test_archive_end_to_end(self): |
| 198 | shapes = [(1280, 720, 40), (1920, 1080, 50), (512, 512, 15)] | 210 | shapes = [(1280, 720, 40), (1920, 1080, 50), (512, 512, 15)] |
| 199 | with tempfile.TemporaryDirectory() as tmp: | 211 | with tempfile.TemporaryDirectory() as tmp: |
diff --git a/tests/test_build_runtime_fallback.py b/tests/test_build_runtime_fallback.py index 93457d1c7..75d938fdc 100644 --- a/tests/test_build_runtime_fallback.py +++ b/tests/test_build_runtime_fallback.py | |||
| @@ -41,6 +41,11 @@ class FallbackBuildsTheHarnesses(unittest.TestCase): | |||
| 41 | with self.subTest(source=name): | 41 | with self.subTest(source=name): |
| 42 | self.assertTrue((ROOT / "runtime" / "test" / name).is_file()) | 42 | self.assertTrue((ROOT / "runtime" / "test" / name).is_file()) |
| 43 | 43 | ||
| 44 | def test_build_cmd_sets_utf8_codepage_for_ninja_showincludes(self): | ||
| 45 | text = SCRIPT.read_text(encoding="utf-8") | ||
| 46 | self.assertIn("chcp 65001 >nul", text) | ||
| 47 | self.assertLess(text.index("chcp 65001 >nul"), text.index('call `"$vcvars`"')) | ||
| 48 | |||
| 44 | 49 | ||
| 45 | if __name__ == "__main__": | 50 | if __name__ == "__main__": |
| 46 | unittest.main() | 51 | unittest.main() |
diff --git a/tests/test_ctest_registration.py b/tests/test_ctest_registration.py index cfaad282f..980c11cec 100644 --- a/tests/test_ctest_registration.py +++ b/tests/test_ctest_registration.py | |||
| @@ -63,6 +63,38 @@ class CTestRegistrationTest(unittest.TestCase): | |||
| 63 | self.assertEqual(len(skips), 3, f"expected three whole-test SKIP paths, got {len(skips)}") | 63 | self.assertEqual(len(skips), 3, f"expected three whole-test SKIP paths, got {len(skips)}") |
| 64 | self.assertEqual(skips, [77, 77, 77], "SKIP paths must return 77 for SKIP_RETURN_CODE 77") | 64 | self.assertEqual(skips, [77, 77, 77], "SKIP paths must return 77 for SKIP_RETURN_CODE 77") |
| 65 | 65 | ||
| 66 | def test_whole_test_skips_return_the_skip_code(self): | ||
| 67 | # A test registered with SKIP_RETURN_CODE 77 that prints SKIP and returns 0 is counted as passed although it | ||
| 68 | # checked nothing: bink_audio_test did that for a movie without audio tracks after #1580. | ||
| 69 | wrong = whole_test_skips_not_77(self.cmake, ROOT / "runtime") | ||
| 70 | self.assertEqual(wrong, [], f"SKIP followed by a return code other than 77: {wrong}") | ||
| 71 | |||
| 72 | |||
| 73 | def whole_test_skips_not_77(cmake_text, runtime_dir): | ||
| 74 | """[(source:line, code)] for a SKIP print directly followed by `return N;` (N != 77) in the sources of a test | ||
| 75 | registered with SKIP_RETURN_CODE 77. A SKIP print with no return right after it skips one section, not the test.""" | ||
| 76 | skip_tests = set(re.findall(r"set_tests_properties\(\s*([A-Za-z0-9_]+)\s+PROPERTIES[^)]*SKIP_RETURN_CODE\s+77", | ||
| 77 | cmake_text)) | ||
| 78 | commands = dict(re.findall(r"add_test\(\s*NAME\s+([A-Za-z0-9_]+)\s+COMMAND\s+\"?([A-Za-z0-9_]+)", cmake_text)) | ||
| 79 | wrong = [] | ||
| 80 | for test in sorted(skip_tests): | ||
| 81 | exe = commands.get(test) | ||
| 82 | m = exe and re.search(r"add_executable\(\s*" + re.escape(exe) + r"\b([^)]*)\)", cmake_text) | ||
| 83 | if not m: | ||
| 84 | continue | ||
| 85 | for src in re.findall(r"(test/[A-Za-z0-9_./]+\.cpp)", m.group(1)): | ||
| 86 | path = runtime_dir / src | ||
| 87 | if not path.is_file(): | ||
| 88 | continue | ||
| 89 | lines = path.read_text(encoding="utf-8", errors="replace").splitlines() | ||
| 90 | for i, line in enumerate(lines): | ||
| 91 | if not re.search(r'(printf|puts)\(\s*"SKIP', line): | ||
| 92 | continue | ||
| 93 | after = re.match(r"\s*return\s+(\w+)\s*;", lines[i + 1]) if i + 1 < len(lines) else None | ||
| 94 | if after and after.group(1) != "77": | ||
| 95 | wrong.append((f"{src}:{i + 2}", after.group(1))) | ||
| 96 | return wrong | ||
| 97 | |||
| 66 | 98 | ||
| 67 | if __name__ == "__main__": | 99 | if __name__ == "__main__": |
| 68 | unittest.main() | 100 | unittest.main() |
diff --git a/tests/test_d16_format_probe.py b/tests/test_d16_format_probe.py new file mode 100644 index 000000000..320116d6d --- /dev/null +++ b/tests/test_d16_format_probe.py | |||
| @@ -0,0 +1,222 @@ | |||
| 1 | """tools/d16_format_probe.py: the candidate rules, the GFX10 descriptor, what each kernel stages and loads, the | ||
| 2 | comparison and its exit codes (through a fake oracle that plays the GPU), and the exit-77 contract. The last class | ||
| 3 | runs on the hardware when the oracle tools are present and the GPU is GFX10, and is skipped otherwise. Standard | ||
| 4 | library only.""" | ||
| 5 | import io | ||
| 6 | import json | ||
| 7 | import os | ||
| 8 | from contextlib import redirect_stdout | ||
| 9 | from pathlib import Path | ||
| 10 | import re | ||
| 11 | import subprocess | ||
| 12 | import sys | ||
| 13 | import tempfile | ||
| 14 | import unittest | ||
| 15 | from unittest import mock | ||
| 16 | |||
| 17 | TOOLS = Path(__file__).resolve().parents[1] / "tools" | ||
| 18 | sys.path.insert(0, str(TOOLS)) | ||
| 19 | import d16_format_probe as pr # noqa: E402 | ||
| 20 | from hw_oracle import asm, runner # noqa: E402 | ||
| 21 | |||
| 22 | |||
| 23 | class Rules(unittest.TestCase): | ||
| 24 | def test_self_test(self): | ||
| 25 | with redirect_stdout(io.StringIO()): | ||
| 26 | self.assertEqual(pr.self_test(), 0) | ||
| 27 | |||
| 28 | def test_the_489_counts_in_docs_design(self): | ||
| 29 | # docs/design.md ("d16 and f16 format narrowing"): with RTZ narrowing 123 of 256 UNORM8, 31,742 of 65,536 | ||
| 30 | # UNORM16 and 110 of 256 SNORM8 values came out 1 ulp low | ||
| 31 | self.assertEqual(pr.rte_rtz_disagreements("unorm", 8), 123) | ||
| 32 | self.assertEqual(pr.rte_rtz_disagreements("snorm", 8), 110) | ||
| 33 | self.assertEqual(pr.rte_rtz_disagreements("unorm", 16), 31742) | ||
| 34 | |||
| 35 | def test_only_four_16_bit_values_separate_one_rounding_from_two(self): | ||
| 36 | split = {(k, v) for k in ("unorm", "snorm") for v in range(65536) | ||
| 37 | if pr.models16(k, 16, v)["rte"] != pr.models16(k, 16, v)["f32_rte"]} | ||
| 38 | self.assertEqual(split, {("unorm", 0xFFAF), ("unorm", 0xFFEF), ("snorm", 0x7FF7), ("snorm", 0x8009)}) | ||
| 39 | |||
| 40 | def test_8_and_10_bit_formats_only_tell_rte_from_rtz(self): | ||
| 41 | for kind, n in (("unorm", 8), ("snorm", 8), ("unorm", 10)): | ||
| 42 | for v in range(1 << n): | ||
| 43 | m = pr.models16(kind, n, v) | ||
| 44 | self.assertEqual(len({m["f32_rte"], m["rte"], m["mul_rte"], m["f32_rte_flush"]}), 1, (kind, v)) | ||
| 45 | |||
| 46 | def test_snorm_minimum_is_minus_one_and_f32_decode_is_exact(self): | ||
| 47 | self.assertEqual(pr.models16("snorm", 8, 0x80)["f32_rte"], 0xBC00) | ||
| 48 | self.assertEqual(pr.models16("snorm", 8, 0x81)["f32_rte"], 0xBC00) | ||
| 49 | self.assertEqual(pr.models32("unorm", 16, 0xFFFF)["f32_rte"], 0x3F800000) | ||
| 50 | self.assertEqual(pr.models32("unorm", 8, 0x80)["f32_rte"], 0x3F008081) # 128 / 255 | ||
| 51 | |||
| 52 | |||
| 53 | class Kernels(unittest.TestCase): | ||
| 54 | def test_descriptor_word3(self): | ||
| 55 | w = pr.descriptor_word3(8) | ||
| 56 | self.assertEqual([w & 7, w >> 3 & 7, w >> 6 & 7, w >> 9 & 7], [4, 5, 6, 7]) | ||
| 57 | self.assertEqual((w >> 12 & 0x7F, w >> 24 & 1, w >> 28 & 3, w >> 30), (8, 1, 3, 0)) | ||
| 58 | |||
| 59 | def test_every_value_is_staged_once(self): | ||
| 60 | for fmt, (_, _, n) in pr.FORMATS.items(): | ||
| 61 | seen = [] | ||
| 62 | for inst, base in pr.jobs(fmt): | ||
| 63 | if inst != "buffer_d16": | ||
| 64 | continue | ||
| 65 | self.assertEqual(pr.kernel_lines(inst, fmt, base)[0], f"v_add_nc_u32 v1, 0x{base:x}, v0") | ||
| 66 | seen += [(base + t) & ((1 << n) - 1) for t in range(min(pr.THREADS, (1 << n) - base))] | ||
| 67 | self.assertEqual(seen, list(range(1 << n)), fmt) | ||
| 68 | |||
| 69 | def test_mtbuf_names_the_format_and_mubuf_takes_it_from_the_descriptor(self): | ||
| 70 | lines = pr.kernel_lines("tbuffer_d16", "snorm16", 0) | ||
| 71 | self.assertIn("format:8 offen glc dlc", lines[10]) | ||
| 72 | self.assertTrue(pr.kernel_lines("buffer_d16", "snorm16", 0)[10].startswith("buffer_load_format_d16_x")) | ||
| 73 | self.assertIn(f"s_mov_b32 s11, 0x{pr.descriptor_word3(8):x}", lines) | ||
| 74 | |||
| 75 | def test_kernels_assemble_for_rdna2(self): | ||
| 76 | try: | ||
| 77 | clang = runner.find_clang() | ||
| 78 | except runner.Unavailable as e: | ||
| 79 | self.skipTest(str(e)) | ||
| 80 | kernels = [asm.Kernel(pr.kernel_lines(inst, fmt, 0), 32, pr.THREADS, pr.WORDS, raw=True, vgprs=8, sgprs=16) | ||
| 81 | for fmt in pr.FORMATS for inst in pr.INSTS] | ||
| 82 | text, names, _ = asm.module_text(kernels, "gfx1031", wave=32) | ||
| 83 | with tempfile.TemporaryDirectory() as d: | ||
| 84 | s = Path(d) / "k.s" | ||
| 85 | s.write_text(text, encoding="utf-8") | ||
| 86 | r = subprocess.run([clang, "--target=amdgcn-amd-amdhsa", "-mcpu=gfx1031", "-c", str(s), "-o", | ||
| 87 | str(Path(d) / "k.o")], capture_output=True, text=True) | ||
| 88 | self.assertEqual(r.returncode, 0, r.stderr[:800]) | ||
| 89 | self.assertIn("global_store_dword v4, v3, s[2:3]", text) | ||
| 90 | self.assertIn("s_waitcnt_vscnt null, 0x0", text) | ||
| 91 | |||
| 92 | |||
| 93 | class FakeOracle: | ||
| 94 | """Plays the GPU: reads each kernel's base, format code and load, and answers with a rule's bits.""" | ||
| 95 | arch = "gfx1031" | ||
| 96 | device = "fake gfx1031" | ||
| 97 | |||
| 98 | def __init__(self, rule="rte", clobber_hi=False, wave64_off=None): | ||
| 99 | self.rule, self.clobber_hi, self.wave64_off = rule, clobber_hi, wave64_off | ||
| 100 | |||
| 101 | def run(self, kernels, words=4): | ||
| 102 | code_of = {c: (f, k, n) for f, (c, k, n) in pr.FORMATS.items()} | ||
| 103 | out = [] | ||
| 104 | for k in kernels: | ||
| 105 | base = int(re.search(r"0x([0-9a-f]+)", k.lines[0]).group(1), 16) | ||
| 106 | w3 = int(next(ln for ln in k.lines if ln.startswith("s_mov_b32 s11")).split("0x")[1], 16) | ||
| 107 | fmt, kind, n = code_of[w3 >> 12 & 0x7F] | ||
| 108 | load = k.lines[10] | ||
| 109 | staged = [(base + t) & ((1 << n) - 1) for t in range(pr.THREADS)] | ||
| 110 | res = [] | ||
| 111 | for v in staged: | ||
| 112 | if kind == "f16": | ||
| 113 | bits = v | ||
| 114 | elif load.startswith("buffer_load_format_x"): | ||
| 115 | res.append(pr.models32(kind, n, v)["f32_rte"]) | ||
| 116 | continue | ||
| 117 | else: | ||
| 118 | bits = pr.models16(kind, n, v)[self.rule] | ||
| 119 | if self.wave64_off is not None and k.wave == 64 and v == self.wave64_off: | ||
| 120 | bits ^= 1 | ||
| 121 | hi = 0 if self.clobber_hi else pr.HI_SEED | ||
| 122 | res.append(hi | bits) | ||
| 123 | out.append(staged + res) | ||
| 124 | return out | ||
| 125 | |||
| 126 | def close(self): | ||
| 127 | pass | ||
| 128 | |||
| 129 | |||
| 130 | def run_main(oracle, *args): | ||
| 131 | buf = io.StringIO() | ||
| 132 | with mock.patch.object(runner, "open_oracle", return_value=oracle), redirect_stdout(buf): | ||
| 133 | rc = pr.main(["--formats", "unorm8,float16", *args]) | ||
| 134 | return rc, buf.getvalue() | ||
| 135 | |||
| 136 | |||
| 137 | class Compare(unittest.TestCase): | ||
| 138 | def test_the_translators_rule_matches_everywhere(self): | ||
| 139 | rc, out = run_main(FakeOracle()) | ||
| 140 | self.assertEqual(rc, 0, out) | ||
| 141 | self.assertIn("off the rule 0", out) | ||
| 142 | self.assertIn("own bits 65536/65536", out) | ||
| 143 | |||
| 144 | def test_double_rounding_hardware_shows_the_four_halfway_values(self): | ||
| 145 | buf = io.StringIO() | ||
| 146 | with mock.patch.object(runner, "open_oracle", return_value=FakeOracle("f32_rte")), redirect_stdout(buf): | ||
| 147 | rc = pr.main(["--formats", "unorm16,snorm16", "--waves", "32"]) | ||
| 148 | self.assertEqual(rc, 0, buf.getvalue()) | ||
| 149 | self.assertEqual(buf.getvalue().count("off the rule 2"), 4) # MUBUF and MTBUF, two formats | ||
| 150 | self.assertIn("value 0xffef: hw 0x3c00, rule 0x3bff", buf.getvalue()) | ||
| 151 | |||
| 152 | def test_rtz_hardware_is_a_finding_not_a_failure(self): | ||
| 153 | with tempfile.TemporaryDirectory() as d: | ||
| 154 | j = os.path.join(d, "r.json") | ||
| 155 | rc, out = run_main(FakeOracle("f32_rtz"), "--json", j) | ||
| 156 | with open(j, encoding="utf-8") as f: | ||
| 157 | rep = json.load(f) | ||
| 158 | self.assertEqual(rc, 0, out) | ||
| 159 | d16 = rep["formats"]["unorm8"]["insts"]["buffer_d16"] | ||
| 160 | self.assertEqual(d16["off_rule"], 123) | ||
| 161 | self.assertEqual(d16["match"]["f32_rtz"], 256) | ||
| 162 | self.assertIn("f32_rtz", d16["first_off"][0]["fits"]) | ||
| 163 | |||
| 164 | def test_a_wave_difference_exits_1(self): | ||
| 165 | rc, out = run_main(FakeOracle(wave64_off=9)) | ||
| 166 | self.assertEqual(rc, 1, out) | ||
| 167 | |||
| 168 | def test_a_clobbered_high_half_is_a_harness_error(self): | ||
| 169 | rc, out = run_main(FakeOracle(clobber_hi=True)) | ||
| 170 | self.assertEqual(rc, 2, out) | ||
| 171 | self.assertIn("high half", out) | ||
| 172 | |||
| 173 | def test_not_gfx10_exits_77(self): | ||
| 174 | o = FakeOracle() | ||
| 175 | o.arch = "gfx1150" | ||
| 176 | rc, out = run_main(o) | ||
| 177 | self.assertEqual(rc, 77, out) | ||
| 178 | |||
| 179 | |||
| 180 | class Cli(unittest.TestCase): | ||
| 181 | def test_exits_77_without_the_tools(self): | ||
| 182 | env = dict(os.environ, LEONIDA_AMD_CLANG=str(TOOLS / "no-such-clang.exe"), LEONIDA_HW_DRM_NODE="") | ||
| 183 | r = subprocess.run([sys.executable, "-I", str(TOOLS / "d16_format_probe.py"), "--formats", "unorm8"], | ||
| 184 | capture_output=True, text=True, env=env) | ||
| 185 | self.assertEqual(r.returncode, 77, r.stdout + r.stderr) | ||
| 186 | self.assertIn("unavailable", r.stdout) | ||
| 187 | |||
| 188 | def test_unknown_format_is_a_usage_error(self): | ||
| 189 | r = subprocess.run([sys.executable, "-I", str(TOOLS / "d16_format_probe.py"), "--formats", "unorm12"], | ||
| 190 | capture_output=True, text=True) | ||
| 191 | self.assertEqual(r.returncode, 2) | ||
| 192 | self.assertIn("unorm12", r.stderr) | ||
| 193 | |||
| 194 | |||
| 195 | class OnHardware(unittest.TestCase): | ||
| 196 | @classmethod | ||
| 197 | def setUpClass(cls): | ||
| 198 | try: | ||
| 199 | cls.oracle = runner.open_oracle() | ||
| 200 | except runner.Unavailable as e: | ||
| 201 | raise unittest.SkipTest(f"hardware oracle unavailable: {e}") from None | ||
| 202 | if asm.family(cls.oracle.arch) != "gfx10": | ||
| 203 | cls.oracle.close() | ||
| 204 | raise unittest.SkipTest(f"{cls.oracle.arch} is not GFX10") | ||
| 205 | |||
| 206 | @classmethod | ||
| 207 | def tearDownClass(cls): | ||
| 208 | cls.oracle.close() | ||
| 209 | |||
| 210 | def test_unorm8_controls_hold_and_both_wave_sizes_agree(self): | ||
| 211 | w32 = pr.sweep(self.oracle, "unorm8", 32) | ||
| 212 | w64 = pr.sweep(self.oracle, "unorm8", 64) | ||
| 213 | self.assertEqual(w32, w64) | ||
| 214 | res = pr.classify("unorm8", w32) | ||
| 215 | self.assertEqual(res["control"], []) | ||
| 216 | self.assertEqual(w32["buffer_d16"][255] & 0xFFFF, 0x3C00) | ||
| 217 | self.assertEqual(w32["buffer_d16"][0] & 0xFFFF, 0) | ||
| 218 | self.assertEqual(w32["buffer_f32"][255], 0x3F800000) | ||
| 219 | |||
| 220 | |||
| 221 | if __name__ == "__main__": | ||
| 222 | unittest.main() | ||
diff --git a/tests/test_d3d12_xs_surface.py b/tests/test_d3d12_xs_surface.py index 536a2673a..754355d30 100644 --- a/tests/test_d3d12_xs_surface.py +++ b/tests/test_d3d12_xs_surface.py | |||
| @@ -82,4 +82,9 @@ if __name__ == "__main__": | |||
| 82 | errors, checked, _um = S.check_sdk() | 82 | errors, checked, _um = S.check_sdk() |
| 83 | assert errors == [], errors | 83 | assert errors == [], errors |
| 84 | assert checked == 83 | 84 | assert checked == 83 |
| 85 | if os.environ.get("SCARAB_REF"): | ||
| 86 | errors, _notes = S.check_scarab(os.environ["SCARAB_REF"]) | ||
| 87 | assert errors == [], errors | ||
| 88 | else: | ||
| 89 | print("SCARAB cross-check skipped: SCARAB_REF is not set") | ||
| 85 | print("ok") | 90 | print("ok") |
diff --git a/tests/test_docs_design_rows.py b/tests/test_docs_design_rows.py new file mode 100644 index 000000000..5da04ba59 --- /dev/null +++ b/tests/test_docs_design_rows.py | |||
| @@ -0,0 +1,64 @@ | |||
| 1 | """Each table in docs/design.md, docs/README.md and docs/testing.md names a topic once. | ||
| 2 | |||
| 3 | python -I tests/test_docs_design_rows.py | ||
| 4 | |||
| 5 | The translator contract table is where every new rule is recorded (CONTRIBUTING.md, AGENTS.md). When two branches | ||
| 6 | edit the same row and a merge keeps both sides, the table ends up with two rows for one topic, each holding facts the | ||
| 7 | other lacks, and a reader who stops at the first one misses the rest. On 2026-11-22 twenty topics appeared two to six | ||
| 8 | times; the docs index and the testing guide's "Known problems" had the same pattern. This test fails on a repeated | ||
| 9 | first cell within one table of those pages, where the first cell is the topic (other pages repeat it on purpose, e.g. | ||
| 10 | one row per benchmark size). No game files or build tools. | ||
| 11 | """ | ||
| 12 | import os | ||
| 13 | import unittest | ||
| 14 | |||
| 15 | ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | ||
| 16 | PAGES = ("design.md", "README.md", "testing.md") | ||
| 17 | |||
| 18 | |||
| 19 | def repeated_topics(lines): | ||
| 20 | """[(topic, [1-based line numbers])] for first cells that appear more than once in one table.""" | ||
| 21 | found = [] | ||
| 22 | table, in_fence = [], False | ||
| 23 | |||
| 24 | def close(): | ||
| 25 | seen = {} | ||
| 26 | for n in table[2:]: # skip the header and the |---| rule | ||
| 27 | cells = lines[n - 1].split("|") | ||
| 28 | if len(cells) > 2 and cells[1].strip(): | ||
| 29 | seen.setdefault(cells[1].strip(), []).append(n) | ||
| 30 | found.extend((k, v) for k, v in seen.items() if len(v) > 1) | ||
| 31 | |||
| 32 | for n, line in enumerate(lines, 1): | ||
| 33 | if line.lstrip().startswith("```"): | ||
| 34 | in_fence = not in_fence | ||
| 35 | if not in_fence and line.startswith("|"): | ||
| 36 | table.append(n) | ||
| 37 | continue | ||
| 38 | if table: | ||
| 39 | close() | ||
| 40 | table = [] | ||
| 41 | if table: | ||
| 42 | close() | ||
| 43 | return found | ||
| 44 | |||
| 45 | |||
| 46 | class DesignTableRows(unittest.TestCase): | ||
| 47 | def test_checker_finds_a_repeated_topic_within_one_table_only(self): | ||
| 48 | lines = ["| Topic | Rule |", "|---|---|", "| EXEC | old |", "| LDS | x |", "| EXEC | new |", "", | ||
| 49 | "| Topic | Rule |", "|---|---|", "| LDS | other table |", "```", "| EXEC | in a code block |", | ||
| 50 | "| EXEC | in a code block |", "```"] | ||
| 51 | self.assertEqual(repeated_topics(lines), [("EXEC", [3, 5])]) | ||
| 52 | |||
| 53 | def test_each_page_names_each_topic_once_per_table(self): | ||
| 54 | for page in PAGES: | ||
| 55 | with self.subTest(page=page): | ||
| 56 | with open(os.path.join(ROOT, "docs", page), encoding="utf-8") as f: | ||
| 57 | lines = f.read().split("\n") | ||
| 58 | repeated = repeated_topics(lines) | ||
| 59 | self.assertEqual(repeated, [], f"rows to merge into one in docs/{page} (topic, lines): " + | ||
| 60 | "; ".join(f"{k[:60]!r} at {v}" for k, v in repeated)) | ||
| 61 | |||
| 62 | |||
| 63 | if __name__ == "__main__": | ||
| 64 | unittest.main() | ||
diff --git a/tests/test_docs_list_items.py b/tests/test_docs_list_items.py new file mode 100644 index 000000000..029994b0d --- /dev/null +++ b/tests/test_docs_list_items.py | |||
| @@ -0,0 +1,72 @@ | |||
| 1 | """No list item in the Markdown docs is repeated a few lines later. | ||
| 2 | |||
| 3 | python -I tests/test_docs_list_items.py | ||
| 4 | |||
| 5 | When two branches rewrite the same bullet and a merge keeps both sides, the page shows the bullet twice: the current | ||
| 6 | text and the one it replaced, often next to each other (docs/d3d12_vulkan.md had its RTV/DSV bullet twice and its | ||
| 7 | "Hash-table cost" / "Wave64" risks twice each; docs/character_models.md kept the first line of a rewritten bullet). | ||
| 8 | A reader cannot tell which copy is current. This test flags two list items within WINDOW lines of each other whose | ||
| 9 | openings match. Reads tracked Markdown only; no game files. | ||
| 10 | """ | ||
| 11 | import os | ||
| 12 | import re | ||
| 13 | import subprocess | ||
| 14 | import unittest | ||
| 15 | |||
| 16 | ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | ||
| 17 | ITEM = re.compile(r"^(\s*)(?:[-*+]|\d+[.)])\s+(\S.*)$") | ||
| 18 | WINDOW = 8 # lines between the two items | ||
| 19 | OPENING = 60 # characters of the item's text that must match (after the list marker) | ||
| 20 | |||
| 21 | |||
| 22 | def repeated_items(text): | ||
| 23 | """[(line a, line b)] for list items within WINDOW lines whose first OPENING characters are equal.""" | ||
| 24 | items, in_fence = [], False | ||
| 25 | for n, line in enumerate(text.split("\n"), 1): | ||
| 26 | if line.lstrip().startswith("```"): | ||
| 27 | in_fence = not in_fence | ||
| 28 | continue | ||
| 29 | m = None if in_fence else ITEM.match(line) | ||
| 30 | if m and len(m.group(2)) >= OPENING: | ||
| 31 | items.append((n, len(m.group(1)), m.group(2)[:OPENING])) | ||
| 32 | found = [] | ||
| 33 | for i, (n, indent, head) in enumerate(items): | ||
| 34 | for n2, indent2, head2 in items[i + 1:]: | ||
| 35 | if n2 - n > WINDOW: | ||
| 36 | break | ||
| 37 | if indent2 == indent and head2 == head: | ||
| 38 | found.append((n, n2)) | ||
| 39 | return found | ||
| 40 | |||
| 41 | |||
| 42 | def markdown_files(): | ||
| 43 | try: | ||
| 44 | out = subprocess.run(["git", "ls-files", "*.md"], cwd=ROOT, capture_output=True, text=True, check=True).stdout | ||
| 45 | files = out.split() | ||
| 46 | except (OSError, subprocess.CalledProcessError): | ||
| 47 | files = [os.path.relpath(os.path.join(r, f), ROOT).replace(os.sep, "/") | ||
| 48 | for r, d, fs in os.walk(ROOT) if ".git" not in r for f in fs if f.endswith(".md")] | ||
| 49 | return [f for f in files if not f.startswith("third_party/")] | ||
| 50 | |||
| 51 | |||
| 52 | class RepeatedListItems(unittest.TestCase): | ||
| 53 | def test_checker_flags_a_repeated_item_only(self): | ||
| 54 | current = "- **Wave64.** A native wave64 shader needs a 64-wide subgroup in its stage: AMD can require it" | ||
| 55 | old = "- **Wave64.** A native wave64 shader needs a 64-wide subgroup in its stage: AMD (old wording)" | ||
| 56 | text = "\n".join([current, " continued", "- **Other.** " + "x" * 70, old, "", | ||
| 57 | "- **19 two-slice 2D arrays** (`depth = 2`, `depth - 1 = 1`) appeared as `depth = 1`", | ||
| 58 | "- **99 three-slice 2D arrays** (`depth = 3`, `depth - 1 = 2`) appeared as `depth = 2`", | ||
| 59 | "```", current, current, "```"]) | ||
| 60 | self.assertEqual(repeated_items(text), [(1, 4)]) | ||
| 61 | |||
| 62 | def test_docs_have_no_repeated_list_items(self): | ||
| 63 | found = [] | ||
| 64 | for path in markdown_files(): | ||
| 65 | with open(os.path.join(ROOT, path), encoding="utf-8") as f: | ||
| 66 | found += [f"{path}:{a} and :{b}" for a, b in repeated_items(f.read())] | ||
| 67 | self.assertEqual(found, [], "a list item repeated a few lines later (keep the current copy): " + | ||
| 68 | "; ".join(found)) | ||
| 69 | |||
| 70 | |||
| 71 | if __name__ == "__main__": | ||
| 72 | unittest.main() | ||
diff --git a/tests/test_docs_repo_paths.py b/tests/test_docs_repo_paths.py new file mode 100644 index 000000000..69f19b0e2 --- /dev/null +++ b/tests/test_docs_repo_paths.py | |||
| @@ -0,0 +1,79 @@ | |||
| 1 | """Repository paths the docs name in backticks exist. | ||
| 2 | |||
| 3 | python -I tests/test_docs_repo_paths.py | ||
| 4 | |||
| 5 | `tests/test_docs_links.py` checks Markdown links; this checks the other way the docs point at code, a backticked | ||
| 6 | `tools/...`, `runtime/...`, `tests/...` or `scripts/...` path. A rename, or a page written against an unmerged pull | ||
| 7 | request, leaves such a path pointing at nothing (docs/saves.md described #279's `xgameruntime_services.cpp` as the | ||
| 8 | runtime's save store while #279 was still open). Reads tracked files only (`git ls-files`, with a directory walk when | ||
| 9 | git is not available); no game files. | ||
| 10 | """ | ||
| 11 | import os | ||
| 12 | import re | ||
| 13 | import subprocess | ||
| 14 | import unittest | ||
| 15 | |||
| 16 | ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | ||
| 17 | PATH = re.compile(r"`((?:tools|runtime|tests|scripts)/[A-Za-z0-9_./\-]+)`") | ||
| 18 | # Pages that quote another project's tree (SCARAB, americas-recomp): their paths are not this repository's. | ||
| 19 | OTHER_PROJECTS = {"docs/fssm_crosscheck.md", "docs/d3d12_xs_surface.md"} | ||
| 20 | # Build output, not tracked. | ||
| 21 | BUILD_OUTPUT = ("runtime/build",) | ||
| 22 | |||
| 23 | |||
| 24 | def tracked_files(): | ||
| 25 | try: | ||
| 26 | out = subprocess.run(["git", "ls-files"], cwd=ROOT, capture_output=True, text=True, check=True).stdout | ||
| 27 | return [p for p in out.splitlines() if p] | ||
| 28 | except (OSError, subprocess.CalledProcessError): | ||
| 29 | found = [] | ||
| 30 | for root, dirs, files in os.walk(ROOT): | ||
| 31 | dirs[:] = [d for d in dirs if d not in (".git", "build", "__pycache__")] | ||
| 32 | found += [os.path.relpath(os.path.join(root, f), ROOT).replace(os.sep, "/") for f in files] | ||
| 33 | return found | ||
| 34 | |||
| 35 | |||
| 36 | def missing_paths(pages, files): | ||
| 37 | """[(page:line, path)] for backticked repository paths in `pages` ({name: text}) that `files` lacks.""" | ||
| 38 | known = set(files) | ||
| 39 | for f in files: | ||
| 40 | parts = f.split("/") | ||
| 41 | known.update("/".join(parts[:i]) for i in range(1, len(parts))) | ||
| 42 | out = [] | ||
| 43 | for page, text in sorted(pages.items()): | ||
| 44 | in_fence = False | ||
| 45 | for n, line in enumerate(text.split("\n"), 1): | ||
| 46 | if line.lstrip().startswith("```"): | ||
| 47 | in_fence = not in_fence | ||
| 48 | continue | ||
| 49 | if in_fence or "://" in line: # a link into another repository names its paths | ||
| 50 | continue | ||
| 51 | for m in PATH.finditer(line): | ||
| 52 | path = m.group(1).rstrip("/.") | ||
| 53 | if "*" in path or path.startswith(BUILD_OUTPUT) or path in known: | ||
| 54 | continue | ||
| 55 | out.append((f"{page}:{n}", path)) | ||
| 56 | return out | ||
| 57 | |||
| 58 | |||
| 59 | class DocsRepoPaths(unittest.TestCase): | ||
| 60 | def test_checker_reports_only_the_missing_path(self): | ||
| 61 | pages = {"docs/a.md": "Run `tools/real.py`, then `tools/gone.py`.\n```\n`tools/in_fence.py`\n```\n" | ||
| 62 | "`runtime/build/x.exe` and `tests/` and [`tools/x.py`](https://example.org/tools/x.py)"} | ||
| 63 | self.assertEqual(missing_paths(pages, ["tools/real.py", "tests/t.py"]), [("docs/a.md:1", "tools/gone.py")]) | ||
| 64 | |||
| 65 | def test_docs_name_existing_paths(self): | ||
| 66 | files = tracked_files() | ||
| 67 | pages = {} | ||
| 68 | for p in files: | ||
| 69 | if p.startswith("docs/") and p.endswith(".md") and p not in OTHER_PROJECTS: | ||
| 70 | with open(os.path.join(ROOT, p), encoding="utf-8") as f: | ||
| 71 | pages[p] = f.read() | ||
| 72 | self.assertTrue(pages) | ||
| 73 | missing = missing_paths(pages, files) | ||
| 74 | self.assertEqual(missing, [], "backticked paths that name no tracked file: " + | ||
| 75 | "; ".join(f"{where} {path}" for where, path in missing)) | ||
| 76 | |||
| 77 | |||
| 78 | if __name__ == "__main__": | ||
| 79 | unittest.main() | ||
diff --git a/tests/test_feature_scan.py b/tests/test_feature_scan.py index a3e80ae43..41a4dd815 100644 --- a/tests/test_feature_scan.py +++ b/tests/test_feature_scan.py | |||
| @@ -318,9 +318,103 @@ def test_v_perm_b32_selectors(): | |||
| 318 | assert failures == 0, f"{failures} v_perm_b32 check(s) failed" | 318 | assert failures == 0, f"{failures} v_perm_b32 check(s) failed" |
| 319 | 319 | ||
| 320 | 320 | ||
| 321 | def psv0(records, size=24, truncate=False): | ||
| 322 | """PSV0 payload: a 24-byte runtime info, then the resource count, record size and (type, kind) records.""" | ||
| 323 | body = struct.pack("<I", 24) + bytes(24) + struct.pack("<II", len(records), size) | ||
| 324 | for t, k in records: | ||
| 325 | rec = struct.pack("<4I", t, 0, 0, 0) + (struct.pack("<II", k, 0) if size >= 24 else b"") | ||
| 326 | body += rec + bytes(size - len(rec)) | ||
| 327 | return body[:-4] if truncate else body | ||
| 328 | |||
| 329 | |||
| 330 | def listing(lines): | ||
| 331 | """A .s listing with `; encoding:` comments of the right length, so pcs and branch targets are real.""" | ||
| 332 | return "".join(f"\t{code} ; encoding: [{','.join(['0x00'] * n)}]\n" for code, n in lines) | ||
| 333 | |||
| 334 | |||
| 335 | def test_typed_buffers_and_psv0(): | ||
| 336 | """§8.2 #16: PSV0 counter/typed-buffer bindings, MTBUF formats and where each MUBUF V# word 3 comes from.""" | ||
| 337 | with tempfile.TemporaryDirectory() as tmp: | ||
| 338 | sh = os.path.join(tmp, "shaders") | ||
| 339 | dx = os.path.join(sh, "dxbc") | ||
| 340 | dis = os.path.join(dx, "disasm") | ||
| 341 | os.makedirs(dis) | ||
| 342 | cs = listing([ | ||
| 343 | ("s_load_dwordx4 s[8:11], s[0:1], 0x0", 8), # pc 0 | ||
| 344 | ("s_mov_b32 s15, 0x38000", 8), # 8: format 56, 8_8_8_8_UNORM | ||
| 345 | ("s_mov_b32 s19, 0x24000", 8), # 16: format 36, 10_11_11_FLOAT | ||
| 346 | ("s_or_b32 s23, s23, 0x1000", 8), # 24: computed | ||
| 347 | ("s_cmp_eq_u32 s11, 0", 4), # 32: reads s11, writes nothing | ||
| 348 | ("buffer_load_format_xyzw v[0:3], v4, s[8:11], 0 idxen", 8), # 36: memory | ||
| 349 | ("buffer_load_format_x v5, v4, s[12:15], 0 idxen", 8), # 44: literal | ||
| 350 | ("buffer_store_format_x v5, v4, s[16:19], 0 idxen", 8), # 52: literal, not in the table | ||
| 351 | ("buffer_load_format_x v6, v4, s[20:23], 0 idxen", 8), # 60: computed | ||
| 352 | ("buffer_load_format_x v7, v4, s[24:27], 0 idxen", 8), # 68: never written: shader input | ||
| 353 | ("s_cbranch_scc0 1", 4), # 76: to 84; 80 and 84 lead blocks | ||
| 354 | ("s_nop 0", 4), # 80 | ||
| 355 | ("buffer_load_format_x v8, v4, s[8:11], 0 idxen", 8), # 84: loaded in an earlier block | ||
| 356 | ("buffer_load_format_x v9, v4, s[12:15], 0 idxen", 8), # 92: literal from an earlier block | ||
| 357 | ("tbuffer_load_format_xy v[0:1], v4, s[8:11], 0 format:[BUF_FMT_16_16_SNORM] idxen", 8), | ||
| 358 | ("tbuffer_load_format_x v2, v4, s[8:11], 0 idxen", 8), # no format: GFX10 default 8_UNORM | ||
| 359 | ("tbuffer_store_format_x v2, v4, s[8:11], 0 format:[BUF_FMT_10_11_11_FLOAT] idxen", 8), | ||
| 360 | ("s_endpgm", 4)]) | ||
| 361 | ps = listing([("s_mov_b32 s11, 0", 4), # word 3 0: FORMAT INVALID | ||
| 362 | ("buffer_load_format_x v0, v1, s[0:3], 0 idxen", 8), | ||
| 363 | ("buffer_load_format_x v2, v1, s[8:11], 0 idxen", 8), ("s_endpgm", 4)]) | ||
| 364 | vs = listing([("v_mov_b32_e32 v0, v1", 4), ("s_endpgm", 4)]) | ||
| 365 | synthetic = [ | ||
| 366 | ("tb_cs", "cs", cs, psv0([(9, 12), (3, 10), (6, 2)])), # counter UAV, typed buffer SRV, typed 2D UAV | ||
| 367 | ("tb_ps", "ps", ps, psv0([(6, 10), (6, 10)])), # two typed buffer UAVs | ||
| 368 | ("tb_vs", "vs", vs, psv0([(3, 10)], size=16)), # v0 records carry no kind | ||
| 369 | ("tb_gs", "gs", None, psv0([(9, 12)], truncate=True)), # records past the end of the part | ||
| 370 | ] | ||
| 371 | index = [] | ||
| 372 | for name, stage, text, psv in synthetic: | ||
| 373 | with open(os.path.join(dx, name + ".dxbc"), "wb") as f: | ||
| 374 | f.write(dxbc([("SFI0", struct.pack("<Q", 0)), ("OSG1", signature([0])), ("PSV0", psv)])) | ||
| 375 | index.append({"name": name, "file": name + ".dxbc", "stage": stage}) | ||
| 376 | if text: | ||
| 377 | with open(os.path.join(dis, name + ".s"), "w", encoding="utf-8") as f: | ||
| 378 | f.write(f"; {name}\n" + text) | ||
| 379 | with open(os.path.join(dx, "index.json"), "w", encoding="utf-8") as f: | ||
| 380 | json.dump(index, f) | ||
| 381 | |||
| 382 | pv = F.scan_dxbc(dx, index)["psv0"] | ||
| 383 | check(pv["records"] == 6 and pv["unreadable"] == 1, f"PSV0: 6 records read, 1 truncated table ({pv})") | ||
| 384 | check(pv["shaders"] == {"uav_with_counter": 1, "typed_buffer_srv": 1, "typed_buffer_uav": 1}, | ||
| 385 | f"PSV0 shaders with a counter UAV / typed buffer SRV / typed buffer UAV ({pv['shaders']})") | ||
| 386 | check(pv["records_of"] == {"uav_with_counter": 1, "typed_buffer_srv": 1, "typed_buffer_uav": 2}, | ||
| 387 | "a typed UAV of a texture kind and a v0 record without a kind are not typed buffers") | ||
| 388 | check(pv["by_type"] == {"UAVStructuredWithCounter": 1, "SRVTyped": 2, "UAVTyped": 3}, f"by type {pv['by_type']}") | ||
| 389 | |||
| 390 | tb = F.scan_typed_buffers(dis, {e["name"]: e["stage"] for e in index}) | ||
| 391 | check(tb["mtbuf"] == {"load 16_16_SNORM": 1, "load 8_UNORM": 1, "store 10_11_11_FLOAT": 1}, | ||
| 392 | f"MTBUF formats from the instruction, 8_UNORM without format: ({tb['mtbuf']})") | ||
| 393 | check(tb["mubuf_word3"] == {"load computed": 1, "load earlier_literal": 1, "load earlier_memory": 1, | ||
| 394 | "load literal": 2, "load memory": 1, "load shader_input": 2, | ||
| 395 | "store literal": 1}, | ||
| 396 | f"MUBUF word 3 by source, s_cmp is no write, a branch target starts a block ({tb['mubuf_word3']})") | ||
| 397 | check(tb["mubuf_literal_formats"] == {"load 8_8_8_8_UNORM": 2, "load INVALID": 1, | ||
| 398 | "store 10_11_11_FLOAT": 1}, f"literal word 3 formats ({tb['mubuf_literal_formats']})") | ||
| 399 | check(tb["not_in_translator"] == {"mtbuf store 10_11_11_FLOAT": 1, "mubuf_literal store 10_11_11_FLOAT": 1}, | ||
| 400 | f"formats outside rdna2spirv.Gen.FORMATS are listed, INVALID (reads 0) is not ({tb['not_in_translator']})") | ||
| 401 | check(tb["shaders"] == {"mtbuf": {"cs": 1}, "mubuf": {"cs": 1, "ps": 1}, "mubuf_literal": {"cs": 1, "ps": 1}, | ||
| 402 | "mubuf_runtime_format": {"cs": 1, "ps": 1}}, f"shaders per stage ({tb['shaders']})") | ||
| 403 | |||
| 404 | out_json = os.path.join(tmp, "out.json") | ||
| 405 | r = subprocess.run([sys.executable, "-I", os.path.join(TOOLS, "feature_scan.py"), sh, "--out", out_json], | ||
| 406 | capture_output=True, text=True) | ||
| 407 | check(r.returncode == 0 and "PSV0 bindings: 6 records" in r.stdout and "uav_with_counter 1" in r.stdout | ||
| 408 | and "10_11_11_FLOAT" in r.stdout, f"CLI prints the #16 summary (rc={r.returncode})") | ||
| 409 | raw_json = open(out_json, encoding="utf-8").read() | ||
| 410 | check(all(n not in r.stdout and n not in raw_json for n, *_ in synthetic), "no shader name in stdout or JSON") | ||
| 411 | assert failures == 0, f"{failures} typed-buffer check(s) failed" | ||
| 412 | |||
| 413 | |||
| 321 | if __name__ == "__main__": | 414 | if __name__ == "__main__": |
| 322 | try: | 415 | try: |
| 323 | test_feature_scan() | 416 | test_feature_scan() |
| 417 | test_typed_buffers_and_psv0() | ||
| 324 | test_short_signature() | 418 | test_short_signature() |
| 325 | test_part_payload_outside_container_is_unreadable() | 419 | test_part_payload_outside_container_is_unreadable() |
| 326 | test_bad_shaders_folder_is_one_line() | 420 | test_bad_shaders_folder_is_one_line() |
diff --git a/tests/test_fma_mix_probe.py b/tests/test_fma_mix_probe.py index db85fcd08..46c49f0cd 100644 --- a/tests/test_fma_mix_probe.py +++ b/tests/test_fma_mix_probe.py | |||
| @@ -65,14 +65,13 @@ class Inputs(unittest.TestCase): | |||
| 65 | 65 | ||
| 66 | 66 | ||
| 67 | class Translator(unittest.TestCase): | 67 | class Translator(unittest.TestCase): |
| 68 | def test_translator_rounds_twice(self): | 68 | def test_translator_rounds_once(self): |
| 69 | # docs/design.md, Known approximations: nearest-mode v_fma_mix* takes the f32 Fma and then narrows. If the | 69 | # docs/design.md, Known approximations: v_fma_mix* rounds once straight to f16 (measured on RDNA2 hardware). |
| 70 | # translator is changed to round once (after a hardware measurement), this test and that sentence change too. | ||
| 71 | got = probe.run_translator() | 70 | got = probe.run_translator() |
| 72 | rule, _ = probe.verdict(list(zip(probe.CASES, got))) | 71 | rule, _ = probe.verdict(list(zip(probe.CASES, got))) |
| 73 | self.assertEqual(rule, probe.DOUBLE) | 72 | self.assertEqual(rule, probe.SINGLE) |
| 74 | for case, w in zip(probe.CASES, got): | 73 | for case, w in zip(probe.CASES, got): |
| 75 | self.assertEqual(w, word(case, BY_HAND[case.name][1]), case.name) | 74 | self.assertEqual(w, word(case, BY_HAND[case.name][0]), case.name) |
| 76 | 75 | ||
| 77 | def test_compute_listing_gives_the_pixel_shader_words(self): | 76 | def test_compute_listing_gives_the_pixel_shader_words(self): |
| 78 | # The Vulkan side's shader (operands from user SGPRs, one store per case) on the CPU interpreter, with the | 77 | # The Vulkan side's shader (operands from user SGPRs, one store per case) on the CPU interpreter, with the |
| @@ -149,7 +148,7 @@ class Command(unittest.TestCase): | |||
| 149 | with contextlib.redirect_stdout(buf): | 148 | with contextlib.redirect_stdout(buf): |
| 150 | rc = probe.main([]) | 149 | rc = probe.main([]) |
| 151 | self.assertEqual(rc, 0) | 150 | self.assertEqual(rc, 0) |
| 152 | self.assertIn("translator: follows double rounding", buf.getvalue()) | 151 | self.assertIn("translator: follows single rounding", buf.getvalue()) |
| 153 | 152 | ||
| 154 | def test_unknown_side_and_missing_build_are_usage_errors(self): | 153 | def test_unknown_side_and_missing_build_are_usage_errors(self): |
| 155 | import contextlib | 154 | import contextlib |
diff --git a/tests/test_fspx_unpack.py b/tests/test_fspx_unpack.py index 3c9c843fc..c5c8b8fd3 100644 --- a/tests/test_fspx_unpack.py +++ b/tests/test_fspx_unpack.py | |||
| @@ -200,6 +200,26 @@ class Cli(unittest.TestCase): | |||
| 200 | with open(os.path.join(out, "lib_01.dxbc"), "rb") as f: | 200 | with open(os.path.join(out, "lib_01.dxbc"), "rb") as f: |
| 201 | self.assertEqual(f.read(), c) | 201 | self.assertEqual(f.read(), c) |
| 202 | 202 | ||
| 203 | def test_retains_programs_with_matching_input_stems(self): | ||
| 204 | container = Containers().container() | ||
| 205 | with tempfile.TemporaryDirectory() as tmp: | ||
| 206 | a = os.path.join(tmp, "a", "sample.dxbc") | ||
| 207 | b = os.path.join(tmp, "b", "sample.dll") | ||
| 208 | for path, data in ((a, container), (b, b"MZ" + bytes(62) + container)): | ||
| 209 | os.makedirs(os.path.dirname(path)) | ||
| 210 | with open(path, "wb") as f: | ||
| 211 | f.write(data) | ||
| 212 | out = os.path.join(tmp, "out") | ||
| 213 | code, _, err = self.run_tool(a, b, "--out", out) | ||
| 214 | self.assertEqual(code, 0, err) | ||
| 215 | with open(os.path.join(out, "index.json"), encoding="utf-8") as f: | ||
| 216 | index = json.load(f) | ||
| 217 | self.assertEqual([entry["file"] for entry in index], ["sample.dxbc", "sample_2.dxbc"]) | ||
| 218 | for name, offset in (("sample", 0), ("sample_2", 64)): | ||
| 219 | with open(os.path.join(out, "fspx", name + ".json"), encoding="utf-8") as f: | ||
| 220 | self.assertEqual(json.load(f)["source"]["offset"], offset) | ||
| 221 | self.assertTrue(os.path.isfile(os.path.join(out, name + ".dxbc"))) | ||
| 222 | |||
| 203 | def test_bare_payload_and_a_file_without_fspx(self): | 223 | def test_bare_payload_and_a_file_without_fspx(self): |
| 204 | with tempfile.TemporaryDirectory() as t: | 224 | with tempfile.TemporaryDirectory() as t: |
| 205 | bare = os.path.join(t, "one.fspx") | 225 | bare = os.path.join(t, "one.fspx") |
| @@ -227,6 +247,24 @@ class Cli(unittest.TestCase): | |||
| 227 | self.assertEqual(code, 1) | 247 | self.assertEqual(code, 1) |
| 228 | self.assertIn("FSPX status 5", err) | 248 | self.assertIn("FSPX status 5", err) |
| 229 | 249 | ||
| 250 | def test_short_kind0_unpacks_without_keyerror(self): | ||
| 251 | with tempfile.TemporaryDirectory() as t: | ||
| 252 | src = os.path.join(t, "short.fspx") | ||
| 253 | with open(src, "wb") as f: | ||
| 254 | f.write(make_fspx([(0, struct.pack("<2I", 1, 2)), (6, program())])) | ||
| 255 | out = os.path.join(t, "out") | ||
| 256 | code, _, err = self.run_tool(src, "--out", out) | ||
| 257 | self.assertEqual(code, 0) | ||
| 258 | self.assertEqual(err, "") | ||
| 259 | with open(os.path.join(out, "index.json"), encoding="utf-8") as f: | ||
| 260 | index = json.load(f) | ||
| 261 | self.assertEqual(len(index), 1) | ||
| 262 | self.assertNotIn("threads", index[0]) | ||
| 263 | self.assertNotIn("wave32", index[0]) | ||
| 264 | with open(os.path.join(out, "fspx", "short.json"), encoding="utf-8") as f: | ||
| 265 | meta = json.load(f) | ||
| 266 | self.assertEqual(meta["words"], [1, 2]) | ||
| 267 | |||
| 230 | 268 | ||
| 231 | class TranslatorSidecars(unittest.TestCase): | 269 | class TranslatorSidecars(unittest.TestCase): |
| 232 | """rdna2spirv reads an FSPX program's code and dispatch state from fspx/ when there is no FSSM blob.""" | 270 | """rdna2spirv reads an FSPX program's code and dispatch state from fspx/ when there is no FSSM blob.""" |
diff --git a/tests/test_gamedata_index.py b/tests/test_gamedata_index.py index 1409150dd..832926511 100644 --- a/tests/test_gamedata_index.py +++ b/tests/test_gamedata_index.py | |||
| @@ -150,6 +150,25 @@ class GamedataIndexTest(unittest.TestCase): | |||
| 150 | self.assertEqual(rows[0]["root"], "RootA") | 150 | self.assertEqual(rows[0]["root"], "RootA") |
| 151 | self.assertEqual(rows[0]["type"], "xml") | 151 | self.assertEqual(rows[0]["type"], "xml") |
| 152 | 152 | ||
| 153 | def test_printable_page_directory_stream_is_not_xml(self): | ||
| 154 | # A resource stream with the "0DRP" page marker at +16 whose first 4 KiB are over 95% printable and hold a | ||
| 155 | # "<": data.rpf's 337 such streams were reported as incomplete XML with no root. | ||
| 156 | head = bytes(8) + bytes.fromhex("80ca005000000000") + b"0DRP" + bytes(12) | ||
| 157 | page = head + (b"<abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ>" * 80)[:4096 - len(head)] | ||
| 158 | page += bytes(512) | ||
| 159 | tool = load_tool() | ||
| 160 | self.assertGreater(tool.printable(page), 0.95) # the heuristic alone would call it text | ||
| 161 | self.add(page) | ||
| 162 | self.finish() | ||
| 163 | out = os.path.join(self.root, "index.json") | ||
| 164 | p = self.run_tool(self.carve, "--json", out) | ||
| 165 | self.assertEqual(p.returncode, 0, p.stdout + p.stderr) | ||
| 166 | with open(out, encoding="utf-8") as f: | ||
| 167 | data = json.load(f) | ||
| 168 | self.assertNotIn("xml", data["summary"]["types"]) | ||
| 169 | self.assertEqual(data["summary"]["xml_incomplete"], 0) | ||
| 170 | self.assertEqual([(r["type"], r["detail"]) for r in data["rows"]], [("other", "0DRP")]) | ||
| 171 | |||
| 153 | def test_archive_runs_the_carver_and_reads_roots(self): | 172 | def test_archive_runs_the_carver_and_reads_roots(self): |
| 154 | xml = b'<?xml version="1.0"?>\n<RootA><!-- synthetic fixture, longer than 64 bytes --><Item value="1"/></RootA>' | 173 | xml = b'<?xml version="1.0"?>\n<RootA><!-- synthetic fixture, longer than 64 bytes --><Item value="1"/></RootA>' |
| 155 | blob = b"\x00\x01\x02binary\xff" * 32 | 174 | blob = b"\x00\x01\x02binary\xff" * 32 |
diff --git a/tests/test_glb_writer.py b/tests/test_glb_writer.py index ac3dcdbea..840fec126 100644 --- a/tests/test_glb_writer.py +++ b/tests/test_glb_writer.py | |||
| @@ -748,6 +748,25 @@ class TestObjParserAndBounds(unittest.TestCase): | |||
| 748 | for actual, target in zip(normals[position, uv], expected_normal): | 748 | for actual, target in zip(normals[position, uv], expected_normal): |
| 749 | self.assertAlmostEqual(actual, target) | 749 | self.assertAlmostEqual(actual, target) |
| 750 | 750 | ||
| 751 | def test_parse_obj_explicit_faces_preserve_generated_hard_edge(self): | ||
| 752 | # A top face without normals shares two positions with a fully normaled side. | ||
| 753 | vertices = ["v 0 1 0", "v 1 1 0", "v 1 1 1", "v 0 1 1", "v 0 0 1", "v 1 0 1"] | ||
| 754 | top = "f 1 4 3 2" | ||
| 755 | side = "f 5//1 6//1 3//1 4//1" | ||
| 756 | for faces in ((top, side), (side, top)): | ||
| 757 | with self.subTest(first_face=faces[0]): | ||
| 758 | obj_text = "\n".join([*vertices, "vn 0 0 1", *faces]) | ||
| 759 | prim, = glb_writer.parse_obj(obj_text, is_path=False, up_axis="y") | ||
| 760 | normals_by_face = [ | ||
| 761 | {(0.0, 1.0, 0.0)} if face == top else {(0.0, 0.0, 1.0)} | ||
| 762 | for face in faces | ||
| 763 | ] | ||
| 764 | self.assertEqual(len(prim["positions"]), 8) | ||
| 765 | self.assertEqual(len(prim["indices"]), 12) | ||
| 766 | for start, expected in zip((0, 6), normals_by_face): | ||
| 767 | actual = {prim["normals"][i] for i in prim["indices"][start:start + 6]} | ||
| 768 | self.assertEqual(actual, expected) | ||
| 769 | |||
| 751 | def test_parse_obj_quad_fan_triangulation(self): | 770 | def test_parse_obj_quad_fan_triangulation(self): |
| 752 | obj_text = "\n".join([ | 771 | obj_text = "\n".join([ |
| 753 | "v 0 0 0", | 772 | "v 0 0 0", |
diff --git a/tests/test_hashdict.py b/tests/test_hashdict.py index c517f6a92..b9cc76a9a 100644 --- a/tests/test_hashdict.py +++ b/tests/test_hashdict.py | |||
| @@ -359,6 +359,32 @@ class CarveAndExtraCLITest(unittest.TestCase): | |||
| 359 | self.assertEqual(p_lookup.returncode, 0, p_lookup.stderr) | 359 | self.assertEqual(p_lookup.returncode, 0, p_lookup.stderr) |
| 360 | self.assertIn(f"{lookup_hash} model_prop", p_lookup.stdout) | 360 | self.assertIn(f"{lookup_hash} model_prop", p_lookup.stdout) |
| 361 | 361 | ||
| 362 | def test_one_archive_folder_is_harvested_as_that_archive(self): | ||
| 363 | # <work>/carve/common (its own index.json, as the gamedata_* tools take it) used to give an empty | ||
| 364 | # dictionary with exit 0: only <carve>/<archive>/index.json was looked for. | ||
| 365 | p = self.run_tool(os.path.join(self.carve_dir, "common"), "--out", self.out_json) | ||
| 366 | self.assertEqual(p.returncode, 0, p.stderr) | ||
| 367 | self.assertIn("common: ", p.stdout) | ||
| 368 | with open(self.out_json, encoding="utf-8") as f: | ||
| 369 | d = json.load(f) | ||
| 370 | self.assertEqual(d.get(f"{hashdict.joaat('common_archive_asset'):08x}"), "common_archive_asset") | ||
| 371 | self.assertNotIn(f"{hashdict.joaat('bink2_skipped_asset'):08x}", d) | ||
| 372 | # An archive outside --archives still contributes only its PSIN/RBF0 blobs. | ||
| 373 | p = self.run_tool(os.path.join(self.carve_dir, "custom_pack"), "--out", self.out_json) | ||
| 374 | self.assertEqual(p.returncode, 0, p.stderr) | ||
| 375 | with open(self.out_json, encoding="utf-8") as f: | ||
| 376 | self.assertEqual(json.load(f), {f"{hashdict.joaat('pso_metadata_token'):08x}": "pso_metadata_token"}) | ||
| 377 | |||
| 378 | def test_out_naming_a_one_archive_index_is_refused(self): | ||
| 379 | index = os.path.join(self.carve_dir, "common", "index.json") | ||
| 380 | with open(index, "rb") as f: | ||
| 381 | before = f.read() | ||
| 382 | p = self.run_tool(os.path.join(self.carve_dir, "common"), "--out", index) | ||
| 383 | self.assertEqual(p.returncode, 2, p.stderr) | ||
| 384 | self.assertIn("is one of the inputs", p.stderr) | ||
| 385 | with open(index, "rb") as f: | ||
| 386 | self.assertEqual(f.read(), before) | ||
| 387 | |||
| 362 | def test_build_requires_an_explicit_carve_directory(self): | 388 | def test_build_requires_an_explicit_carve_directory(self): |
| 363 | empty = os.path.join(self.dir, "empty") | 389 | empty = os.path.join(self.dir, "empty") |
| 364 | os.mkdir(empty) | 390 | os.mkdir(empty) |
diff --git a/tests/test_imhex_patterns.py b/tests/test_imhex_patterns.py new file mode 100644 index 000000000..751de8b90 --- /dev/null +++ b/tests/test_imhex_patterns.py | |||
| @@ -0,0 +1,256 @@ | |||
| 1 | """Tests for the ImHex patterns in tools/imhex. | ||
| 2 | |||
| 3 | python -I tests/test_imhex_patterns.py | ||
| 4 | |||
| 5 | Every byte here is built by the test: no game file, name or path is used. The RBF0 inputs are first checked with | ||
| 6 | tools/rbf0_index.py and the PSIN inputs with tools/psin_index.py and tools/psin_data.py, the repository's own | ||
| 7 | parsers (the PSIN schema reuses the invented names of tests/test_psin_index.py). When ImHex is installed, each pattern | ||
| 8 | then runs on the same bytes | ||
| 9 | through ImHex's pattern-language CLI (`imhex --pl format ... -f json`) and the decoded fields are compared with the | ||
| 10 | parser's result. ImHex is found through LEONIDA_IMHEX, then PATH, then its default Windows install folder; without it | ||
| 11 | the ImHex half is skipped and the rest still runs. | ||
| 12 | """ | ||
| 13 | import json | ||
| 14 | import os | ||
| 15 | import shutil | ||
| 16 | import struct | ||
| 17 | import subprocess | ||
| 18 | import sys | ||
| 19 | import tempfile | ||
| 20 | import unittest | ||
| 21 | |||
| 22 | ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | ||
| 23 | PATTERNS = os.path.join(ROOT, "tools", "imhex") | ||
| 24 | sys.path.insert(0, os.path.join(ROOT, "tools")) | ||
| 25 | sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) | ||
| 26 | |||
| 27 | import psin_data # noqa: E402 | ||
| 28 | import psin_index # noqa: E402 | ||
| 29 | import rbf0_index # noqa: E402 | ||
| 30 | from test_psin_index import SCHEMA as PSIN_SCHEMA, joaat, make_lenm, make_lsch, make_section # noqa: E402 | ||
| 31 | |||
| 32 | |||
| 33 | def find_imhex(): | ||
| 34 | candidates = [os.environ.get("LEONIDA_IMHEX"), shutil.which("imhex")] | ||
| 35 | if os.name == "nt": | ||
| 36 | candidates.append(os.path.join(os.environ.get("ProgramFiles", r"C:\Program Files"), "ImHex", "imhex.exe")) | ||
| 37 | for c in candidates: | ||
| 38 | if c and os.path.isfile(c): | ||
| 39 | return c | ||
| 40 | return None | ||
| 41 | |||
| 42 | |||
| 43 | IMHEX = find_imhex() | ||
| 44 | |||
| 45 | |||
| 46 | # ---- synthetic inputs ------------------------------------------------------------------------------------------ | ||
| 47 | |||
| 48 | def _name(name): | ||
| 49 | return struct.pack("<H", len(name)) + name | ||
| 50 | |||
| 51 | |||
| 52 | def rbf0_stream(wide): | ||
| 53 | """One resource with every record type of docs/rbf0.md section 3, then bytes past the root close.""" | ||
| 54 | q, d = ("Q", "d") if wide else ("I", "f") | ||
| 55 | q, d, d3 = "<" + q, "<" + d, "<" + d * 3 | ||
| 56 | out = b"RBF0" + (rbf0_index.PROLOGUE if wide else b"") | ||
| 57 | out += bytes([0, 0x00]) + _name(b"root") + struct.pack("<HHH", 0, 0, 1) | ||
| 58 | out += bytes([1, 0x10]) + _name(b"count") + struct.pack(q, 7) # the root's one attribute | ||
| 59 | out += bytes([2, 0x00]) + _name(b"item") + struct.pack("<HHH", 0, 0, 0) | ||
| 60 | out += bytes([3, 0x40]) + _name(b"scale") + struct.pack(d, 1.5) | ||
| 61 | out += bytes([4, 0x50]) + _name(b"pos") + struct.pack(d3, 1.0, -2.0, 0.25) | ||
| 62 | out += bytes([5, 0x60]) + _name(b"label") + struct.pack("<H", 5) + b"probe" | ||
| 63 | out += bytes([6, 0x20]) + _name(b"flag") + bytes([6, 0x30]) # new, then reused | ||
| 64 | out += bytes([3, 0x10]) + struct.pack(q, 9) # reused with another type | ||
| 65 | out += bytes([0xFD, 0xFF]) + struct.pack("<I", 5) + b"text\x00" | ||
| 66 | out += b"\xff\xff" # close item | ||
| 67 | out += b"\xff\xff" # close root: the end | ||
| 68 | return out + b"\x00\x11\x22\x33" # not part of the resource | ||
| 69 | |||
| 70 | |||
| 71 | def rpf9_archive(data_offset=0x100, size=0x140): | ||
| 72 | head = b"9FPR" + struct.pack("<III", data_offset, 0x11, 0x22) | ||
| 73 | toc = bytes((i * 37) & 0xFF for i in range(data_offset - len(head))) | ||
| 74 | body = b"\x78\x9c" + bytes(size - data_offset - 2) | ||
| 75 | return head + toc + body | ||
| 76 | |||
| 77 | |||
| 78 | PSIN_BLOCKS = [(PSIN_SCHEMA[0][0], bytes(range(0x20))), (0x10, b"probe\x00"), (0x16, struct.pack("<3Q", 1, 2, 3))] | ||
| 79 | PSIN_ENUMS = [(joaat("ProbeEnum"), 0x33333333, [(0, joaat("PROBE_A")), (-1, joaat("PROBE_B"))])] | ||
| 80 | LSNS_BLOCKS = [(0x101, 32), (0x207, 16)] | ||
| 81 | |||
| 82 | |||
| 83 | def psin_container(lsns=True): | ||
| 84 | """A complete container (docs/psin.md): block table, blocks, LSCH, LENM, LSNS, LGID, LRSC (root 1), CHKS.""" | ||
| 85 | rows = b"".join(struct.pack("<II", t, len(d)) + b"\xaa" * 8 for t, d in PSIN_BLOCKS) + b"\x70" * 8 | ||
| 86 | data = b"".join(d + bytes(-len(d) % 16) for _t, d in PSIN_BLOCKS) | ||
| 87 | first = 8 + len(rows) + len(data) | ||
| 88 | lsns_payload = struct.pack("<I", len(LSNS_BLOCKS)) + b"".join(struct.pack("<II", k, n) for k, n in LSNS_BLOCKS) | ||
| 89 | lsns_payload += bytes((i * 29) & 0xFF for i in range(sum(n for _k, n in LSNS_BLOCKS))) | ||
| 90 | lrsc = b"0DRP" + struct.pack("<I", 122) + bytes(8) + struct.pack("<I", 1) + bytes(12) | ||
| 91 | sections = make_section("LSCH", make_lsch(PSIN_SCHEMA)) + make_section("LENM", make_lenm(PSIN_ENUMS)) | ||
| 92 | if lsns: | ||
| 93 | sections += make_section("LSNS", lsns_payload) | ||
| 94 | sections += make_section("LGID") + make_section("LRSC", lrsc) | ||
| 95 | sections += make_section("CHKS", struct.pack(">I", first + len(sections) + 16) + b"\x12\x34\x56\x78") | ||
| 96 | return b"PSIN" + struct.pack(">I", first) + rows + data + sections | ||
| 97 | |||
| 98 | |||
| 99 | def pragma_magic(pattern): | ||
| 100 | """The bytes of `#pragma magic [ .. ] @ 0x00` in a pattern file.""" | ||
| 101 | with open(os.path.join(PATTERNS, pattern), encoding="utf-8") as f: | ||
| 102 | for line in f: | ||
| 103 | if line.startswith("#pragma magic"): | ||
| 104 | inside = line[line.index("[") + 1:line.index("]")] | ||
| 105 | return bytes(int(b, 16) for b in inside.split()) | ||
| 106 | return None | ||
| 107 | |||
| 108 | |||
| 109 | # ---- tests ----------------------------------------------------------------------------------------------------- | ||
| 110 | |||
| 111 | class InputsAndMagic(unittest.TestCase): | ||
| 112 | """Runs everywhere: the synthetic inputs are valid RBF0 by the repository's parser, and the magics agree.""" | ||
| 113 | |||
| 114 | def test_synthetic_streams_parse(self): | ||
| 115 | for wide in (True, False): | ||
| 116 | r = rbf0_index.parse_rbf0(rbf0_stream(wide)[:-4]) | ||
| 117 | self.assertEqual(r["status"], "ok", r["error"]) | ||
| 118 | self.assertEqual(r["layout"], "wide-64" if wide else "narrow-32") | ||
| 119 | self.assertEqual(r["elements"], 2) | ||
| 120 | self.assertEqual(r["descriptors"], 7) | ||
| 121 | |||
| 122 | def test_synthetic_psin_parses(self): | ||
| 123 | blob = psin_container() | ||
| 124 | r = psin_index.parse(blob, schema=True) | ||
| 125 | self.assertTrue(r["complete"], r["error"]) | ||
| 126 | self.assertEqual(r["schema"]["reason"], "") | ||
| 127 | self.assertEqual(r["lsns_blocks"], len(LSNS_BLOCKS)) | ||
| 128 | blocks, exact = psin_data.block_table(blob, r["first_section"]) | ||
| 129 | self.assertTrue(exact) | ||
| 130 | self.assertEqual([(t, n) for t, _at, n in blocks], [(t, len(d)) for t, d in PSIN_BLOCKS]) | ||
| 131 | |||
| 132 | def test_pattern_magics(self): | ||
| 133 | self.assertEqual(pragma_magic("rbf0.hexpat"), rbf0_index.MAGIC) | ||
| 134 | self.assertEqual(pragma_magic("rpf9.hexpat"), b"9FPR") # RPF9 stored little-endian (docs/rpf.md) | ||
| 135 | self.assertEqual(pragma_magic("psin.hexpat"), psin_index.MAGIC) | ||
| 136 | |||
| 137 | |||
| 138 | @unittest.skipUnless(IMHEX, "ImHex is not installed (set LEONIDA_IMHEX to imhex.exe)") | ||
| 139 | class PatternsInImHex(unittest.TestCase): | ||
| 140 | def setUp(self): | ||
| 141 | self.tmp = tempfile.TemporaryDirectory() | ||
| 142 | self.addCleanup(self.tmp.cleanup) | ||
| 143 | |||
| 144 | def run_pattern(self, pattern, data): | ||
| 145 | """Returns (decoded JSON or None, combined output).""" | ||
| 146 | src = os.path.join(self.tmp.name, "input.bin") | ||
| 147 | out = os.path.join(self.tmp.name, "out.json") | ||
| 148 | if os.path.exists(out): | ||
| 149 | os.remove(out) | ||
| 150 | with open(src, "wb") as f: | ||
| 151 | f.write(data) | ||
| 152 | cmd = [IMHEX, "--pl", "format", "-i", src, "-p", os.path.join(PATTERNS, pattern), "-o", out, "-f", "json"] | ||
| 153 | includes = os.path.join(os.path.dirname(IMHEX), "includes") | ||
| 154 | if os.path.isdir(includes): | ||
| 155 | cmd += ["-I", includes] | ||
| 156 | p = subprocess.run(cmd, capture_output=True, text=True, timeout=120) | ||
| 157 | log = p.stdout + p.stderr | ||
| 158 | if not os.path.exists(out): | ||
| 159 | return None, log | ||
| 160 | with open(out, encoding="utf-8") as f: | ||
| 161 | return json.load(f), log | ||
| 162 | |||
| 163 | def check_rbf0(self, wide): | ||
| 164 | data = rbf0_stream(wide) | ||
| 165 | ref = rbf0_index.parse_rbf0(data[:-4]) | ||
| 166 | got, log = self.run_pattern("rbf0.hexpat", data) | ||
| 167 | self.assertIsNotNone(got, log) | ||
| 168 | self.assertEqual("prologue" in got["header"], wide) | ||
| 169 | records = got["records"] | ||
| 170 | |||
| 171 | names = [r["name"] for r in records if "name" in r] | ||
| 172 | self.assertEqual(names, ref["descriptor_names"]) | ||
| 173 | self.assertEqual(sum(1 for r in records if r["index"] < 0xFD and r["type"] == 0x00), ref["elements"]) | ||
| 174 | ints = [r["value_int"] for r in records if "value_int" in r] | ||
| 175 | self.assertEqual(ints, ref["ints"]) | ||
| 176 | floats = [] | ||
| 177 | for r in records: | ||
| 178 | floats += [r["value_float"]] if "value_float" in r else r.get("value_vec3", []) | ||
| 179 | self.assertEqual(floats, ref["floats"]) | ||
| 180 | strings = [r.get("value_string", r.get("text", "")) for r in records if "value_string" in r or "text" in r] | ||
| 181 | self.assertEqual([s.split("%00")[0] for s in strings], ref["strings"]) | ||
| 182 | self.assertEqual([r["attribute_count"] for r in records if "attribute_count" in r], [1, 0]) | ||
| 183 | # The pattern stops where the root closes, as parse_rbf0 does: the 4 trailing bytes are not records. | ||
| 184 | self.assertEqual(records[-1]["index"], 0xFF) | ||
| 185 | self.assertEqual(sum(1 for r in records if r["index"] == 0xFF), 2) | ||
| 186 | |||
| 187 | def test_rbf0_wide(self): | ||
| 188 | self.check_rbf0(wide=True) | ||
| 189 | |||
| 190 | def test_rbf0_narrow(self): | ||
| 191 | self.check_rbf0(wide=False) | ||
| 192 | |||
| 193 | def test_rpf9_header_and_opaque_toc(self): | ||
| 194 | got, log = self.run_pattern("rpf9.hexpat", rpf9_archive(data_offset=0x100)) | ||
| 195 | self.assertIsNotNone(got, log) | ||
| 196 | self.assertEqual(got["header"]["magic"], "9FPR") | ||
| 197 | self.assertEqual(got["header"]["data_offset"], 0x100) | ||
| 198 | self.assertEqual((got["header"]["u32_08"], got["header"]["u32_0c"]), (0x11, 0x22)) | ||
| 199 | self.assertEqual(len(got["header_rest_and_toc"]), 0x100 - 0x10) | ||
| 200 | |||
| 201 | def test_psin_matches_psin_index_and_psin_data(self): | ||
| 202 | blob = psin_container() | ||
| 203 | ref = psin_index.parse(blob, schema=True) | ||
| 204 | table, _exact = psin_data.block_table(blob, ref["first_section"]) | ||
| 205 | got, log = self.run_pattern("psin.hexpat", blob) | ||
| 206 | self.assertIsNotNone(got, log) | ||
| 207 | self.assertEqual(got["header"]["first_section"], ref["first_section"]) | ||
| 208 | |||
| 209 | # Block table: rows, the "pppppppp" end, and each block's data where psin_data places it. | ||
| 210 | self.assertEqual([(r["type"], r["size"]) for r in got["rows"]], [(t, n) for t, _at, n in table]) | ||
| 211 | self.assertEqual(got["table_end"], "pppppppp") | ||
| 212 | self.assertEqual([bytes(b["data"]) for b in got["blocks"]], [blob[at:at + n] for _t, at, n in table]) | ||
| 213 | |||
| 214 | sections = {s["tag"]: s for s in got["sections"]} | ||
| 215 | self.assertEqual([(s["tag"], s["size"]) for s in got["sections"]], | ||
| 216 | [(s["tag"], s["size"]) for s in ref["sections"]]) | ||
| 217 | schema = ref["schema"] | ||
| 218 | self.assertEqual([s["name_hash"] for s in sections["LSCH"]["structs"]], | ||
| 219 | [int(s["hash"], 16) for s in schema["structs"]]) | ||
| 220 | self.assertEqual([(m["name_hash"], m["offset"], m["type"], m["index"], m["ref_hash"]) | ||
| 221 | for m in sections["LSCH"]["members"]], | ||
| 222 | [(int(m["hash"], 16), m["offset"], m["type"], m["index"], int(m["ref"], 16)) | ||
| 223 | for s in schema["structs"] for m in s["members"]]) | ||
| 224 | self.assertEqual([e["value_count"] for e in sections["LENM"]["enums"]], | ||
| 225 | [len(e["values"]) for e in schema["enums"]]) | ||
| 226 | self.assertEqual([v["value"] for v in sections["LENM"]["values"]], | ||
| 227 | [v["value"] for e in schema["enums"] for v in e["values"]]) | ||
| 228 | lsns = next(s for s in ref["sections"] if s["tag"] == "LSNS") | ||
| 229 | self.assertEqual([(d["kind"], d["bytes"]) for d in sections["LSNS"]["descs"]], | ||
| 230 | [(int(b["kind"], 16), b["bytes"]) for b in lsns["blocks"]]) | ||
| 231 | self.assertEqual([len(b["records"]) for b in sections["LSNS"]["lsns_blocks"]], [n // 16 for _k, n in LSNS_BLOCKS]) | ||
| 232 | self.assertEqual(sections["LRSC"]["rsc_version"], ref["rsc_version"]) | ||
| 233 | self.assertEqual(sections["LRSC"]["root_block"], 1) | ||
| 234 | self.assertEqual(sections["CHKS"]["checksum_size"], ref["checksum_size"]) | ||
| 235 | |||
| 236 | def test_psin_truncated_keeps_the_whole_sections(self): | ||
| 237 | blob = psin_container(lsns=False) | ||
| 238 | first = struct.unpack_from(">I", blob, 4)[0] | ||
| 239 | lsch_size = struct.unpack_from(">I", blob, first + 4)[0] | ||
| 240 | cut = blob[:first + lsch_size + 20] # inside LENM | ||
| 241 | self.assertFalse(psin_index.parse(cut)["complete"]) | ||
| 242 | got, log = self.run_pattern("psin.hexpat", cut) | ||
| 243 | self.assertIsNotNone(got, log) | ||
| 244 | tags = [s["tag"] for s in got["sections"]] | ||
| 245 | self.assertEqual(tags, ["LSCH", "LENM"]) | ||
| 246 | self.assertIn("structs", got["sections"][0]) | ||
| 247 | self.assertEqual(len(got["sections"][1]["truncated"]), 12) # what is left after LENM's 8-byte header | ||
| 248 | |||
| 249 | def test_rpf9_rejects_a_data_offset_past_the_end(self): | ||
| 250 | got, log = self.run_pattern("rpf9.hexpat", rpf9_archive(data_offset=0x100, size=0x140)[:0x20]) | ||
| 251 | self.assertIsNone(got) | ||
| 252 | self.assertIn("data offset is outside the file", log) | ||
| 253 | |||
| 254 | |||
| 255 | if __name__ == "__main__": | ||
| 256 | unittest.main() | ||
diff --git a/tests/test_int_hw_probe.py b/tests/test_int_hw_probe.py new file mode 100644 index 000000000..69336702b --- /dev/null +++ b/tests/test_int_hw_probe.py | |||
| @@ -0,0 +1,126 @@ | |||
| 1 | """Unit tests for tools/int_hw_probe.py (SHADER-137). Standard library only; no GPU or game files needed.""" | ||
| 2 | import io | ||
| 3 | import json | ||
| 4 | import os | ||
| 5 | import sys | ||
| 6 | import tempfile | ||
| 7 | import unittest | ||
| 8 | import unittest.mock | ||
| 9 | from contextlib import redirect_stderr, redirect_stdout | ||
| 10 | from pathlib import Path | ||
| 11 | |||
| 12 | ROOT = Path(__file__).resolve().parents[1] | ||
| 13 | TOOLS = ROOT / "tools" | ||
| 14 | sys.dont_write_bytecode = True | ||
| 15 | if str(TOOLS) not in sys.path: | ||
| 16 | sys.path.insert(0, str(TOOLS)) | ||
| 17 | |||
| 18 | import int_hw_probe as probe # noqa: E402 | ||
| 19 | from hw_oracle import runner as hw_runner # noqa: E402 | ||
| 20 | |||
| 21 | |||
| 22 | class IntHwProbeTests(unittest.TestCase): | ||
| 23 | def test_cases_unique_and_nonempty(self): | ||
| 24 | cases = probe.build_cases() | ||
| 25 | self.assertGreaterEqual(len(cases), 80) | ||
| 26 | names = [c.name for c in cases] | ||
| 27 | self.assertEqual(len(names), len(set(names))) | ||
| 28 | groups = {c.group for c in cases} | ||
| 29 | self.assertGreaterEqual(len(groups), 19) | ||
| 30 | for key in probe.KNOWN_DIVERGENCES: | ||
| 31 | self.assertIn(key, names) | ||
| 32 | |||
| 33 | def test_wave32_and_wave64_placeholder_expansion(self): | ||
| 34 | by_name = {c.name: c for c in probe.build_cases()} | ||
| 35 | c = by_name["v_mad_u64_u32_inactive_lane"] | ||
| 36 | w32 = "\n".join(c.lines(wave=32)) | ||
| 37 | w64 = "\n".join(c.lines(wave=64)) | ||
| 38 | self.assertIn("s_mov_b32 s14, exec_lo", w32) | ||
| 39 | self.assertIn("v_mad_u64_u32 v[8:9], vcc_lo", w32) | ||
| 40 | self.assertIn("s_mov_b64 s[14:15], exec", w64) | ||
| 41 | self.assertIn("v_mad_u64_u32 v[8:9], vcc,", w64) | ||
| 42 | self.assertNotIn("{", w32) | ||
| 43 | self.assertNotIn("{", w64) | ||
| 44 | |||
| 45 | def test_self_test_and_translator_groups(self): | ||
| 46 | buf = io.StringIO() | ||
| 47 | with redirect_stdout(buf): | ||
| 48 | rc = probe.main(["--self-test"]) | ||
| 49 | self.assertEqual(rc, 0) | ||
| 50 | self.assertIn("self-test:", buf.getvalue()) | ||
| 51 | |||
| 52 | def test_list_groups_and_unknown_group(self): | ||
| 53 | out, err = io.StringIO(), io.StringIO() | ||
| 54 | with redirect_stdout(out): | ||
| 55 | rc = probe.main(["--list-groups"]) | ||
| 56 | self.assertEqual(rc, 0) | ||
| 57 | self.assertIn("valu_cvt_pknorm", out.getvalue()) | ||
| 58 | |||
| 59 | with redirect_stderr(err): | ||
| 60 | rc = probe.main(["--group", "does_not_exist"]) | ||
| 61 | self.assertEqual(rc, 2) | ||
| 62 | self.assertIn("unknown group", err.getvalue()) | ||
| 63 | |||
| 64 | def test_hw_unavailable_returns_77(self): | ||
| 65 | err = io.StringIO() | ||
| 66 | with unittest.mock.patch.object(hw_runner, "open_oracle", side_effect=hw_runner.Unavailable("no GPU")): | ||
| 67 | with redirect_stderr(err): | ||
| 68 | rc = probe.main(["--oracle", "hw", "--group", "salu_bfe_past31"]) | ||
| 69 | self.assertEqual(rc, 77) | ||
| 70 | self.assertIn("no GPU", err.getvalue()) | ||
| 71 | |||
| 72 | def test_known_divergence_vs_strict_and_json_output(self): | ||
| 73 | # Mock hardware oracle returning the measured gfx1035 words for valu_cvt_flr_rpi. | ||
| 74 | measured = { | ||
| 75 | "v_cvt_rpi_precision": [0x00000000, 0x00800001, 0x00FFFFFF, 0x00000000], | ||
| 76 | "v_cvt_flr_rpi_nan_inf": [0x7FFFFFFF, 0x80000000, 0x7FFFFFFF, 0x80000000], | ||
| 77 | "v_cvt_i32_f32_nan_control": [0x00000000, 0x00000000, 0x00000000, 0x00000000], | ||
| 78 | "v_cvt_flr_edges": [0xFFFFFFFE, 0x7FFFFFFF, 0x80000000, 0x7FFFFFFF], | ||
| 79 | } | ||
| 80 | fake_hw = ("device=mock arch=gfx1035", {32: measured, 64: measured}) | ||
| 81 | with tempfile.TemporaryDirectory() as tmp: | ||
| 82 | jpath = os.path.join(tmp, "out.json") | ||
| 83 | out = io.StringIO() | ||
| 84 | # The table is empty since #1831/#1856 fixed the measured divergences, so give the reporting path one: the | ||
| 85 | # "hardware" returns other words for v_cvt_flr_edges, and the table lists them as a known divergence. | ||
| 86 | fake_hw[1][32]["v_cvt_flr_edges"] = fake_hw[1][64]["v_cvt_flr_edges"] = [1, 2, 3, 4] | ||
| 87 | known = {"v_cvt_flr_edges": ("synthetic", [1, 2, 3, 4], "test-only divergence")} | ||
| 88 | patch_known = unittest.mock.patch.dict(probe.KNOWN_DIVERGENCES, known) | ||
| 89 | patch_known.start() | ||
| 90 | self.addCleanup(patch_known.stop) | ||
| 91 | with unittest.mock.patch.object(probe, "run_hw", return_value=fake_hw): | ||
| 92 | with redirect_stdout(out): | ||
| 93 | rc = probe.main(["--oracle", "both", "--group", "valu_cvt_flr_rpi", "--json", jpath]) | ||
| 94 | self.assertEqual(rc, 0) | ||
| 95 | self.assertIn("3 match, 1 known divergence, 0 unexpected mismatch, 0 wave32/64 diff", out.getvalue()) | ||
| 96 | data = json.loads(Path(jpath).read_text(encoding="utf-8")) | ||
| 97 | self.assertEqual(data["device"], "device=mock arch=gfx1035") | ||
| 98 | self.assertEqual(len(data["cases"]), 4) | ||
| 99 | |||
| 100 | out2 = io.StringIO() | ||
| 101 | with unittest.mock.patch.object(probe, "run_hw", return_value=fake_hw): | ||
| 102 | with redirect_stdout(out2): | ||
| 103 | rc_strict = probe.main(["--oracle", "both", "--group", "valu_cvt_flr_rpi", "--strict"]) | ||
| 104 | self.assertEqual(rc_strict, 1) | ||
| 105 | |||
| 106 | err = io.StringIO() | ||
| 107 | with unittest.mock.patch.object(probe, "run_hw", return_value=fake_hw): | ||
| 108 | with redirect_stderr(err): | ||
| 109 | rc_dir = probe.main(["--oracle", "both", "--group", "valu_cvt_flr_rpi", "--json", tmp]) | ||
| 110 | self.assertEqual(rc_dir, 2) | ||
| 111 | |||
| 112 | def test_unexpected_mismatch_and_wave_diff_fail(self): | ||
| 113 | bad_hw = ("device=mock arch=gfx1035", { | ||
| 114 | 32: {"s_bfe_i32_past31": [1, 2, 3, 4], "s_bfe_u32_past31": [0, 0, 0, 0], "s_bfe_i32_width0": [0, 0, 0, 0]}, | ||
| 115 | 64: {"s_bfe_i32_past31": [1, 2, 3, 5], "s_bfe_u32_past31": [0, 0, 0, 0], "s_bfe_i32_width0": [0, 0, 0, 0]}, | ||
| 116 | }) | ||
| 117 | out = io.StringIO() | ||
| 118 | with unittest.mock.patch.object(probe, "run_hw", return_value=bad_hw): | ||
| 119 | with redirect_stdout(out): | ||
| 120 | rc = probe.main(["--oracle", "both", "--group", "salu_bfe_past31"]) | ||
| 121 | self.assertEqual(rc, 1) | ||
| 122 | self.assertIn("WAVE_DIFF", out.getvalue()) | ||
| 123 | |||
| 124 | |||
| 125 | if __name__ == "__main__": | ||
| 126 | unittest.main() | ||
diff --git a/tests/test_lds_fuzz.py b/tests/test_lds_fuzz.py index e59020c2c..3c286e45b 100644 --- a/tests/test_lds_fuzz.py +++ b/tests/test_lds_fuzz.py | |||
| @@ -85,6 +85,24 @@ class Generator(unittest.TestCase): | |||
| 85 | else: | 85 | else: |
| 86 | self.assertEqual(x, y) | 86 | self.assertEqual(x, y) |
| 87 | 87 | ||
| 88 | def test_permute_is_generated_and_no_exec_clears_only_permute(self): | ||
| 89 | self.assertIn("permute", f.EXEC_KINDS) | ||
| 90 | found = 0 | ||
| 91 | for idx in range(40): | ||
| 92 | a = f.Program(1, idx, 64, permute=True) | ||
| 93 | b = f.Program(1, idx, 64, no_exec=("permute",), permute=True) | ||
| 94 | self.assertEqual(len(a.ops), len(b.ops)) | ||
| 95 | for x, y in zip(a.ops, b.ops): | ||
| 96 | if x["kind"] == "permute": | ||
| 97 | if x["exec"] is not None: | ||
| 98 | found += 1 | ||
| 99 | self.assertIsNone(y["exec"]) | ||
| 100 | self.assertEqual({k: v for k, v in x.items() if k not in ("exec", "hyp")}, | ||
| 101 | {k: v for k, v in y.items() if k not in ("exec", "hyp")}) | ||
| 102 | else: | ||
| 103 | self.assertEqual(x, y) | ||
| 104 | self.assertGreater(found, 0, "expected at least one permute op with non-None exec mask") | ||
| 105 | |||
| 88 | 106 | ||
| 89 | class Model(unittest.TestCase): | 107 | class Model(unittest.TestCase): |
| 90 | def test_initial_lds_pattern(self): | 108 | def test_initial_lds_pattern(self): |
| @@ -104,6 +122,48 @@ class Model(unittest.TestCase): | |||
| 104 | keep.ops = [] | 122 | keep.ops = [] |
| 105 | self.assertEqual(regs[9][21], keep.model()[0][9][21]) # lane 9 is off itself: keeps its value | 123 | self.assertEqual(regs[9][21], keep.model()[0][9][21]) # lane 9 is off itself: keeps its value |
| 106 | 124 | ||
| 125 | def test_permute_collision_highest_active_wins_and_unaddressed_is_zero(self): | ||
| 126 | # All active lanes scatter to lane 5 in their own 32-lane half (mul=0, add=5, offset=0). | ||
| 127 | # EXEC: low half has lanes 0..7 active (highest active = 7); high half has lanes 32, 35, 40 active (highest = 40). | ||
| 128 | mask = 0xFF | (1 << 32) | (1 << 35) | (1 << 40) | ||
| 129 | p = f.Program(1, 0, 64) | ||
| 130 | p.ops = [{"kind": "permute", "mul": 0, "add": 5, "offset": 0, "src": 20, "dst": 21, "exec": mask}] | ||
| 131 | base = f.Program(1, 0, 64) | ||
| 132 | base.ops = [] | ||
| 133 | init_regs, _ = base.model() | ||
| 134 | regs, _ = p.model() | ||
| 135 | |||
| 136 | # Low half: lane 5 is active and receives highest active source (lane 7). | ||
| 137 | self.assertEqual(regs[5][21], init_regs[7][20]) | ||
| 138 | # Low half: active lanes != 5 receive nobody -> 0. | ||
| 139 | for t in (0, 1, 2, 3, 4, 6, 7): | ||
| 140 | self.assertEqual(regs[t][21], 0) | ||
| 141 | # Low half: inactive lanes keep their original v21. | ||
| 142 | for t in (8, 15, 31): | ||
| 143 | self.assertEqual(regs[t][21], init_regs[t][21]) | ||
| 144 | # High half: target lane 32+5=37 is INACTIVE, so it keeps its original v21 even though 32,35,40 targeted it. | ||
| 145 | self.assertEqual(regs[37][21], init_regs[37][21]) | ||
| 146 | # High half: active lanes 32, 35, 40 receive nobody -> 0. | ||
| 147 | for t in (32, 35, 40): | ||
| 148 | self.assertEqual(regs[t][21], 0) | ||
| 149 | self.assertIn("ds_permute_b32 v21, v6, v20 offset:0", p.asm()) | ||
| 150 | |||
| 151 | with f.perturbed("permute_lowest_wins"): | ||
| 152 | bad_regs, _ = p.model() | ||
| 153 | self.assertEqual(bad_regs[5][21], init_regs[0][20]) | ||
| 154 | |||
| 155 | def test_permute_half_isolation_and_offset(self): | ||
| 156 | # Identity + offset:8 (+2 lanes) mod 32 within each 32-lane half, all lanes active. | ||
| 157 | p = f.Program(2, 1, 64) | ||
| 158 | p.ops = [{"kind": "permute", "mul": 1, "add": 0, "offset": 8, "src": 20, "dst": 22, "exec": None}] | ||
| 159 | base = f.Program(2, 1, 64) | ||
| 160 | base.ops = [] | ||
| 161 | init_regs, _ = base.model() | ||
| 162 | regs, _ = p.model() | ||
| 163 | for t in range(64): | ||
| 164 | src_lane = (t & ~31) | ((t - 2) & 31) | ||
| 165 | self.assertEqual(regs[t][22], init_regs[src_lane][20]) | ||
| 166 | |||
| 107 | def test_d16_hi_read_keeps_the_low_half(self): | 167 | def test_d16_hi_read_keeps_the_low_half(self): |
| 108 | p = f.Program(1, 0, 64) | 168 | p = f.Program(1, 0, 64) |
| 109 | p.ops = [{"kind": "read", "name": "ds_read_u16_d16_hi", "addr": (0, 0, 0), "dst": 20, "exec": None}] | 169 | p.ops = [{"kind": "read", "name": "ds_read_u16_d16_hi", "addr": (0, 0, 0), "dst": 20, "exec": None}] |
diff --git a/tests/test_lds_fuzz_hw.py b/tests/test_lds_fuzz_hw.py index 6041abfda..986fddbb3 100644 --- a/tests/test_lds_fuzz_hw.py +++ b/tests/test_lds_fuzz_hw.py | |||
| @@ -122,11 +122,13 @@ class OpMix(unittest.TestCase): | |||
| 122 | progs = f.programs(3, 40, (64, 32), permute=True) | 122 | progs = f.programs(3, 40, (64, 32), permute=True) |
| 123 | perm = [p for p in progs if any(op["kind"] == "permute" for op in p.ops)] | 123 | perm = [p for p in progs if any(op["kind"] == "permute" for op in p.ops)] |
| 124 | self.assertTrue(perm) | 124 | self.assertTrue(perm) |
| 125 | parities = set() | ||
| 125 | for p in perm: | 126 | for p in perm: |
| 126 | for i, op in enumerate(p.ops): | 127 | for i, op in enumerate(p.ops): |
| 127 | self.assertEqual(i in p.hyp_ops, op["kind"] == "permute") | 128 | self.assertEqual(i in p.hyp_ops, op["kind"] == "permute") |
| 128 | if op["kind"] == "permute": | 129 | if op["kind"] == "permute": |
| 129 | self.assertEqual(op["mul"] % 2, 1) # a bijection: no two lanes send to one lane | 130 | parities.add(op["mul"] % 2) |
| 131 | self.assertEqual(parities, {0, 1}) # generates both colliding and bijective multipliers | ||
| 130 | 132 | ||
| 131 | def test_swizzle_exec_hypothesis_only_under_a_mask(self): | 133 | def test_swizzle_exec_hypothesis_only_under_a_mask(self): |
| 132 | progs = f.programs(3, 60, (32,), swizzle_exec=True) | 134 | progs = f.programs(3, 60, (32,), swizzle_exec=True) |
diff --git a/tests/test_make_game_assets_pools.py b/tests/test_make_game_assets_pools.py index 9716b5ad7..0de945dfe 100644 --- a/tests/test_make_game_assets_pools.py +++ b/tests/test_make_game_assets_pools.py | |||
| @@ -39,7 +39,7 @@ class AssetsPoolsTest(unittest.TestCase): | |||
| 39 | pass | 39 | pass |
| 40 | 40 | ||
| 41 | def pool(self, rel, size=100): | 41 | def pool(self, rel, size=100): |
| 42 | path = os.path.join(self.game, rel) | 42 | path = os.path.join(self.game, *rel.split("/")) |
| 43 | os.makedirs(os.path.dirname(path), exist_ok=True) | 43 | os.makedirs(os.path.dirname(path), exist_ok=True) |
| 44 | with open(path, "wb") as f: | 44 | with open(path, "wb") as f: |
| 45 | f.write(b"x" * size) | 45 | f.write(b"x" * size) |
diff --git a/tests/test_make_game_preflight.py b/tests/test_make_game_preflight.py index eb6964bb1..540d0b0e3 100644 --- a/tests/test_make_game_preflight.py +++ b/tests/test_make_game_preflight.py | |||
| @@ -654,9 +654,41 @@ class PathAndGameSelectionTest(PreflightTestBase): | |||
| 654 | self.assert_fails(make_game.choose_game, | 654 | self.assert_fails(make_game.choose_game, |
| 655 | match="More than one copy found: choose one with --game.") | 655 | match="More than one copy found: choose one with --game.") |
| 656 | 656 | ||
| 657 | def default_out_in(self, platform, icloud_documents, earlier_build=False, call=None): | ||
| 658 | """default_out() (or `call`) with a temporary home folder; icloud_documents makes the folder macOS keeps in | ||
| 659 | iCloud Drive when Desktop & Documents sync is on (~/Library/Mobile Documents/com~apple~CloudDocs/Documents), | ||
| 660 | earlier_build a ~/Documents/Leonida from before the change.""" | ||
| 661 | with tempfile.TemporaryDirectory() as home: | ||
| 662 | if icloud_documents: | ||
| 663 | os.makedirs(os.path.join(home, "Library", "Mobile Documents", "com~apple~CloudDocs", "Documents")) | ||
| 664 | if earlier_build: | ||
| 665 | os.makedirs(os.path.join(home, "Documents", "Leonida", "work")) | ||
| 666 | with mock.patch.object(make_game.os.path, "expanduser", lambda p: home + p[1:] if p.startswith("~") else p), \ | ||
| 667 | mock.patch.object(make_game.sys, "platform", platform): | ||
| 668 | if call: | ||
| 669 | return [note.replace(home, "~") for note in call()] | ||
| 670 | return os.path.relpath(make_game.default_out(), home) | ||
| 671 | |||
| 672 | def test_icloud_note_names_an_earlier_build_in_documents(self): | ||
| 673 | # A Mac that built into ~/Documents/Leonida before the default moved: say where that resumable build is. | ||
| 674 | notes = self.default_out_in("darwin", True, earlier_build=True, call=make_game.icloud_default_notes) | ||
| 675 | self.assertEqual(len(notes), 2, notes) | ||
| 676 | self.assertIn("off iCloud", notes[0]) | ||
| 677 | self.assertIn(os.path.join("~", "Documents", "Leonida"), notes[1]) | ||
| 678 | self.assertIn(os.path.join("~", "Leonida") + " to resume", notes[1]) | ||
| 679 | self.assertIn("--out", notes[1]) | ||
| 680 | self.assertEqual(len(self.default_out_in("darwin", True, call=make_game.icloud_default_notes)), 1) | ||
| 681 | |||
| 657 | def test_default_out_matches_documents_folder(self): | 682 | def test_default_out_matches_documents_folder(self): |
| 658 | expected = os.path.join(os.path.expanduser("~"), "Documents", "Leonida") | 683 | for platform in ("win32", "linux", "darwin"): |
| 659 | self.assertEqual(make_game.default_out(), expected) | 684 | self.assertEqual(self.default_out_in(platform, False), os.path.join("Documents", "Leonida"), platform) |
| 685 | |||
| 686 | def test_default_out_leaves_icloud_synced_documents_on_a_mac(self): | ||
| 687 | # Before: with iCloud Desktop & Documents sync on, ~/Documents/Leonida (and its work folder, hundreds of GB | ||
| 688 | # made from the game) went into iCloud Drive, which uploads it and can evict the work files from the disk. | ||
| 689 | self.assertEqual(self.default_out_in("darwin", True), "Leonida") | ||
| 690 | # Only macOS keeps Documents in iCloud Drive this way; elsewhere the folder means nothing. | ||
| 691 | self.assertEqual(self.default_out_in("linux", True), os.path.join("Documents", "Leonida")) | ||
| 660 | 692 | ||
| 661 | def test_constants_definitions(self): | 693 | def test_constants_definitions(self): |
| 662 | self.assertEqual(make_game.STAGES, ["check", "shaders", "assets", "runtime", "pipelines"]) | 694 | self.assertEqual(make_game.STAGES, ["check", "shaders", "assets", "runtime", "pipelines"]) |
diff --git a/tests/test_manifest.py b/tests/test_manifest.py index ae335871a..52afc1cbc 100644 --- a/tests/test_manifest.py +++ b/tests/test_manifest.py | |||
| @@ -401,9 +401,9 @@ class ManifestAtomicCreateTest(unittest.TestCase): | |||
| 401 | f.write(b"atomic create payload") | 401 | f.write(b"atomic create payload") |
| 402 | self.out = os.path.join(self.tmp.name, "manifest.json") | 402 | self.out = os.path.join(self.tmp.name, "manifest.json") |
| 403 | 403 | ||
| 404 | def create(self): | 404 | def create(self, jobs=1): |
| 405 | with contextlib.redirect_stdout(io.StringIO()): | 405 | with contextlib.redirect_stdout(io.StringIO()): |
| 406 | return manifest.create(self.pkg, self.out, jobs=1) | 406 | return manifest.create(self.pkg, self.out, jobs=jobs) |
| 407 | 407 | ||
| 408 | def test_create_preserves_an_existing_partial_sibling(self): | 408 | def test_create_preserves_an_existing_partial_sibling(self): |
| 409 | sibling = self.out + ".partial" | 409 | sibling = self.out + ".partial" |
| @@ -452,6 +452,55 @@ class ManifestAtomicCreateTest(unittest.TestCase): | |||
| 452 | self.assertEqual(self.create(), 0) | 452 | self.assertEqual(self.create(), 0) |
| 453 | self.assertEqual(sorted(manifest.load_manifest(self.out)), ["added.dat", "sample.dat"]) | 453 | self.assertEqual(sorted(manifest.load_manifest(self.out)), ["added.dat", "sample.dat"]) |
| 454 | 454 | ||
| 455 | def test_size_change_before_open_keeps_the_previous_manifest(self): | ||
| 456 | self.assertEqual(self.create(), 0) | ||
| 457 | with open(self.out, "rb") as f: | ||
| 458 | previous = f.read() | ||
| 459 | source = os.path.join(self.pkg, "sample.dat") | ||
| 460 | |||
| 461 | def open_after_growth(path, mode, **kwargs): | ||
| 462 | if path == source and mode == "rb": | ||
| 463 | with open(source, "ab") as f: | ||
| 464 | f.write(b"more bytes") | ||
| 465 | return open(path, mode, **kwargs) | ||
| 466 | |||
| 467 | for jobs in (1, 2): | ||
| 468 | with self.subTest(jobs=jobs): | ||
| 469 | with patch.object(manifest, "open", side_effect=open_after_growth, create=True): | ||
| 470 | with self.assertRaisesRegex(manifest.ManifestError, r"sample\.dat.*changed"): | ||
| 471 | self.create(jobs=jobs) | ||
| 472 | with open(self.out, "rb") as f: | ||
| 473 | self.assertEqual(f.read(), previous) | ||
| 474 | |||
| 475 | def test_same_size_change_during_read_keeps_the_previous_manifest(self): | ||
| 476 | self.assertEqual(self.create(), 0) | ||
| 477 | with open(self.out, "rb") as f: | ||
| 478 | previous = f.read() | ||
| 479 | source = os.path.join(self.pkg, "sample.dat") | ||
| 480 | |||
| 481 | def open_with_edit(path, mode, **kwargs): | ||
| 482 | stream = open(path, mode, **kwargs) | ||
| 483 | if path == source and mode == "rb": | ||
| 484 | original_read = stream.read | ||
| 485 | |||
| 486 | def read_then_edit(size): | ||
| 487 | chunk = original_read(size) | ||
| 488 | stream.read = original_read | ||
| 489 | stamp = os.stat(source) | ||
| 490 | with open(source, "r+b") as f: | ||
| 491 | f.write(b"X") | ||
| 492 | os.utime(source, ns=(stamp.st_atime_ns, stamp.st_mtime_ns + 2_000_000_000)) | ||
| 493 | return chunk | ||
| 494 | |||
| 495 | stream.read = read_then_edit | ||
| 496 | return stream | ||
| 497 | |||
| 498 | with patch.object(manifest, "open", side_effect=open_with_edit, create=True): | ||
| 499 | with self.assertRaisesRegex(manifest.ManifestError, r"sample\.dat.*changed"): | ||
| 500 | self.create() | ||
| 501 | with open(self.out, "rb") as f: | ||
| 502 | self.assertEqual(f.read(), previous) | ||
| 503 | |||
| 455 | 504 | ||
| 456 | class ManifestBelowNormalTest(unittest.TestCase): | 505 | class ManifestBelowNormalTest(unittest.TestCase): |
| 457 | def test_below_normal_callable(self): | 506 | def test_below_normal_callable(self): |
diff --git a/tests/test_mission_tables.py b/tests/test_mission_tables.py new file mode 100644 index 000000000..738266023 --- /dev/null +++ b/tests/test_mission_tables.py | |||
| @@ -0,0 +1,235 @@ | |||
| 1 | """Synthetic tests for tools/mission_tables.py (no game data: every byte below is built here).""" | ||
| 2 | import json | ||
| 3 | import os | ||
| 4 | import struct | ||
| 5 | import subprocess | ||
| 6 | import sys | ||
| 7 | import tempfile | ||
| 8 | import unittest | ||
| 9 | |||
| 10 | ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | ||
| 11 | TOOL = os.path.join(ROOT, "tools", "mission_tables.py") | ||
| 12 | sys.path.insert(0, os.path.join(ROOT, "tools")) | ||
| 13 | |||
| 14 | import mission_tables as M # noqa: E402 | ||
| 15 | |||
| 16 | |||
| 17 | def record(key, kind, offset, count, col_b=1, band=0): | ||
| 18 | """One 32-byte record. The offset sits in the high half of the dword at +16.""" | ||
| 19 | word = (kind & 0xFFFF) | ((offset & 0xFFFF) << 16) | ||
| 20 | return struct.pack("<8I", key, 0, col_b, 0, word, band, (count << 16) | count, 0) | ||
| 21 | |||
| 22 | |||
| 23 | def element(archetype, pos, rot, link, hash_value=None, extra=0): | ||
| 24 | """One 64-byte pool element: hash, 3 zeros, pos(x,y,z,x), rot(x,y,z,x), hash, link, extra, 0.""" | ||
| 25 | head = struct.pack("<4I", archetype, 0, 0, 0) | ||
| 26 | pos_bytes = struct.pack("<4f", pos[0], pos[1], pos[2], pos[0]) | ||
| 27 | rot_bytes = struct.pack("<4f", rot[0], rot[1], rot[2], rot[0]) | ||
| 28 | tail = struct.pack("<4I", archetype if hash_value is None else hash_value, link, extra, 0) | ||
| 29 | return head + pos_bytes + rot_bytes + tail | ||
| 30 | |||
| 31 | |||
| 32 | def blob_with(records, elements): | ||
| 33 | """records: [(address, bytes)]; elements: [(address, bytes)]. Returns a zero-padded bytearray.""" | ||
| 34 | end = max([address + len(data) for address, data in records + elements] + [0]) | ||
| 35 | blob = bytearray(end) | ||
| 36 | for address, data in records + elements: | ||
| 37 | blob[address:address + len(data)] = data | ||
| 38 | return blob | ||
| 39 | |||
| 40 | |||
| 41 | def good_element(archetype=0x11223344, pos=(1.5, -2.25, 3.75), rot=(0.25, 0.5, -0.75), | ||
| 42 | link=0x55667788, extra=0): | ||
| 43 | return element(archetype, pos, rot, link, extra=extra) | ||
| 44 | |||
| 45 | |||
| 46 | class TestRecord(unittest.TestCase): | ||
| 47 | def test_big_endian_offset_half(self): | ||
| 48 | # The measured bytes of a real record: 03 00 80 07. kind is 3 and the offset is 0x780. | ||
| 49 | raw = struct.pack("<8I", 0x3B643C5E, 0, 1, 0, 0x07800003, 0, 0x00010001, 0) | ||
| 50 | self.assertEqual(raw[16:20], bytes((0x03, 0x00, 0x80, 0x07))) | ||
| 51 | decoded = M.decode_record(raw, 0) | ||
| 52 | self.assertIsNotNone(decoded) | ||
| 53 | self.assertEqual(decoded["key"], 0x3B643C5E) | ||
| 54 | self.assertEqual(decoded["kind"], 3) | ||
| 55 | self.assertEqual(decoded["poolOffset"], 0x780) # not 0x8007: the u16 is still little-endian | ||
| 56 | self.assertEqual(decoded["count"], 1) | ||
| 57 | self.assertEqual(decoded["band"], 0) | ||
| 58 | self.assertEqual(decoded["colB"], 1) | ||
| 59 | |||
| 60 | def test_duplicated_count_and_zero_fields_are_required(self): | ||
| 61 | self.assertIsNone(M.decode_record(bytes(16), 0)) # shorter than a record | ||
| 62 | bad_count = bytearray(record(0x12345678, 1, 0x100, 1)) | ||
| 63 | struct.pack_into("<I", bad_count, 24, 0x00010002) | ||
| 64 | self.assertIsNone(M.decode_record(bytes(bad_count), 0)) | ||
| 65 | bad_zero = bytearray(record(0x12345678, 1, 0x100, 1)) | ||
| 66 | struct.pack_into("<I", bad_zero, 28, 1) | ||
| 67 | self.assertIsNone(M.decode_record(bytes(bad_zero), 0)) | ||
| 68 | |||
| 69 | def test_joaat_folds_case(self): | ||
| 70 | self.assertEqual(M.joaat("AlphaBeta"), M.joaat("alphabeta")) | ||
| 71 | self.assertEqual(M.joaat("ALPHABETA"), M.joaat("alphabeta")) | ||
| 72 | # An independent transcription of Jenkins one-at-a-time, seeded at 0. | ||
| 73 | def reference(text): | ||
| 74 | value = 0 | ||
| 75 | for byte in text.lower().encode("latin-1"): | ||
| 76 | value = (value + byte) & 0xFFFFFFFF | ||
| 77 | value = (value + (value << 10)) & 0xFFFFFFFF | ||
| 78 | value ^= value >> 6 | ||
| 79 | value = (value + (value << 3)) & 0xFFFFFFFF | ||
| 80 | value ^= value >> 11 | ||
| 81 | return (value + (value << 15)) & 0xFFFFFFFF | ||
| 82 | for name in ("", "StateOne", "RoadJob", "a_b-c.d"): | ||
| 83 | self.assertEqual(M.joaat(name), reference(name)) | ||
| 84 | |||
| 85 | |||
| 86 | class TestElement(unittest.TestCase): | ||
| 87 | def test_round_trip(self): | ||
| 88 | state_one = 0x11111111 | ||
| 89 | state_two = 0x22222222 | ||
| 90 | blob = blob_with( | ||
| 91 | [(0x100, record(state_one, 7, 0x1C0, 1)), | ||
| 92 | (0x120, record(state_two, 7, 0x200, 1))], | ||
| 93 | [(0x1C0, good_element(archetype=0xAABBCCDD, link=0x01020304)), | ||
| 94 | (0x200, good_element(archetype=0x99887766, link=0x05060708, | ||
| 95 | pos=(-10.0, 20.0, 30.0), rot=(0.0, 1.0, 2.0)))], | ||
| 96 | ) | ||
| 97 | result = M.parse_blob(bytes(blob), "round-trip.bin") | ||
| 98 | self.assertEqual(result["records"], 2) | ||
| 99 | self.assertEqual(result["chunks"], 1) | ||
| 100 | self.assertEqual(result["state_keys"], 2) | ||
| 101 | self.assertEqual(result["entities"], 2) | ||
| 102 | self.assertEqual(result["unresolved_records"], 0) | ||
| 103 | self.assertEqual(result["skipped_slots"], 0) | ||
| 104 | by_archetype = {entity["archetype"]: entity for entity in result["entity_list"]} | ||
| 105 | self.assertEqual(set(by_archetype), {0xAABBCCDD, 0x99887766}) | ||
| 106 | first = by_archetype[0xAABBCCDD] | ||
| 107 | self.assertEqual(first["link"], 0x01020304) | ||
| 108 | self.assertEqual([round(value, 4) for value in first["pos"]], [1.5, -2.25, 3.75]) | ||
| 109 | self.assertEqual([round(value, 4) for value in first["rot"]], [0.25, 0.5, -0.75]) | ||
| 110 | second = by_archetype[0x99887766] | ||
| 111 | self.assertEqual([round(value, 4) for value in second["pos"]], [-10.0, 20.0, 30.0]) | ||
| 112 | |||
| 113 | def test_mismatched_duplicated_position_is_not_an_entity(self): | ||
| 114 | broken = bytearray(good_element(archetype=0xDEADBEEF, link=0x00000001)) | ||
| 115 | struct.pack_into("<I", broken, 0x1C, 0x7FC00000) # pos.x copy no longer equals pos.x | ||
| 116 | blob = blob_with( | ||
| 117 | [(0x100, record(0x11111111, 7, 0x180, 1)), | ||
| 118 | (0x120, record(0x22222222, 7, 0x1C0, 1))], | ||
| 119 | [(0x180, bytes(broken)), | ||
| 120 | (0x1C0, good_element(archetype=0xCAFEBABE, link=0x00000002))], | ||
| 121 | ) | ||
| 122 | result = M.parse_blob(bytes(blob), "mismatch.bin") | ||
| 123 | self.assertEqual(result["records"], 2) | ||
| 124 | self.assertEqual(result["entities"], 1) | ||
| 125 | self.assertEqual(result["skipped_slots"], 1) | ||
| 126 | self.assertEqual(result["unresolved_records"], 1) | ||
| 127 | self.assertEqual([entity["archetype"] for entity in result["entity_list"]], [0xCAFEBABE]) | ||
| 128 | |||
| 129 | def test_mismatched_duplicated_rotation_is_not_an_entity(self): | ||
| 130 | broken = bytearray(good_element(archetype=0xDEADBEEF)) | ||
| 131 | struct.pack_into("<I", broken, 0x2C, 0x40000000) # rot.x copy no longer equals rot.x | ||
| 132 | blob = blob_with( | ||
| 133 | [(0x100, record(0x11111111, 7, 0x180, 1)), | ||
| 134 | (0x120, record(0x22222222, 7, 0x180, 1))], | ||
| 135 | [(0x180, bytes(broken))], | ||
| 136 | ) | ||
| 137 | result = M.parse_blob(bytes(blob), "mismatch-rot.bin") | ||
| 138 | self.assertEqual(result["entities"], 0) | ||
| 139 | self.assertEqual(result["skipped_slots"], 2) | ||
| 140 | |||
| 141 | def test_extra_tail_hash_does_not_hide_an_entity(self): | ||
| 142 | # Some elements carry a second hash in the third-last dword; it must not invalidate the element. | ||
| 143 | blob = blob_with( | ||
| 144 | [(0x100, record(0x11111111, 7, 0x180, 1)), | ||
| 145 | (0x120, record(0x22222222, 7, 0x180, 1))], | ||
| 146 | [(0x180, good_element(archetype=0x1234ABCD, link=0x0BADF00D, extra=0xFEEDFACE))], | ||
| 147 | ) | ||
| 148 | result = M.parse_blob(bytes(blob), "extra.bin") | ||
| 149 | self.assertEqual(result["entities"], 1) | ||
| 150 | self.assertEqual(result["entity_list"][0]["extra"], 0xFEEDFACE) | ||
| 151 | |||
| 152 | |||
| 153 | class TestBrokenInput(unittest.TestCase): | ||
| 154 | def test_truncated_element_is_skipped_without_a_crash(self): | ||
| 155 | blob = blob_with( | ||
| 156 | [(0x100, record(0x11111111, 7, 0x1C0, 1)), | ||
| 157 | (0x120, record(0x22222222, 7, 0x1C0, 1))], | ||
| 158 | [(0x1C0, good_element())], | ||
| 159 | ) | ||
| 160 | truncated = bytes(blob[:0x1C0 + 40]) # the element loses its last 24 bytes | ||
| 161 | result = M.parse_blob(truncated, "truncated.bin") | ||
| 162 | self.assertEqual(result["records"], 2) | ||
| 163 | self.assertEqual(result["entities"], 0) | ||
| 164 | self.assertEqual(result["skipped_slots"], 2) | ||
| 165 | self.assertEqual(result["trailing_bytes"], len(truncated) - 0x140) | ||
| 166 | self.assertEqual(result["skipped_bytes"], len(truncated) - 2 * M.RECORD_SIZE) | ||
| 167 | |||
| 168 | def test_shorter_than_one_record_is_all_skipped(self): | ||
| 169 | result = M.parse_blob(b"\x01" * 20, "tiny.bin") | ||
| 170 | self.assertEqual(result["records"], 0) | ||
| 171 | self.assertEqual(result["entities"], 0) | ||
| 172 | self.assertEqual(result["skipped_bytes"], 20) | ||
| 173 | self.assertEqual(result["trailing_bytes"], 20) | ||
| 174 | |||
| 175 | def test_offset_outside_the_file_is_a_record_but_not_an_entity(self): | ||
| 176 | blob = blob_with( | ||
| 177 | [(0x100, record(0x11111111, 7, 0x180, 1)), | ||
| 178 | (0x120, record(0x22222222, 7, 0xFFF0, 1))], | ||
| 179 | [(0x180, good_element(archetype=0xABCDEF01, link=0x00000003))], | ||
| 180 | ) | ||
| 181 | result = M.parse_blob(bytes(blob), "outside.bin") | ||
| 182 | self.assertEqual(result["records"], 2) | ||
| 183 | self.assertEqual(result["state_keys"], 2) | ||
| 184 | self.assertEqual(result["entities"], 1) | ||
| 185 | self.assertEqual(result["unresolved_records"], 1) | ||
| 186 | self.assertEqual(result["entity_list"][0]["archetype"], 0xABCDEF01) | ||
| 187 | self.assertIn(0x22222222, {state["key"] for state in result["states"]}) | ||
| 188 | |||
| 189 | |||
| 190 | class TestCli(unittest.TestCase): | ||
| 191 | def test_directory_is_sorted_and_json_is_machine_readable(self): | ||
| 192 | one = bytes(blob_with( | ||
| 193 | [(0x100, record(0x11111111, 7, 0x180, 1)), | ||
| 194 | (0x120, record(0x22222222, 7, 0x180, 1))], | ||
| 195 | [(0x180, good_element())], | ||
| 196 | )) | ||
| 197 | with tempfile.TemporaryDirectory() as folder: | ||
| 198 | for name in ("b.bin", "a.bin"): | ||
| 199 | with open(os.path.join(folder, name), "wb") as handle: | ||
| 200 | handle.write(one) | ||
| 201 | with open(os.path.join(folder, "notes.txt"), "w", encoding="utf-8") as handle: | ||
| 202 | handle.write("not a stream") | ||
| 203 | result = M.collect(folder) | ||
| 204 | self.assertEqual([record["file"] for record in result], ["a.bin", "b.bin"]) | ||
| 205 | completed = subprocess.run( | ||
| 206 | [sys.executable, "-I", TOOL, folder, "--json"], | ||
| 207 | capture_output=True, text=True, check=True, | ||
| 208 | ) | ||
| 209 | payload = json.loads(completed.stdout) | ||
| 210 | self.assertEqual([record["file"] for record in payload["files"]], ["a.bin", "b.bin"]) | ||
| 211 | self.assertEqual(payload["summary"]["files"], 2) | ||
| 212 | self.assertEqual(payload["summary"]["records"], 4) | ||
| 213 | self.assertEqual(payload["summary"]["entities"], 2) | ||
| 214 | self.assertRegex(payload["files"][0]["entity_list"][0]["archetype"], r"^[0-9a-f]{8}$") | ||
| 215 | |||
| 216 | def test_limit_stops_after_the_requested_file_count(self): | ||
| 217 | one = bytes(blob_with( | ||
| 218 | [(0x100, record(0x11111111, 7, 0x180, 1)), | ||
| 219 | (0x120, record(0x22222222, 7, 0x180, 1))], | ||
| 220 | [(0x180, good_element())], | ||
| 221 | )) | ||
| 222 | with tempfile.TemporaryDirectory() as folder: | ||
| 223 | for name in ("a.bin", "b.bin", "c.bin"): | ||
| 224 | with open(os.path.join(folder, name), "wb") as handle: | ||
| 225 | handle.write(one) | ||
| 226 | completed = subprocess.run( | ||
| 227 | [sys.executable, "-I", TOOL, folder, "--limit", "2"], | ||
| 228 | capture_output=True, text=True, check=True, | ||
| 229 | ) | ||
| 230 | self.assertEqual(completed.stdout.count(" records="), 2) | ||
| 231 | self.assertIn("2 files,", completed.stdout) | ||
| 232 | |||
| 233 | |||
| 234 | if __name__ == "__main__": | ||
| 235 | unittest.main() | ||
diff --git a/tests/test_opus_tags.py b/tests/test_opus_tags.py index 13c9720c9..3eb8215eb 100644 --- a/tests/test_opus_tags.py +++ b/tests/test_opus_tags.py | |||
| @@ -139,6 +139,17 @@ class TestFolder(unittest.TestCase): | |||
| 139 | self.assertEqual(self.tags("story", "bank_02", "1FFFFFFF.ogg"), ["TITLE=door_slam_03"]) | 139 | self.assertEqual(self.tags("story", "bank_02", "1FFFFFFF.ogg"), ["TITLE=door_slam_03"]) |
| 140 | self.assertEqual(self.tags("story", "bank_01", "00000123.ogg"), []) | 140 | self.assertEqual(self.tags("story", "bank_01", "00000123.ogg"), []) |
| 141 | 141 | ||
| 142 | def test_duplicate_id_stream_gets_the_same_tags(self): | ||
| 143 | # awc_opus.py names a bank's second stream with an id already used <id>~2 (export_stems); it has the same | ||
| 144 | # id, so it is the same name and dialogue line. | ||
| 145 | stem = awc_opus.export_stems([0x0ABCDEF1, 0x0ABCDEF1])[1] | ||
| 146 | make_ogg(os.path.join(self.opus, "story", "bank_01", stem + ".ogg")) | ||
| 147 | dialogue, langs = T.load_dialogue(self.dialogue) | ||
| 148 | stats = T.tag_folder(self.opus, T.load_names(self.names, "story"), dialogue, langs) | ||
| 149 | self.assertEqual((stats["ogg files"], stats["tagged"], stats["without a name"]), (4, 3, 1)) | ||
| 150 | self.assertEqual(self.tags("story", "bank_01", stem + ".ogg"), self.tags("story", "bank_01", "0ABCDEF1.ogg")) | ||
| 151 | self.assertIn("TITLE=heistau_abcd_01", self.tags("story", "bank_01", stem + ".ogg")) | ||
| 152 | |||
| 142 | def test_second_run_replaces_its_own_tags(self): | 153 | def test_second_run_replaces_its_own_tags(self): |
| 143 | names = T.load_names(self.names, "story") | 154 | names = T.load_names(self.names, "story") |
| 144 | T.tag_folder(self.opus, names) | 155 | T.tag_folder(self.opus, names) |
diff --git a/tests/test_pe_inspect.py b/tests/test_pe_inspect.py index f4dd76356..0534be001 100644 --- a/tests/test_pe_inspect.py +++ b/tests/test_pe_inspect.py | |||
| @@ -636,5 +636,33 @@ class TruncatedImageTest(unittest.TestCase): | |||
| 636 | self.assertLessEqual(len(exports), pe_inspect.MAX_ENTRIES + 2) | 636 | self.assertLessEqual(len(exports), pe_inspect.MAX_ENTRIES + 2) |
| 637 | 637 | ||
| 638 | 638 | ||
| 639 | class DeclaredOptionalHeaderSizeTest(unittest.TestCase): | ||
| 640 | """Reject optional headers smaller than the fields the parser reads.""" | ||
| 641 | |||
| 642 | def test_declared_optional_header_too_small(self): | ||
| 643 | for is64 in (False, True): | ||
| 644 | for declared_size in (0, 2, 71): | ||
| 645 | with self.subTest(is64=is64, declared_size=declared_size): | ||
| 646 | data = bytearray(build_image(is64=is64)) | ||
| 647 | pe_offset = struct.unpack_from("<I", data, 0x3C)[0] | ||
| 648 | struct.pack_into("<H", data, pe_offset + 20, declared_size) | ||
| 649 | |||
| 650 | with self.assertRaisesRegex( | ||
| 651 | pe_inspect.PeFormatError, "truncated optional header" | ||
| 652 | ): | ||
| 653 | pe_inspect.PeImage(bytes(data)) | ||
| 654 | |||
| 655 | def test_declared_optional_header_extends_beyond_file(self): | ||
| 656 | for is64 in (False, True): | ||
| 657 | with self.subTest(is64=is64): | ||
| 658 | data = bytearray(build_image(is64=is64)) | ||
| 659 | pe_offset = struct.unpack_from("<I", data, 0x3C)[0] | ||
| 660 | struct.pack_into("<H", data, pe_offset + 20, 0xFFFF) | ||
| 661 | |||
| 662 | with self.assertRaisesRegex( | ||
| 663 | pe_inspect.PeFormatError, "truncated optional header" | ||
| 664 | ): | ||
| 665 | pe_inspect.PeImage(bytes(data)) | ||
| 666 | |||
| 639 | if __name__ == "__main__": | 667 | if __name__ == "__main__": |
| 640 | unittest.main() | 668 | unittest.main() |
diff --git a/tests/test_pe_shader_containers.py b/tests/test_pe_shader_containers.py new file mode 100644 index 000000000..a7ffb8a08 --- /dev/null +++ b/tests/test_pe_shader_containers.py | |||
| @@ -0,0 +1,171 @@ | |||
| 1 | """Unit tests for tools/pe_shader_containers.py, on synthetic containers (no game data, no PE needed). | ||
| 2 | |||
| 3 | The containers are built by hand here: a u32 offset table at +32, and each chunk beginning with its fourcc | ||
| 4 | and a u32 size. The scan's job is to accept exactly that shape and to reject the `DXBC` immediates and error | ||
| 5 | strings that occur in ordinary code. | ||
| 6 | """ | ||
| 7 | |||
| 8 | import json | ||
| 9 | import os | ||
| 10 | import random | ||
| 11 | import struct | ||
| 12 | import sys | ||
| 13 | import tempfile | ||
| 14 | import unittest | ||
| 15 | |||
| 16 | HERE = os.path.dirname(os.path.abspath(__file__)) | ||
| 17 | ROOT = os.path.dirname(HERE) | ||
| 18 | sys.path.insert(0, os.path.join(ROOT, "tools")) | ||
| 19 | |||
| 20 | import pe_shader_containers as psc | ||
| 21 | |||
| 22 | |||
| 23 | def container(parts) -> bytes: | ||
| 24 | """Assemble a DXBC container from (fourcc, payload) pairs.""" | ||
| 25 | header = 32 + 4 * len(parts) | ||
| 26 | offsets, body, end = [], b"", header | ||
| 27 | for fourcc, payload in parts: | ||
| 28 | offsets.append(header + len(body)) | ||
| 29 | body += fourcc + struct.pack("<I", len(payload)) + payload | ||
| 30 | end = header + len(body) | ||
| 31 | body += bytes( | ||
| 32 | (-len(body)) % 4 | ||
| 33 | ) # chunks are 4-byte aligned; nothing follows the last one | ||
| 34 | total = end | ||
| 35 | out = b"DXBC" + bytes(16) + struct.pack("<III", 1, total, len(parts)) | ||
| 36 | out += b"".join(struct.pack("<I", o) for o in offsets) | ||
| 37 | return out + body[: total - header] | ||
| 38 | |||
| 39 | |||
| 40 | def xdat(entries, base: int) -> bytes: | ||
| 41 | """An XDAT directory whose payload offsets are relative to the DXIL part, as the package has it.""" | ||
| 42 | head = base + 12 + 12 * len(entries) | ||
| 43 | directory, payload = b"", b"" | ||
| 44 | for tag, value in entries: | ||
| 45 | directory += struct.pack("<III", tag, head + len(payload), len(value)) | ||
| 46 | payload += value | ||
| 47 | return b"XDAT" + struct.pack("<II", len(entries), 0) + directory + payload | ||
| 48 | |||
| 49 | |||
| 50 | def dxil_payload(name: str, xbch: bool = True, bitcode: bool = True) -> bytes: | ||
| 51 | entries = [(0x12, bytes(16))] | ||
| 52 | if xbch: | ||
| 53 | entries.append((0x0D, b"XBCH" + bytes(20) + b"payload")) | ||
| 54 | if bitcode: | ||
| 55 | entries.append((0x07, b"BC\xc0\xde" + bytes(8))) | ||
| 56 | prefix = ( | ||
| 57 | b"e\x00\x05\x00" | ||
| 58 | + struct.pack("<I", 24) | ||
| 59 | + b"DXIL" | ||
| 60 | + b"\x05\x01\x00\x00" | ||
| 61 | + struct.pack("<I", 0x70) | ||
| 62 | + struct.pack("<I", 0x668) | ||
| 63 | ) | ||
| 64 | return prefix + xdat(entries, len(prefix)) | ||
| 65 | |||
| 66 | |||
| 67 | def ildn(name: str) -> bytes: | ||
| 68 | path = ( | ||
| 69 | "X:\\americas\\src\\dev\\rage\\3rdparty\\Microsoft\\XboxBvhBuilder\\Build\\Release\\Output\\" | ||
| 70 | f"XboxBvhBuilder\\{name}.pdb" | ||
| 71 | ).encode() | ||
| 72 | return b"\x00\x00" + struct.pack("<H", len(path)) + path | ||
| 73 | |||
| 74 | |||
| 75 | class ContainerTests(unittest.TestCase): | ||
| 76 | def test_scan_reads_one_container(self): | ||
| 77 | data = container( | ||
| 78 | [ | ||
| 79 | (b"SFI0", bytes(8)), | ||
| 80 | (b"ILDN", ildn("BitonicPreSort64CS")), | ||
| 81 | (b"DXIL", dxil_payload("BitonicPreSort64CS")), | ||
| 82 | ] | ||
| 83 | ) | ||
| 84 | found, rejected = psc.inspect(b"MZ" + bytes(64) + data, "fake.dll") | ||
| 85 | self.assertEqual(rejected, []) | ||
| 86 | self.assertEqual(len(found), 1) | ||
| 87 | r = found[0] | ||
| 88 | self.assertEqual(r["offset"], 66) | ||
| 89 | self.assertEqual(r["size"], len(data)) | ||
| 90 | self.assertEqual(r["name"], "BitonicPreSort64CS") | ||
| 91 | self.assertTrue(r["has_xbch"]) | ||
| 92 | self.assertTrue(r["has_bitcode"]) | ||
| 93 | self.assertFalse(r["has_fspx"]) | ||
| 94 | self.assertEqual([c["fourcc"] for c in r["chunks"]], ["SFI0", "ILDN", "DXIL"]) | ||
| 95 | |||
| 96 | def test_scan_rejects_a_bare_magic(self): | ||
| 97 | data = b"junk" + b"DXBC" + bytes(40) | ||
| 98 | found, rejected = psc.inspect(data, "fake.dll") | ||
| 99 | self.assertEqual(found, []) | ||
| 100 | self.assertEqual(rejected, [4]) | ||
| 101 | |||
| 102 | def test_scan_rejects_a_truncated_chunk(self): | ||
| 103 | good = container([(b"SFI0", bytes(8)), (b"DXIL", dxil_payload("x"))]) | ||
| 104 | data = good[:-8] | ||
| 105 | found, rejected = psc.inspect(data, "fake.dll") | ||
| 106 | self.assertEqual(found, []) | ||
| 107 | self.assertEqual(len(rejected), 1) | ||
| 108 | |||
| 109 | def test_fspx_is_reported_and_has_no_xbch(self): | ||
| 110 | data = container([(b"SFI0", bytes(8)), (b"ACCC", b"FSPX" + bytes(12))]) | ||
| 111 | found, _ = psc.inspect(data, "fsr.dll") | ||
| 112 | self.assertEqual(len(found), 1) | ||
| 113 | self.assertTrue(found[0]["has_fspx"]) | ||
| 114 | self.assertFalse(found[0]["has_xbch"]) | ||
| 115 | self.assertFalse(found[0]["has_bitcode"]) | ||
| 116 | self.assertIsNone(found[0]["name"]) | ||
| 117 | |||
| 118 | def test_xdat_directory(self): | ||
| 119 | tags = psc.xdat_tags(dxil_payload("x")) | ||
| 120 | self.assertEqual([t["tag"] for t in tags], [0x12, 0x0D, 0x07]) | ||
| 121 | self.assertEqual(tags[1]["magic"], "XBCH") | ||
| 122 | |||
| 123 | def test_module_name_forms(self): | ||
| 124 | self.assertEqual(psc.module_name(ildn("ConstructBVH4")), "ConstructBVH4") | ||
| 125 | self.assertEqual(psc.module_name(b"\x00\x00\x0a\x00C:\\a\\b.pdb"), "b") | ||
| 126 | self.assertIsNone(psc.module_name(b"")) | ||
| 127 | |||
| 128 | def test_extract_writes_container_and_index(self): | ||
| 129 | data = container( | ||
| 130 | [(b"ILDN", ildn("RefitBVH4")), (b"DXIL", dxil_payload("RefitBVH4"))] | ||
| 131 | ) | ||
| 132 | found, _ = psc.inspect(data, "fake.dll") | ||
| 133 | with tempfile.TemporaryDirectory() as tmp: | ||
| 134 | index = psc.extract(data, found, tmp) | ||
| 135 | with open(os.path.join(tmp, index[0]["file"]), "rb") as f: | ||
| 136 | self.assertEqual(f.read(), data) | ||
| 137 | with open(os.path.join(tmp, "index.json"), "w", encoding="utf-8") as f: | ||
| 138 | json.dump(index, f) | ||
| 139 | with open(os.path.join(tmp, "index.json"), encoding="utf-8") as f: | ||
| 140 | self.assertEqual( | ||
| 141 | json.load(f)[0], | ||
| 142 | {"name": "RefitBVH4", "file": "RefitBVH4.dxbc", "stage": "cs"}, | ||
| 143 | ) | ||
| 144 | |||
| 145 | def test_safe_stem(self): | ||
| 146 | self.assertEqual(psc.safe_stem("a b/c", 1), "a_b_c") | ||
| 147 | self.assertEqual(psc.safe_stem(None, 7), "container_07") | ||
| 148 | |||
| 149 | def test_random_buffers_raise_only_container_error(self): | ||
| 150 | """The scan must never traceback on bytes that are not a container (dcastell1's review).""" | ||
| 151 | rng = random.Random(0xDBC) | ||
| 152 | for _ in range(2000): | ||
| 153 | size = rng.randrange(0, 400) | ||
| 154 | data = bytearray(rng.randbytes(size)) | ||
| 155 | if size >= 4: | ||
| 156 | at = rng.randrange(0, size - 3) | ||
| 157 | data[at : at + 4] = b"DXBC" | ||
| 158 | try: | ||
| 159 | psc.parse_container(bytes(data), at) | ||
| 160 | except psc.ContainerError: | ||
| 161 | pass | ||
| 162 | except Exception as e: # noqa: BLE001 - any other type is the failure being asserted | ||
| 163 | self.fail(f"parse_container raised {type(e).__name__}: {e}") | ||
| 164 | try: | ||
| 165 | psc.inspect(bytes(data), "fuzz.dll") | ||
| 166 | except Exception as e: # noqa: BLE001 - any exception is the failure being asserted | ||
| 167 | self.fail(f"inspect raised {type(e).__name__}: {e}") | ||
| 168 | |||
| 169 | |||
| 170 | if __name__ == "__main__": | ||
| 171 | unittest.main() | ||
diff --git a/tests/test_psin_names.py b/tests/test_psin_names.py index d4f0d50ed..7502db7b0 100644 --- a/tests/test_psin_names.py +++ b/tests/test_psin_names.py | |||
| @@ -137,6 +137,24 @@ class TestCli(unittest.TestCase): | |||
| 137 | self.assertEqual(r.returncode, 0, r.stderr) | 137 | self.assertEqual(r.returncode, 0, r.stderr) |
| 138 | self.assertEqual(json.loads(r.stdout)["summary"]["u64 resolved"], 1) | 138 | self.assertEqual(json.loads(r.stdout)["summary"]["u64 resolved"], 1) |
| 139 | 139 | ||
| 140 | def test_rejects_refs_aliasing_inputs(self): | ||
| 141 | with tempfile.TemporaryDirectory() as tmp: | ||
| 142 | source = os.path.join(tmp, "one.bin") | ||
| 143 | names = os.path.join(tmp, "names.txt") | ||
| 144 | for path, data in ((source, sample()), (names, b"prop_crate_01\n")): | ||
| 145 | with open(path, "wb") as f: | ||
| 146 | f.write(data) | ||
| 147 | for destination in (source, names): | ||
| 148 | with self.subTest(destination=destination): | ||
| 149 | with open(destination, "rb") as f: | ||
| 150 | original = f.read() | ||
| 151 | alias = os.path.join(tmp, ".", os.path.basename(destination)) | ||
| 152 | result = self.run_tool(source, "--names", names, "--refs", alias) | ||
| 153 | self.assertEqual(result.returncode, 2, result.stderr) | ||
| 154 | self.assertIn("--refs must not overwrite an input", result.stderr) | ||
| 155 | with open(destination, "rb") as f: | ||
| 156 | self.assertEqual(f.read(), original) | ||
| 157 | |||
| 140 | def test_missing_names_file_is_one_line(self): | 158 | def test_missing_names_file_is_one_line(self): |
| 141 | with tempfile.TemporaryDirectory() as d: | 159 | with tempfile.TemporaryDirectory() as d: |
| 142 | r = self.run_tool(d, "--names", os.path.join(d, "none.txt")) | 160 | r = self.run_tool(d, "--names", os.path.join(d, "none.txt")) |
diff --git a/tests/test_rdna2spirv_cli.py b/tests/test_rdna2spirv_cli.py index 64dfca3bb..353f79cdb 100644 --- a/tests/test_rdna2spirv_cli.py +++ b/tests/test_rdna2spirv_cli.py | |||
| @@ -215,6 +215,34 @@ class ValidatedOutput(unittest.TestCase): | |||
| 215 | self.assertEqual(json.loads(self.index.read_text(encoding="utf-8")), previous) | 215 | self.assertEqual(json.loads(self.index.read_text(encoding="utf-8")), previous) |
| 216 | self.assertEqual(other.read_bytes(), b"unrelated module") | 216 | self.assertEqual(other.read_bytes(), b"unrelated module") |
| 217 | 217 | ||
| 218 | def test_unsupported_clears_retried_shader_but_preserves_unrelated_output(self): | ||
| 219 | # s_barrier is compute-only, so this PS is Unsupported before any SPIR-V tool runs. A module an | ||
| 220 | # earlier run published for it must not survive: the index is make_game.py's proof of completion. | ||
| 221 | self.src.write_text("\ts_barrier\n\ts_endpgm\n", encoding="utf-8") | ||
| 222 | other = self.out / "cs_other.spv" | ||
| 223 | other.write_bytes(b"unrelated module") | ||
| 224 | previous = {"cs_other": {"stage": "cs"}} | ||
| 225 | self.module.write_bytes(b"old module") | ||
| 226 | self.index.write_text(json.dumps({**previous, "ps_fixture": {"stage": "ps"}}), encoding="utf-8") | ||
| 227 | output = self.translate() | ||
| 228 | self.assertIn("s_barrier outside compute", output) | ||
| 229 | self.assertFalse(self.module.exists()) | ||
| 230 | self.assertEqual(json.loads(self.index.read_text(encoding="utf-8")), previous) | ||
| 231 | self.assertEqual(other.read_bytes(), b"unrelated module") | ||
| 232 | self.assertEqual(list(self.out.glob("*.tmp")), []) | ||
| 233 | |||
| 234 | def test_translator_error_clears_retried_shader(self): | ||
| 235 | self.module.write_bytes(b"old module") | ||
| 236 | self.index.write_text(json.dumps({"ps_fixture": {"stage": "ps"}}), encoding="utf-8") | ||
| 237 | output = io.StringIO() | ||
| 238 | with mock.patch.object(rdna2spirv, "translate", side_effect=ValueError("synthetic translator error")), \ | ||
| 239 | mock.patch.object(sys, "argv", [TOOL, str(self.src), "--out", str(self.out)]), \ | ||
| 240 | redirect_stdout(output): | ||
| 241 | rdna2spirv.main() | ||
| 242 | self.assertIn("translator error ValueError", output.getvalue()) | ||
| 243 | self.assertFalse(self.module.exists()) | ||
| 244 | self.assertEqual(json.loads(self.index.read_text(encoding="utf-8")), {}) | ||
| 245 | |||
| 218 | def test_validation_success_publishes_binary_and_metadata(self): | 246 | def test_validation_success_publishes_binary_and_metadata(self): |
| 219 | self.assertIn("1 pass spirv-val", self.translate()) | 247 | self.assertIn("1 pass spirv-val", self.translate()) |
| 220 | self.assertEqual(self.module.read_bytes(), b"new module") | 248 | self.assertEqual(self.module.read_bytes(), b"new module") |
| @@ -223,3 +251,26 @@ class ValidatedOutput(unittest.TestCase): | |||
| 223 | 251 | ||
| 224 | if __name__ == "__main__": | 252 | if __name__ == "__main__": |
| 225 | unittest.main() | 253 | unittest.main() |
| 254 | |||
| 255 | |||
| 256 | class EmptyShader(unittest.TestCase): | ||
| 257 | """A .s with no tab-indented instruction parses to an empty shader. | ||
| 258 | |||
| 259 | It used to translate to a module that passes spirv-val, lands in index.json and does no work at all, which is | ||
| 260 | what a hand-written or re-indented .s looks like: found while writing a fixture with spaces instead of tabs. | ||
| 261 | """ | ||
| 262 | |||
| 263 | def test_no_instructions_is_reported_and_no_module_is_published(self): | ||
| 264 | with tempfile.TemporaryDirectory() as tmp: | ||
| 265 | src = os.path.join(tmp, "disasm") | ||
| 266 | os.mkdir(src) | ||
| 267 | with open(os.path.join(src, "ps_empty.s"), "w", encoding="utf-8") as f: | ||
| 268 | f.write("; ps_empty code 0x0..0x0 (synthetic), gfx1013, 0 invalid words\n s_endpgm\n") | ||
| 269 | with open(os.path.join(tmp, "ps_empty.dxbc"), "wb") as f: | ||
| 270 | f.write(b"DXBC" + bytes(28)) | ||
| 271 | out = os.path.join(tmp, "spirv") | ||
| 272 | p = subprocess.run([sys.executable, "-I", TOOL, src, "--out", out], capture_output=True, text=True) | ||
| 273 | self.assertEqual(p.returncode, 0, p.stderr) | ||
| 274 | self.assertIn("0 translated", p.stdout, p.stdout) | ||
| 275 | self.assertIn("no instructions (nothing tab-indented?)", p.stdout, p.stdout) | ||
| 276 | self.assertFalse(os.path.exists(os.path.join(out, "ps_empty.spv"))) | ||
diff --git a/tests/test_rdna2spirv_merge.py b/tests/test_rdna2spirv_merge.py new file mode 100644 index 000000000..20bc22a7d --- /dev/null +++ b/tests/test_rdna2spirv_merge.py | |||
| @@ -0,0 +1,180 @@ | |||
| 1 | """tools/rdna2spirv.py --merge: an incomplete shard set is refused, not published as a partial index. | ||
| 2 | |||
| 3 | python -I tests/test_rdna2spirv_merge.py | ||
| 4 | """ | ||
| 5 | import json | ||
| 6 | import subprocess | ||
| 7 | import sys | ||
| 8 | import tempfile | ||
| 9 | import unittest | ||
| 10 | from pathlib import Path | ||
| 11 | |||
| 12 | ROOT = Path(__file__).resolve().parents[1] | ||
| 13 | sys.path.insert(0, str(ROOT / "tools")) | ||
| 14 | import rdna2spirv as R # noqa: E402 | ||
| 15 | |||
| 16 | TOOL = ROOT / "tools" / "rdna2spirv.py" | ||
| 17 | |||
| 18 | |||
| 19 | class MergeShardPartsTest(unittest.TestCase): | ||
| 20 | def setUp(self): | ||
| 21 | self.tmp = tempfile.TemporaryDirectory() | ||
| 22 | self.addCleanup(self.tmp.cleanup) | ||
| 23 | self.out = Path(self.tmp.name) | ||
| 24 | |||
| 25 | def part(self, index, doc): | ||
| 26 | (self.out / f"index.part{index}.json").write_text(json.dumps(doc), encoding="utf-8") | ||
| 27 | |||
| 28 | def marker(self, index, count): | ||
| 29 | (self.out / f"shard{index}.json").write_text(json.dumps({"index": index, "count": count}), encoding="utf-8") | ||
| 30 | |||
| 31 | def plan(self, jobs): | ||
| 32 | (self.out / "shards.json").write_text(json.dumps({"jobs": jobs}), encoding="utf-8") | ||
| 33 | |||
| 34 | def merge_error(self): | ||
| 35 | with self.assertRaises(R.ShardSetError) as cm: | ||
| 36 | R.merge_shard_parts(str(self.out)) | ||
| 37 | return str(cm.exception) | ||
| 38 | |||
| 39 | def test_complete_set_merges(self): | ||
| 40 | self.part(0, {"a": {"r": 1}}) | ||
| 41 | self.part(1, {"b": {"r": 2}}) | ||
| 42 | self.marker(0, 2) | ||
| 43 | self.marker(1, 2) | ||
| 44 | self.assertEqual(R.merge_shard_parts(str(self.out)), {"a": {"r": 1}, "b": {"r": 2}}) | ||
| 45 | |||
| 46 | def test_missing_part_is_refused(self): | ||
| 47 | self.part(0, {"a": {}}) | ||
| 48 | self.marker(0, 3) | ||
| 49 | self.marker(1, 3) | ||
| 50 | self.marker(2, 3) | ||
| 51 | message = self.merge_error() | ||
| 52 | self.assertIn("incomplete shard set", message) | ||
| 53 | self.assertIn("1 of 3", message) | ||
| 54 | self.assertIn("missing [1, 2]", message) | ||
| 55 | |||
| 56 | def test_extra_part_is_refused(self): | ||
| 57 | for i in range(3): | ||
| 58 | self.part(i, {}) | ||
| 59 | self.marker(i, 2) | ||
| 60 | message = self.merge_error() | ||
| 61 | self.assertIn("incomplete shard set", message) | ||
| 62 | self.assertIn("unexpected [2]", message) | ||
| 63 | |||
| 64 | def test_parts_and_markers_must_match(self): | ||
| 65 | self.part(0, {}) | ||
| 66 | self.part(1, {}) | ||
| 67 | self.marker(0, 2) | ||
| 68 | self.assertIn("index parts and shard markers disagree", self.merge_error()) | ||
| 69 | |||
| 70 | def test_a_part_without_its_marker_is_refused(self): | ||
| 71 | # A part left by an older rdna2spirv.py that did not write markers mixed with a newer set. | ||
| 72 | for i in range(3): | ||
| 73 | self.part(i, {}) | ||
| 74 | self.marker(1, 3) | ||
| 75 | self.marker(2, 3) | ||
| 76 | message = self.merge_error() | ||
| 77 | self.assertIn("index parts and shard markers disagree", message) | ||
| 78 | self.assertIn("parts [0, 1, 2]", message) | ||
| 79 | self.assertIn("markers [1, 2]", message) | ||
| 80 | |||
| 81 | def test_marker_counts_must_agree(self): | ||
| 82 | self.part(0, {}) | ||
| 83 | self.part(1, {}) | ||
| 84 | self.marker(0, 2) | ||
| 85 | self.marker(1, 3) | ||
| 86 | self.assertIn("disagree on the shard count", self.merge_error()) | ||
| 87 | |||
| 88 | def test_plan_count_is_used_without_markers(self): | ||
| 89 | self.part(0, {}) | ||
| 90 | self.plan(2) | ||
| 91 | self.assertIn("incomplete shard set", self.merge_error()) | ||
| 92 | |||
| 93 | def test_legacy_parts_without_metadata_still_merge(self): | ||
| 94 | self.part(0, {"a": {}}) | ||
| 95 | self.part(1, {"b": {}}) | ||
| 96 | self.assertEqual(sorted(R.merge_shard_parts(str(self.out))), ["a", "b"]) | ||
| 97 | |||
| 98 | def test_unexpected_part_name_is_refused(self): | ||
| 99 | (self.out / "index.partx.json").write_text("{}", encoding="utf-8") | ||
| 100 | self.assertIn("not an index.part", self.merge_error()) | ||
| 101 | |||
| 102 | |||
| 103 | class MergeCliTest(unittest.TestCase): | ||
| 104 | def setUp(self): | ||
| 105 | self.tmp = tempfile.TemporaryDirectory() | ||
| 106 | self.addCleanup(self.tmp.cleanup) | ||
| 107 | self.out = Path(self.tmp.name) | ||
| 108 | |||
| 109 | def part(self, index, doc): | ||
| 110 | (self.out / f"index.part{index}.json").write_text(json.dumps(doc), encoding="utf-8") | ||
| 111 | |||
| 112 | def marker(self, index, count): | ||
| 113 | (self.out / f"shard{index}.json").write_text(json.dumps({"index": index, "count": count}), encoding="utf-8") | ||
| 114 | |||
| 115 | def run_merge(self): | ||
| 116 | return subprocess.run([sys.executable, "-I", str(TOOL), str(self.out), "--out", str(self.out), "--merge"], | ||
| 117 | capture_output=True, text=True, timeout=120) | ||
| 118 | |||
| 119 | def test_cli_refuses_a_partial_set_and_writes_no_index(self): | ||
| 120 | self.part(0, {"a": {}}) | ||
| 121 | self.marker(0, 2) | ||
| 122 | self.marker(1, 2) | ||
| 123 | result = self.run_merge() | ||
| 124 | self.assertEqual(result.returncode, 2, result.stdout + result.stderr) | ||
| 125 | self.assertIn("ERROR: incomplete shard set", result.stderr) | ||
| 126 | self.assertNotIn("Traceback", result.stderr) | ||
| 127 | self.assertFalse((self.out / "index.json").exists()) | ||
| 128 | |||
| 129 | def test_cli_merges_a_complete_set(self): | ||
| 130 | self.part(0, {"a": {}}) | ||
| 131 | self.part(1, {"b": {}}) | ||
| 132 | self.marker(0, 2) | ||
| 133 | self.marker(1, 2) | ||
| 134 | result = self.run_merge() | ||
| 135 | self.assertEqual(result.returncode, 0, result.stdout + result.stderr) | ||
| 136 | self.assertIn("merged 2 entries", result.stdout) | ||
| 137 | merged = json.loads((self.out / "index.json").read_text(encoding="utf-8")) | ||
| 138 | self.assertEqual(sorted(merged), ["a", "b"]) | ||
| 139 | |||
| 140 | |||
| 141 | class ShardRoundTripTest(unittest.TestCase): | ||
| 142 | """The writer and the merge through the real CLI, on an empty input directory (no .s and no llvm-mc needed).""" | ||
| 143 | |||
| 144 | def setUp(self): | ||
| 145 | self.tmp = tempfile.TemporaryDirectory() | ||
| 146 | self.addCleanup(self.tmp.cleanup) | ||
| 147 | self.src = Path(self.tmp.name) / "src" | ||
| 148 | self.out = Path(self.tmp.name) / "out" | ||
| 149 | self.src.mkdir() | ||
| 150 | self.out.mkdir() | ||
| 151 | |||
| 152 | def run_tool(self, *args): | ||
| 153 | return subprocess.run([sys.executable, "-I", str(TOOL), str(self.src), "--out", str(self.out), *args], | ||
| 154 | capture_output=True, text=True, timeout=120) | ||
| 155 | |||
| 156 | def test_a_shard_writes_its_marker_and_part_and_merge_needs_the_whole_set(self): | ||
| 157 | first = self.run_tool("--shard", "0/2") | ||
| 158 | self.assertEqual(first.returncode, 0, first.stdout + first.stderr) | ||
| 159 | self.assertTrue((self.out / "index.part0.json").is_file()) | ||
| 160 | marker = json.loads((self.out / "shard0.json").read_text(encoding="utf-8")) | ||
| 161 | self.assertEqual(marker, {"index": 0, "count": 2}) | ||
| 162 | |||
| 163 | partial = self.run_tool("--merge") | ||
| 164 | self.assertEqual(partial.returncode, 2, partial.stdout + partial.stderr) | ||
| 165 | self.assertIn("incomplete shard set", partial.stderr) | ||
| 166 | self.assertFalse((self.out / "index.json").exists()) | ||
| 167 | |||
| 168 | second = self.run_tool("--shard", "1/2") | ||
| 169 | self.assertEqual(second.returncode, 0, second.stdout + second.stderr) | ||
| 170 | self.assertTrue((self.out / "index.part1.json").is_file()) | ||
| 171 | self.assertTrue((self.out / "shard1.json").is_file()) | ||
| 172 | |||
| 173 | full = self.run_tool("--merge") | ||
| 174 | self.assertEqual(full.returncode, 0, full.stdout + full.stderr) | ||
| 175 | self.assertIn("merged 0 entries", full.stdout) | ||
| 176 | self.assertEqual(json.loads((self.out / "index.json").read_text(encoding="utf-8")), {}) | ||
| 177 | |||
| 178 | |||
| 179 | if __name__ == "__main__": | ||
| 180 | unittest.main() | ||
diff --git a/tests/test_save_keys.py b/tests/test_save_keys.py index d50996fe9..906b7c6a0 100644 --- a/tests/test_save_keys.py +++ b/tests/test_save_keys.py | |||
| @@ -143,6 +143,11 @@ class Resolve(unittest.TestCase): | |||
| 143 | self.assertNotIn("Traceback", r.stderr) | 143 | self.assertNotIn("Traceback", r.stderr) |
| 144 | self.assertEqual(r.stdout, "") # refused before the resolve ran | 144 | self.assertEqual(r.stdout, "") # refused before the resolve ran |
| 145 | 145 | ||
| 146 | def test_rejects_negative_compose_count(self): | ||
| 147 | result = self.resolve_cli(self.dir, "--dict", self.dict, "--compose", "-1") | ||
| 148 | self.assertEqual(result.returncode, 2, result.stderr) | ||
| 149 | self.assertIn("--compose must be 0 or more", result.stderr) | ||
| 150 | |||
| 146 | def test_compose_finds_two_word_names(self): | 151 | def test_compose_finds_two_word_names(self): |
| 147 | text = run(["resolve", self.jsav, "--dict", self.dict, "--compose", "50"]) | 152 | text = run(["resolve", self.jsav, "--dict", self.dict, "--compose", "50"]) |
| 148 | self.assertIn("joaat, composed 1 more keys", text) # SprocketCount from Sprocket + Count | 153 | self.assertIn("joaat, composed 1 more keys", text) # SprocketCount from Sprocket + Count |
diff --git a/tests/test_shader_build_fallbacks.py b/tests/test_shader_build_fallbacks.py new file mode 100644 index 000000000..99c467b12 --- /dev/null +++ b/tests/test_shader_build_fallbacks.py | |||
| @@ -0,0 +1,124 @@ | |||
| 1 | """runtime/test/shaders/build.py under the PerVertexKHR fallbacks (LEONIDA_BARY_FALLBACK=1, LEONIDA_F16_INTERP_FALLBACK=1). | ||
| 2 | |||
| 3 | The translator refuses a computed I/J pair (ps_ij_computed) without PerVertexKHR inputs, which both fallbacks take | ||
| 4 | away. build.py used to treat that as a failed batch: it exited before publishing anything, so check.py then reported | ||
| 5 | every test missing (0 of 147 on a Mac, where check.py needs LEONIDA_F16_INTERP_FALLBACK=1). check.py and | ||
| 6 | run_gpu_tests.py report ps_ij_computed as SKIP there; build.py now leaves it out and builds the rest. | ||
| 7 | |||
| 8 | Standard library only; the translator is replaced by a stand-in that writes the index and modules and, like the real | ||
| 9 | one, refuses ps_ij_computed under a fallback. No llvm-mc, SPIR-V tools, GPU or game data. | ||
| 10 | |||
| 11 | python -I tests/test_shader_build_fallbacks.py | ||
| 12 | """ | ||
| 13 | import contextlib | ||
| 14 | import importlib.util | ||
| 15 | import io | ||
| 16 | import json | ||
| 17 | import os | ||
| 18 | import sys | ||
| 19 | import tempfile | ||
| 20 | import types | ||
| 21 | import unittest | ||
| 22 | from pathlib import Path | ||
| 23 | from unittest import mock | ||
| 24 | |||
| 25 | ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | ||
| 26 | BUILD = os.path.join(ROOT, "runtime", "test", "shaders", "build.py") | ||
| 27 | FALLBACKS = ("LEONIDA_BARY_FALLBACK", "LEONIDA_F16_INTERP_FALLBACK") | ||
| 28 | |||
| 29 | |||
| 30 | def load_build(): | ||
| 31 | spec = importlib.util.spec_from_file_location("shaders_build_under_test", BUILD) | ||
| 32 | module = importlib.util.module_from_spec(spec) | ||
| 33 | spec.loader.exec_module(module) | ||
| 34 | return module | ||
| 35 | |||
| 36 | |||
| 37 | class BuildUnderFallbackTest(unittest.TestCase): | ||
| 38 | def setUp(self): | ||
| 39 | self.fresh() | ||
| 40 | |||
| 41 | def fresh(self): | ||
| 42 | """A new build.py, output folder and record of what the translator was asked for (one per subtest).""" | ||
| 43 | self.build = load_build() | ||
| 44 | tmp = tempfile.TemporaryDirectory() | ||
| 45 | self.addCleanup(tmp.cleanup) | ||
| 46 | self.out = Path(tmp.name) / "out" | ||
| 47 | self.asked = [] | ||
| 48 | |||
| 49 | def fake_translate(self, work, names): | ||
| 50 | """What rdna2spirv.py leaves in <work>/spirv: a module and an index entry per shader it validated.""" | ||
| 51 | self.asked.append(list(names)) | ||
| 52 | fallback = any(os.environ.get(v) == "1" for v in FALLBACKS) | ||
| 53 | spirv = Path(work) / "spirv" | ||
| 54 | spirv.mkdir(parents=True) | ||
| 55 | index = {} | ||
| 56 | for n in names: | ||
| 57 | if n == "ps_ij_computed" and fallback: | ||
| 58 | continue # "computed I/J pair under --f16-interp-fallback: no PerVertexKHR inputs" | ||
| 59 | (spirv / (n + ".spv")).write_bytes(b"\x03\x02\x23\x07") | ||
| 60 | (spirv / (n + ".spvasm")).write_text("; SPIR-V\n", encoding="utf-8") | ||
| 61 | index[n] = {"stage": n[:2]} | ||
| 62 | (spirv / "index.json").write_text(json.dumps(index), encoding="utf-8") | ||
| 63 | return 0 | ||
| 64 | |||
| 65 | def run_build(self, names, env): | ||
| 66 | stubs = {"spirv_stubs": types.SimpleNamespace(generate_for_index=lambda *a: None), | ||
| 67 | "bary_fallback_gs": types.SimpleNamespace(build_for_index=lambda *a: None)} | ||
| 68 | clean = {k: v for k, v in os.environ.items() if k not in FALLBACKS} | ||
| 69 | stdout = io.StringIO() | ||
| 70 | with mock.patch.dict(os.environ, {**clean, **env}, clear=True), \ | ||
| 71 | mock.patch.dict(sys.modules, stubs), \ | ||
| 72 | mock.patch.object(self.build, "translate_tests", self.fake_translate), \ | ||
| 73 | mock.patch.object(sys, "argv", ["build.py", str(self.out), *names]), \ | ||
| 74 | contextlib.redirect_stdout(stdout): | ||
| 75 | try: | ||
| 76 | status = self.build.main() | ||
| 77 | except SystemExit as e: | ||
| 78 | status = e.code | ||
| 79 | return status, stdout.getvalue() | ||
| 80 | |||
| 81 | def test_each_fallback_builds_the_rest_without_ps_ij_computed(self): | ||
| 82 | for var in FALLBACKS: | ||
| 83 | with self.subTest(fallback=var): | ||
| 84 | self.fresh() | ||
| 85 | status, printed = self.run_build(["cs_store", "ps_ij_computed"], {var: "1"}) | ||
| 86 | self.assertEqual(status, 0, printed) | ||
| 87 | self.assertEqual(self.asked, [["cs_store"]]) | ||
| 88 | self.assertTrue((self.out / "spirv" / "cs_store.spv").is_file()) | ||
| 89 | self.assertFalse((self.out / "spirv" / "ps_ij_computed.spv").exists()) | ||
| 90 | self.assertIn("ps_ij_computed", printed) | ||
| 91 | self.assertIn("PerVertexKHR", printed) | ||
| 92 | |||
| 93 | def test_the_whole_list_builds_under_a_fallback(self): | ||
| 94 | # Before: "Translation did not produce validated SPIR-V for: ps_ij_computed", and an empty <out>/spirv. | ||
| 95 | status, printed = self.run_build([], {"LEONIDA_F16_INTERP_FALLBACK": "1"}) | ||
| 96 | self.assertEqual(status, 0, printed) | ||
| 97 | self.assertNotIn("ps_ij_computed", self.asked[0]) | ||
| 98 | published = {p.stem for p in (self.out / "spirv").glob("*.spv")} | ||
| 99 | self.assertEqual(published, set(self.asked[0])) | ||
| 100 | self.assertIn("ps_interp_f16_high", published) # the f16 halves still translate under this fallback | ||
| 101 | |||
| 102 | def test_without_a_fallback_ps_ij_computed_is_still_built(self): | ||
| 103 | status, printed = self.run_build(["cs_store", "ps_ij_computed"], {}) | ||
| 104 | self.assertEqual(status, 0, printed) | ||
| 105 | self.assertEqual(self.asked, [["cs_store", "ps_ij_computed"]]) | ||
| 106 | self.assertTrue((self.out / "spirv" / "ps_ij_computed.spv").is_file()) | ||
| 107 | |||
| 108 | def test_a_missing_module_without_a_fallback_still_fails_the_batch(self): | ||
| 109 | keep = self.fake_translate | ||
| 110 | |||
| 111 | def refuse(work, names): | ||
| 112 | keep(work, names) | ||
| 113 | os.remove(os.path.join(work, "spirv", "cs_store.spv")) | ||
| 114 | return 0 | ||
| 115 | self.fake_translate = refuse | ||
| 116 | try: | ||
| 117 | status, _ = self.run_build(["cs_store"], {}) | ||
| 118 | finally: | ||
| 119 | self.fake_translate = keep | ||
| 120 | self.assertIn("did not produce validated SPIR-V for: cs_store", str(status)) | ||
| 121 | |||
| 122 | |||
| 123 | if __name__ == "__main__": | ||
| 124 | unittest.main() | ||
diff --git a/tests/test_shader_carve.py b/tests/test_shader_carve.py index b7c875c74..24b0b7a78 100644 --- a/tests/test_shader_carve.py +++ b/tests/test_shader_carve.py | |||
| @@ -449,11 +449,31 @@ class ShaderCarveCliIntegrationTest(unittest.TestCase): | |||
| 449 | f.write(make_rpf_entry("synthetic", 1, dxbc, compressed_override=compressed)) | 449 | f.write(make_rpf_entry("synthetic", 1, dxbc, compressed_override=compressed)) |
| 450 | 450 | ||
| 451 | res = self.run_carve(self.archive, self.out) | 451 | res = self.run_carve(self.archive, self.out) |
| 452 | self.assertEqual(res.returncode, 0, res.stderr) | 452 | self.assertEqual(res.returncode, 1, res.stderr) |
| 453 | self.assertIn("0 shaders carved, 1 candidates rejected", res.stdout) | 453 | self.assertIn("no shaders carved", res.stderr) |
| 454 | with open(os.path.join(self.out, "index.json"), encoding="utf-8") as f: | 454 | self.assertIn("rejected candidates: 1", res.stderr) |
| 455 | self.assertEqual(json.load(f), []) | 455 | self.assertEqual(os.listdir(self.out), []) |
| 456 | self.assertEqual(os.listdir(self.out), ["index.json"]) | 456 | |
| 457 | def test_empty_carve_preserves_an_existing_index(self): | ||
| 458 | dxbc = make_dxbc([(b"PRIV", bytes(range(32)))]) | ||
| 459 | with open(self.archive, "wb") as f: | ||
| 460 | f.write(make_rpf_entry("valid", 1, dxbc)) | ||
| 461 | initial = self.run_carve(self.archive, self.out) | ||
| 462 | self.assertEqual(initial.returncode, 0, initial.stderr) | ||
| 463 | index_path = os.path.join(self.out, "index.json") | ||
| 464 | with open(index_path, "rb") as f: | ||
| 465 | previous = f.read() | ||
| 466 | with open(self.archive, "wb") as f: | ||
| 467 | f.write(b"no shader entries") | ||
| 468 | |||
| 469 | res = self.run_carve(self.archive, self.out) | ||
| 470 | |||
| 471 | self.assertEqual(res.returncode, 1, res.stderr) | ||
| 472 | self.assertIn("no shaders carved", res.stderr) | ||
| 473 | self.assertIn("rejected candidates: 0", res.stderr) | ||
| 474 | with open(index_path, "rb") as f: | ||
| 475 | self.assertEqual(f.read(), previous) | ||
| 476 | self.assertEqual(sorted(os.listdir(self.out)), ["index.json", "valid.dxbc"]) | ||
| 457 | 477 | ||
| 458 | def test_carve_rejects_incomplete_parts_and_continues(self): | 478 | def test_carve_rejects_incomplete_parts_and_continues(self): |
| 459 | valid = make_dxbc([(b"PRIV", bytes(range(32)))]) | 479 | valid = make_dxbc([(b"PRIV", bytes(range(32)))]) |
diff --git a/tests/test_shader_checks.py b/tests/test_shader_checks.py index 9518c82c7..a9f6453ec 100644 --- a/tests/test_shader_checks.py +++ b/tests/test_shader_checks.py | |||
| @@ -16,6 +16,7 @@ import check | |||
| 16 | 16 | ||
| 17 | GOOD_FMT = struct.pack("<64I", *check.FMT_1010102_WORDS, *[0xEEEEEEEE] * 48) | 17 | GOOD_FMT = struct.pack("<64I", *check.FMT_1010102_WORDS, *[0xEEEEEEEE] * 48) |
| 18 | GOOD_XY_XYZ = struct.pack("<192I", *check.FMT_XY_XYZ_WORDS, *[0xEEEEEEEE] * 108) | 18 | GOOD_XY_XYZ = struct.pack("<192I", *check.FMT_XY_XYZ_WORDS, *[0xEEEEEEEE] * 108) |
| 19 | GOOD_TBUFFER_STORE = struct.pack("<192I", *check.TBUFFER_STORE_WORDS, *[0xEEEEEEEE] * 140) | ||
| 19 | FULL_WAVE = ((0, "compute subgroup size: 64\n0 mismatches\n"), | 20 | FULL_WAVE = ((0, "compute subgroup size: 64\n0 mismatches\n"), |
| 20 | (0, "compute subgroup size: 64\nout[0..7] = 32 16 24 40 8 48 4008636142 4008636142\n")) | 21 | (0, "compute subgroup size: 64\nout[0..7] = 32 16 24 40 8 48 4008636142 4008636142\n")) |
| 21 | 22 | ||
| @@ -29,11 +30,12 @@ WAVE32_WORDS = {n: w for n, w in check.CS_DUMPS if n in check.WAVE32_DUMPS and n | |||
| 29 | 30 | ||
| 30 | # All check.py cases, including the four vk_store_test shaders and the three mesh fixtures, and TEST-184's | 31 | # All check.py cases, including the four vk_store_test shaders and the three mesh fixtures, and TEST-184's |
| 31 | # vk_store_test "words" fixtures and image_get_lod draws. | 32 | # vk_store_test "words" fixtures and image_get_lod draws. |
| 32 | TOTAL = (len(check.COMPUTE) + 4 + len(check.CS_DUMPS) + len(check.W64X_DUMPS) + len(check.W64X_PARTIAL) + 4 | 33 | TOTAL = (len(check.COMPUTE) + 5 + len(check.CS_DUMPS) + len(check.W64X_DUMPS) + len(check.W64X_PARTIAL) + 4 |
| 33 | + len(check.PIXEL_TESTS) + len(check.CLIP_TESTS) + len(check.BOUNDS) + len(check.GLOBAL_OFFSET) | 34 | + len(check.PIXEL_TESTS) + len(check.CLIP_TESTS) + len(check.BOUNDS) + len(check.GLOBAL_OFFSET) |
| 34 | + len(check.MIP_TEST_PASSES) + len(check.GRADIENT_TESTS) | 35 | + len(check.MIP_TEST_PASSES) + len(check.GRADIENT_TESTS) |
| 35 | + len(check.STORE_WORDS) + len(check.GET_LOD_TESTS) | 36 | + len(check.STORE_WORDS) + len(check.GET_LOD_TESTS) |
| 36 | + len(check.TEXTURE_CONSTANTS) + 9) # three mesh fixtures, ps_tex, four compute fixtures and ps_ssharp | 37 | + len(check.TEXTURE_CONSTANTS) + 10) # three mesh fixtures, ps_tex, ps_imgatomic, four compute fixtures and |
| 38 | # ps_ssharp | ||
| 37 | CVT = {bits: [u, s] for bits, u, s in check.CVT_F32_SAT_CASES} | 39 | CVT = {bits: [u, s] for bits, u, s in check.CVT_F32_SAT_CASES} |
| 38 | 40 | ||
| 39 | 41 | ||
| @@ -69,9 +71,9 @@ class Wave64Checks(unittest.TestCase): | |||
| 69 | self.assertEqual((args, env["VKC_OUT_WORDS"]), (("1", "dump"), "64")) | 71 | self.assertEqual((args, env["VKC_OUT_WORDS"]), (("1", "dump"), "64")) |
| 70 | Path(env["VKC_DUMP"]).write_bytes(struct.pack("<64I", *check.FMT_SINT32_WORDS)) | 72 | Path(env["VKC_DUMP"]).write_bytes(struct.pack("<64I", *check.FMT_SINT32_WORDS)) |
| 71 | return 0, "" | 73 | return 0, "" |
| 72 | if name == "cs_fmt_xy_xyz": | 74 | if name in ("cs_fmt_xy_xyz", "cs_tbuffer_store"): |
| 73 | self.assertEqual((args, env["VKC_OUT_WORDS"]), (("1", "dump"), "192")) | 75 | self.assertEqual((args, env["VKC_OUT_WORDS"]), (("1", "dump"), "192")) |
| 74 | Path(env["VKC_DUMP"]).write_bytes(GOOD_XY_XYZ) | 76 | Path(env["VKC_DUMP"]).write_bytes(GOOD_XY_XYZ if name == "cs_fmt_xy_xyz" else GOOD_TBUFFER_STORE) |
| 75 | return 0, "out[0..7] = 0 0 0 0 0 0 0 0\n" | 77 | return 0, "out[0..7] = 0 0 0 0 0 0 0 0\n" |
| 76 | if name == "cs_user_sgprs": | 78 | if name == "cs_user_sgprs": |
| 77 | # The seeded words come back only if check.py passed them in VKC_SGPRS. | 79 | # The seeded words come back only if check.py passed them in VKC_SGPRS. |
| @@ -256,6 +258,23 @@ class FloatToIntSweep(unittest.TestCase): | |||
| 256 | self.assertIn("1 of 16 inputs wrong", problem) | 258 | self.assertIn("1 of 16 inputs wrong", problem) |
| 257 | self.assertIn("0x4f000000", problem) | 259 | self.assertIn("0x4f000000", problem) |
| 258 | 260 | ||
| 261 | def test_a_device_that_cannot_pin_the_wave_size_skips_instead_of_failing(self): | ||
| 262 | # Before: on a 4..32 device (Apple under MoltenVK) every dispatch came back as unpinned_subgroup_skip's Skip, | ||
| 263 | # and the sweep reported it as "16 of 16 inputs wrong, first 0x00000000: SKIP (...)", a failure. | ||
| 264 | calls = [] | ||
| 265 | |||
| 266 | def harness(_tool, _shader, *_args, env=None): | ||
| 267 | calls.append(env.get("VKC_SUBGROUP_SIZE")) | ||
| 268 | return 1, "compute subgroup size: 32 not available\n" | ||
| 269 | |||
| 270 | with patch.object(check, "run", side_effect=harness), \ | ||
| 271 | patch.object(check, "subgroup_size", return_value=32): | ||
| 272 | problem = check.cvt_f32_sat_test("tools", "spirv") | ||
| 273 | self.assertIsInstance(problem, check.Skip) | ||
| 274 | self.assertIn("can't run this shader at 32 lanes", problem) | ||
| 275 | self.assertNotIn("inputs wrong", problem) | ||
| 276 | self.assertEqual(calls, ["32"]) # the first dispatch decides; the other 15 would say the same | ||
| 277 | |||
| 259 | def test_inputs_match_the_interpreter_test(self): | 278 | def test_inputs_match_the_interpreter_test(self): |
| 260 | # The GPU sweep and tests/semantic/test_float_to_int.py must judge the same inputs the same way. | 279 | # The GPU sweep and tests/semantic/test_float_to_int.py must judge the same inputs the same way. |
| 261 | src = (Path(__file__).resolve().parent / "semantic" / "test_float_to_int.py").read_text(encoding="utf-8") | 280 | src = (Path(__file__).resolve().parent / "semantic" / "test_float_to_int.py").read_text(encoding="utf-8") |
diff --git a/tests/test_spirv_metal_set0_aliases.py b/tests/test_spirv_metal_set0_aliases.py new file mode 100644 index 000000000..6399ac7f1 --- /dev/null +++ b/tests/test_spirv_metal_set0_aliases.py | |||
| @@ -0,0 +1,386 @@ | |||
| 1 | """Regression tests for tools/spirv_metal_set0.py file hygiene and aliased set-0 bindings. | ||
| 2 | |||
| 3 | Standard library only; uses synthetic SPIR-V disassembly, no game data and no external SPIRV-Tools binaries. | ||
| 4 | |||
| 5 | python -I -W error::ResourceWarning tests/test_spirv_metal_set0_aliases.py -v | ||
| 6 | """ | ||
| 7 | import ast | ||
| 8 | import contextlib | ||
| 9 | import gc | ||
| 10 | import io | ||
| 11 | import os | ||
| 12 | import re | ||
| 13 | import sys | ||
| 14 | import tempfile | ||
| 15 | import unittest | ||
| 16 | import warnings | ||
| 17 | |||
| 18 | ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | ||
| 19 | TOOLS_DIR = os.path.join(ROOT, "tools") | ||
| 20 | TOOL_PATH = os.path.join(TOOLS_DIR, "spirv_metal_set0.py") | ||
| 21 | if TOOLS_DIR not in sys.path: | ||
| 22 | sys.path.insert(0, TOOLS_DIR) | ||
| 23 | |||
| 24 | import spirv_metal_set0 as m # noqa: E402 | ||
| 25 | |||
| 26 | |||
| 27 | def _parse_defs_and_order(text): | ||
| 28 | """Parse SSA definitions, check for duplicates and declaration-before-use ordering.""" | ||
| 29 | defs = {} | ||
| 30 | def_line = {} | ||
| 31 | decs = [] | ||
| 32 | lines = text.splitlines() | ||
| 33 | for idx, ln in enumerate(lines): | ||
| 34 | m_dec = re.match(r"^\s*OpDecorate (%\S+) (\S+) (\d+)$", ln) | ||
| 35 | if m_dec: | ||
| 36 | decs.append((m_dec.group(1), m_dec.group(2), int(m_dec.group(3)))) | ||
| 37 | continue | ||
| 38 | m_def = re.match(r"^\s*(%\S+) = (.*)$", ln) | ||
| 39 | if not m_def: | ||
| 40 | continue | ||
| 41 | rid, rhs = m_def.group(1), m_def.group(2) | ||
| 42 | if rid in defs: | ||
| 43 | raise AssertionError(f"duplicate SSA definition for {rid} at line {idx + 1}: {ln}") | ||
| 44 | defs[rid] = rhs | ||
| 45 | def_line[rid] = idx | ||
| 46 | |||
| 47 | # Verify declaration-before-use for constants, array types, pointers, and variables. | ||
| 48 | for rid, rhs in defs.items(): | ||
| 49 | cur = def_line[rid] | ||
| 50 | parts = rhs.split() | ||
| 51 | op = parts[0] | ||
| 52 | if op == "OpConstant": | ||
| 53 | ty = parts[1] | ||
| 54 | assert def_line[ty] < cur, f"{rid} uses {ty} before definition" | ||
| 55 | elif op == "OpTypeRuntimeArray": | ||
| 56 | elem = parts[1] | ||
| 57 | assert def_line[elem] < cur, f"{rid} uses {elem} before definition" | ||
| 58 | elif op == "OpTypeArray": | ||
| 59 | elem, length = parts[1], parts[2] | ||
| 60 | assert def_line[elem] < cur, f"{rid} uses {elem} before definition" | ||
| 61 | assert def_line[length] < cur, f"{rid} uses {length} before definition" | ||
| 62 | elif op == "OpTypePointer": | ||
| 63 | pointee = parts[2] | ||
| 64 | assert def_line[pointee] < cur, f"{rid} uses {pointee} before definition" | ||
| 65 | elif op == "OpVariable": | ||
| 66 | ptr = parts[1] | ||
| 67 | assert def_line[ptr] < cur, f"{rid} uses {ptr} before definition" | ||
| 68 | |||
| 69 | return defs, def_line, decs | ||
| 70 | |||
| 71 | |||
| 72 | class TestFileHygiene(unittest.TestCase): | ||
| 73 | def test_capacities_and_print_layout_emit_no_resource_warning(self): | ||
| 74 | with tempfile.TemporaryDirectory() as tmp: | ||
| 75 | good_hdr = os.path.join(tmp, "good.h") | ||
| 76 | bad_hdr = os.path.join(tmp, "bad.h") | ||
| 77 | with open(good_hdr, "w", encoding="utf-8") as f: | ||
| 78 | f.write("std::array<Binding, 2> bindings = {{{VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 16}, " | ||
| 79 | "{VK_DESCRIPTOR_TYPE_SAMPLER, 8}}};\n") | ||
| 80 | with open(bad_hdr, "w", encoding="utf-8") as f: | ||
| 81 | f.write("// missing table\n") | ||
| 82 | |||
| 83 | with warnings.catch_warnings(): | ||
| 84 | warnings.simplefilter("error", ResourceWarning) | ||
| 85 | counts = m.capacities() | ||
| 86 | self.assertEqual(len(counts), 26) | ||
| 87 | self.assertEqual(m.capacities(good_hdr), [16, 8]) | ||
| 88 | with self.assertRaises(SystemExit): | ||
| 89 | m.capacities(bad_hdr) | ||
| 90 | with contextlib.redirect_stdout(io.StringIO()): | ||
| 91 | self.assertEqual(m.main(["spirv_metal_set0.py", "--print-layout"]), 0) | ||
| 92 | gc.collect() | ||
| 93 | |||
| 94 | def test_spirv_metal_set0_has_no_unmanaged_open_calls(self): | ||
| 95 | with open(TOOL_PATH, encoding="utf-8") as f: | ||
| 96 | src = f.read() | ||
| 97 | tree = ast.parse(src, filename=TOOL_PATH) | ||
| 98 | managed = set() | ||
| 99 | for node in ast.walk(tree): | ||
| 100 | if isinstance(node, (ast.With, ast.AsyncWith)): | ||
| 101 | for item in node.items: | ||
| 102 | if isinstance(item.context_expr, ast.Call): | ||
| 103 | managed.add(id(item.context_expr)) | ||
| 104 | bare = [ | ||
| 105 | node.lineno | ||
| 106 | for node in ast.walk(tree) | ||
| 107 | if isinstance(node, ast.Call) | ||
| 108 | and isinstance(node.func, ast.Name) | ||
| 109 | and node.func.id == "open" | ||
| 110 | and id(node) not in managed | ||
| 111 | ] | ||
| 112 | self.assertEqual(bare, []) | ||
| 113 | |||
| 114 | |||
| 115 | class TestSingleAndAliasedBindings(unittest.TestCase): | ||
| 116 | def test_single_variable_bindings_keep_canonical_msl_ids(self): | ||
| 117 | module = """\ | ||
| 118 | OpDecorate %images DescriptorSet 0 | ||
| 119 | OpDecorate %images Binding 0 | ||
| 120 | OpDecorate %samplers DescriptorSet 0 | ||
| 121 | OpDecorate %samplers Binding 1 | ||
| 122 | OpDecorate %desc_map DescriptorSet 0 | ||
| 123 | OpDecorate %desc_map Binding 2 | ||
| 124 | %uint = OpTypeInt 32 0 | ||
| 125 | %float = OpTypeFloat 32 | ||
| 126 | %img2d = OpTypeImage %float 2D 0 0 0 1 Unknown | ||
| 127 | %smp = OpTypeSampler | ||
| 128 | %rt_img = OpTypeRuntimeArray %img2d | ||
| 129 | %rt_smp = OpTypeRuntimeArray %smp | ||
| 130 | %ptr_img = OpTypePointer UniformConstant %rt_img | ||
| 131 | %ptr_smp = OpTypePointer UniformConstant %rt_smp | ||
| 132 | %rt_map = OpTypeRuntimeArray %uint | ||
| 133 | %map = OpTypeStruct %rt_map | ||
| 134 | %ptr_map = OpTypePointer StorageBuffer %map | ||
| 135 | %images = OpVariable %ptr_img UniformConstant | ||
| 136 | %samplers = OpVariable %ptr_smp UniformConstant | ||
| 137 | %desc_map = OpVariable %ptr_map StorageBuffer | ||
| 138 | """ | ||
| 139 | counts = m.capacities() | ||
| 140 | out = m.rewrite(module, counts) | ||
| 141 | defs, _, decs = _parse_defs_and_order(out) | ||
| 142 | |||
| 143 | self.assertEqual(defs["%msl_cap_b0"], f"OpConstant %uint {counts[0]}") | ||
| 144 | self.assertEqual(defs["%msl_arr_b0"], "OpTypeArray %img2d %msl_cap_b0") | ||
| 145 | self.assertEqual(defs["%msl_ptr_b0"], "OpTypePointer UniformConstant %msl_arr_b0") | ||
| 146 | self.assertEqual(defs["%images"], "OpVariable %msl_ptr_b0 UniformConstant") | ||
| 147 | |||
| 148 | self.assertEqual(defs["%msl_cap_b1"], f"OpConstant %uint {counts[1]}") | ||
| 149 | self.assertEqual(defs["%msl_arr_b1"], "OpTypeArray %smp %msl_cap_b1") | ||
| 150 | self.assertEqual(defs["%msl_ptr_b1"], "OpTypePointer UniformConstant %msl_arr_b1") | ||
| 151 | self.assertEqual(defs["%samplers"], "OpVariable %msl_ptr_b1 UniformConstant") | ||
| 152 | self.assertEqual(defs["%desc_map"], "OpVariable %ptr_map StorageBuffer") | ||
| 153 | |||
| 154 | bindings = {vid: val for vid, kind, val in decs if kind == "Binding"} | ||
| 155 | self.assertEqual(bindings, {"%images": 0, "%samplers": 4096, "%desc_map": 5120}) | ||
| 156 | |||
| 157 | def test_distinct_element_type_aliases_at_same_binding(self): | ||
| 158 | # Mirrors tools/rdna2spirv.py emitting %images + typed %itx* aliases at binding 0 | ||
| 159 | # and %images_arr + %itx1_1 at binding 3, plus a 3D alias at binding 0. | ||
| 160 | module = """\ | ||
| 161 | OpDecorate %images DescriptorSet 0 | ||
| 162 | OpDecorate %images Binding 0 | ||
| 163 | OpDecorate %samplers DescriptorSet 0 | ||
| 164 | OpDecorate %samplers Binding 1 | ||
| 165 | OpDecorate %images_arr DescriptorSet 0 | ||
| 166 | OpDecorate %images_arr Binding 3 | ||
| 167 | OpDecorate %itx1_0 DescriptorSet 0 | ||
| 168 | OpDecorate %itx1_0 Binding 0 | ||
| 169 | OpDecorate %itx2_0 DescriptorSet 0 | ||
| 170 | OpDecorate %itx2_0 Binding 0 | ||
| 171 | OpDecorate %itx3d_0 DescriptorSet 0 | ||
| 172 | OpDecorate %itx3d_0 Binding 0 | ||
| 173 | OpDecorate %itx1_1 DescriptorSet 0 | ||
| 174 | OpDecorate %itx1_1 Binding 3 | ||
| 175 | %uint = OpTypeInt 32 0 | ||
| 176 | %int = OpTypeInt 32 1 | ||
| 177 | %float = OpTypeFloat 32 | ||
| 178 | %img2d = OpTypeImage %float 2D 0 0 0 1 Unknown | ||
| 179 | %smp = OpTypeSampler | ||
| 180 | %img2da = OpTypeImage %float 2D 0 1 0 1 Unknown | ||
| 181 | %itximg1_0 = OpTypeImage %uint 2D 0 0 0 1 Unknown | ||
| 182 | %itximg2_0 = OpTypeImage %int 2D 0 0 0 1 Unknown | ||
| 183 | %img_3d = OpTypeImage %float 3D 0 0 0 1 Unknown | ||
| 184 | %itximg1_1 = OpTypeImage %uint 2D 0 1 0 1 Unknown | ||
| 185 | %rt_img = OpTypeRuntimeArray %img2d | ||
| 186 | %ptr_img = OpTypePointer UniformConstant %rt_img | ||
| 187 | %rt_smp = OpTypeRuntimeArray %smp | ||
| 188 | %ptr_smp = OpTypePointer UniformConstant %rt_smp | ||
| 189 | %rt_imga = OpTypeRuntimeArray %img2da | ||
| 190 | %ptr_imga = OpTypePointer UniformConstant %rt_imga | ||
| 191 | %rt_itx10 = OpTypeRuntimeArray %itximg1_0 | ||
| 192 | %ptr_itx10 = OpTypePointer UniformConstant %rt_itx10 | ||
| 193 | %rt_itx20 = OpTypeRuntimeArray %itximg2_0 | ||
| 194 | %ptr_itx20 = OpTypePointer UniformConstant %rt_itx20 | ||
| 195 | %rt_3d0 = OpTypeRuntimeArray %img_3d | ||
| 196 | %ptr_3d0 = OpTypePointer UniformConstant %rt_3d0 | ||
| 197 | %rt_itx11 = OpTypeRuntimeArray %itximg1_1 | ||
| 198 | %ptr_itx11 = OpTypePointer UniformConstant %rt_itx11 | ||
| 199 | %images = OpVariable %ptr_img UniformConstant | ||
| 200 | %samplers = OpVariable %ptr_smp UniformConstant | ||
| 201 | %images_arr = OpVariable %ptr_imga UniformConstant | ||
| 202 | %itx1_0 = OpVariable %ptr_itx10 UniformConstant | ||
| 203 | %itx2_0 = OpVariable %ptr_itx20 UniformConstant | ||
| 204 | %itx3d_0 = OpVariable %ptr_3d0 UniformConstant | ||
| 205 | %itx1_1 = OpVariable %ptr_itx11 UniformConstant | ||
| 206 | """ | ||
| 207 | counts = m.capacities() | ||
| 208 | ids = m.metal_ids(counts) | ||
| 209 | out = m.rewrite(module, counts) | ||
| 210 | defs, _, decs = _parse_defs_and_order(out) | ||
| 211 | |||
| 212 | # OpConstant is emitted once per binding that has UniformConstant runtime arrays. | ||
| 213 | b0_consts = [rid for rid, rhs in defs.items() if rhs == f"OpConstant %uint {counts[0]}"] | ||
| 214 | b1_b3_consts = [rid for rid, rhs in defs.items() if rhs == f"OpConstant %uint {counts[3]}"] | ||
| 215 | self.assertEqual(b0_consts, ["%msl_cap_b0"]) | ||
| 216 | self.assertEqual(counts[1], counts[3]) | ||
| 217 | self.assertEqual(b1_b3_consts, ["%msl_cap_b1", "%msl_cap_b3"]) | ||
| 218 | for b in (0, 1, 3): | ||
| 219 | self.assertEqual(out.count(f"%msl_cap_b{b} = "), 1) | ||
| 220 | |||
| 221 | # Every variable keeps the exact element type of its original runtime array and binding capacity. | ||
| 222 | expected_vars = { | ||
| 223 | "%images": ("%img2d", "%msl_cap_b0", ids[0]), | ||
| 224 | "%samplers": ("%smp", "%msl_cap_b1", ids[1]), | ||
| 225 | "%images_arr": ("%img2da", "%msl_cap_b3", ids[3]), | ||
| 226 | "%itx1_0": ("%itximg1_0", "%msl_cap_b0", ids[0]), | ||
| 227 | "%itx2_0": ("%itximg2_0", "%msl_cap_b0", ids[0]), | ||
| 228 | "%itx3d_0": ("%img_3d", "%msl_cap_b0", ids[0]), | ||
| 229 | "%itx1_1": ("%itximg1_1", "%msl_cap_b3", ids[3]), | ||
| 230 | } | ||
| 231 | bindings = {vid: val for vid, kind, val in decs if kind == "Binding"} | ||
| 232 | seen_ptrs = set() | ||
| 233 | for var_id, (elem, cap, expected_bind) in expected_vars.items(): | ||
| 234 | self.assertEqual(bindings[var_id], expected_bind) | ||
| 235 | m_var = re.match(r"^OpVariable (%\S+) UniformConstant$", defs[var_id]) | ||
| 236 | self.assertIsNotNone(m_var, defs[var_id]) | ||
| 237 | ptr_id = m_var.group(1) | ||
| 238 | seen_ptrs.add(ptr_id) | ||
| 239 | m_ptr = re.match(r"^OpTypePointer UniformConstant (%\S+)$", defs[ptr_id]) | ||
| 240 | self.assertIsNotNone(m_ptr, defs[ptr_id]) | ||
| 241 | arr_id = m_ptr.group(1) | ||
| 242 | self.assertEqual(defs[arr_id], f"OpTypeArray {elem} {cap}") | ||
| 243 | |||
| 244 | # Distinct element types get distinct pointer types. | ||
| 245 | self.assertEqual(len(seen_ptrs), len(expected_vars)) | ||
| 246 | |||
| 247 | def test_reversed_decoration_order_still_declares_cap_before_first_array(self): | ||
| 248 | # %itx1_0 is decorated before %images, yet %ptr_img is declared before %ptr_itx. | ||
| 249 | module = """\ | ||
| 250 | OpDecorate %itx1_0 DescriptorSet 0 | ||
| 251 | OpDecorate %itx1_0 Binding 0 | ||
| 252 | OpDecorate %images DescriptorSet 0 | ||
| 253 | OpDecorate %images Binding 0 | ||
| 254 | %uint = OpTypeInt 32 0 | ||
| 255 | %int = OpTypeInt 32 1 | ||
| 256 | %float = OpTypeFloat 32 | ||
| 257 | %img2d = OpTypeImage %float 2D 0 0 0 1 Unknown | ||
| 258 | %itximg1_0 = OpTypeImage %int 2D 0 0 0 1 Unknown | ||
| 259 | %rt_img = OpTypeRuntimeArray %img2d | ||
| 260 | %ptr_img = OpTypePointer UniformConstant %rt_img | ||
| 261 | %rt_itx = OpTypeRuntimeArray %itximg1_0 | ||
| 262 | %ptr_itx = OpTypePointer UniformConstant %rt_itx | ||
| 263 | %images = OpVariable %ptr_img UniformConstant | ||
| 264 | %itx1_0 = OpVariable %ptr_itx UniformConstant | ||
| 265 | """ | ||
| 266 | out = m.rewrite(module, [4096]) | ||
| 267 | defs, def_line, decs = _parse_defs_and_order(out) | ||
| 268 | |||
| 269 | self.assertLess(def_line["%msl_cap_b0"], def_line["%msl_arr_b0"]) | ||
| 270 | self.assertLess(def_line["%msl_cap_b0"], def_line["%msl_arr_b0_1"]) | ||
| 271 | self.assertEqual(defs["%images"], "OpVariable %msl_ptr_b0 UniformConstant") | ||
| 272 | self.assertEqual(defs["%itx1_0"], "OpVariable %msl_ptr_b0_1 UniformConstant") | ||
| 273 | self.assertEqual(defs["%msl_arr_b0"], "OpTypeArray %img2d %msl_cap_b0") | ||
| 274 | self.assertEqual(defs["%msl_arr_b0_1"], "OpTypeArray %itximg1_0 %msl_cap_b0") | ||
| 275 | self.assertEqual([(v, val) for v, k, val in decs if k == "Binding"], [("%itx1_0", 0), ("%images", 0)]) | ||
| 276 | |||
| 277 | def test_same_binding_and_same_optypepointer_shares_sized_type_without_duplicates(self): | ||
| 278 | module = """\ | ||
| 279 | OpDecorate %images DescriptorSet 0 | ||
| 280 | OpDecorate %images Binding 0 | ||
| 281 | OpDecorate %alias DescriptorSet 0 | ||
| 282 | OpDecorate %alias Binding 0 | ||
| 283 | OpDecorate %single DescriptorSet 0 | ||
| 284 | OpDecorate %single Binding 0 | ||
| 285 | %uint = OpTypeInt 32 0 | ||
| 286 | %float = OpTypeFloat 32 | ||
| 287 | %img2d = OpTypeImage %float 2D 0 0 0 1 Unknown | ||
| 288 | %rt_img = OpTypeRuntimeArray %img2d | ||
| 289 | %ptr_img = OpTypePointer UniformConstant %rt_img | ||
| 290 | %ptr_one = OpTypePointer UniformConstant %img2d | ||
| 291 | %images = OpVariable %ptr_img UniformConstant | ||
| 292 | %alias = OpVariable %ptr_img UniformConstant | ||
| 293 | %single = OpVariable %ptr_one UniformConstant | ||
| 294 | """ | ||
| 295 | out = m.rewrite(module, [128]) | ||
| 296 | defs, _, decs = _parse_defs_and_order(out) | ||
| 297 | |||
| 298 | self.assertEqual(defs["%msl_cap_b0"], "OpConstant %uint 128") | ||
| 299 | self.assertEqual(defs["%msl_arr_b0"], "OpTypeArray %img2d %msl_cap_b0") | ||
| 300 | self.assertEqual(defs["%msl_ptr_b0"], "OpTypePointer UniformConstant %msl_arr_b0") | ||
| 301 | self.assertEqual(defs["%images"], "OpVariable %msl_ptr_b0 UniformConstant") | ||
| 302 | self.assertEqual(defs["%alias"], "OpVariable %msl_ptr_b0 UniformConstant") | ||
| 303 | self.assertEqual(defs["%single"], "OpVariable %ptr_one UniformConstant") | ||
| 304 | self.assertEqual(out.count("%msl_cap_b0 = "), 1) | ||
| 305 | self.assertEqual(out.count("%msl_arr_b0 = "), 1) | ||
| 306 | self.assertEqual(out.count("%msl_ptr_b0 = "), 1) | ||
| 307 | self.assertEqual({v: val for v, k, val in decs if k == "Binding"}, | ||
| 308 | {"%images": 0, "%alias": 0, "%single": 0}) | ||
| 309 | |||
| 310 | def test_same_binding_and_same_element_via_distinct_pointers(self): | ||
| 311 | module = """\ | ||
| 312 | OpDecorate %v1 DescriptorSet 0 | ||
| 313 | OpDecorate %v1 Binding 0 | ||
| 314 | OpDecorate %v2 DescriptorSet 0 | ||
| 315 | OpDecorate %v2 Binding 0 | ||
| 316 | %uint = OpTypeInt 32 0 | ||
| 317 | %float = OpTypeFloat 32 | ||
| 318 | %img2d = OpTypeImage %float 2D 0 0 0 1 Unknown | ||
| 319 | %rt_a = OpTypeRuntimeArray %img2d | ||
| 320 | %ptr_a = OpTypePointer UniformConstant %rt_a | ||
| 321 | %rt_b = OpTypeRuntimeArray %img2d | ||
| 322 | %ptr_b = OpTypePointer UniformConstant %rt_b | ||
| 323 | %v1 = OpVariable %ptr_a UniformConstant | ||
| 324 | %v2 = OpVariable %ptr_b UniformConstant | ||
| 325 | """ | ||
| 326 | out = m.rewrite(module, [64]) | ||
| 327 | defs, def_line, _ = _parse_defs_and_order(out) | ||
| 328 | |||
| 329 | for var_id in ("%v1", "%v2"): | ||
| 330 | m_var = re.match(r"^OpVariable (%\S+) UniformConstant$", defs[var_id]) | ||
| 331 | self.assertIsNotNone(m_var) | ||
| 332 | ptr_id = m_var.group(1) | ||
| 333 | self.assertLess(def_line[ptr_id], def_line[var_id]) | ||
| 334 | m_ptr = re.match(r"^OpTypePointer UniformConstant (%\S+)$", defs[ptr_id]) | ||
| 335 | self.assertIsNotNone(m_ptr) | ||
| 336 | self.assertEqual(defs[m_ptr.group(1)], "OpTypeArray %img2d %msl_cap_b0") | ||
| 337 | |||
| 338 | def test_preexisting_msl_ids_in_input_never_collide(self): | ||
| 339 | module = """\ | ||
| 340 | OpDecorate %images DescriptorSet 0 | ||
| 341 | OpDecorate %images Binding 0 | ||
| 342 | OpDecorate %itx1_0 DescriptorSet 0 | ||
| 343 | OpDecorate %itx1_0 Binding 0 | ||
| 344 | %uint = OpTypeInt 32 0 | ||
| 345 | %int = OpTypeInt 32 1 | ||
| 346 | %float = OpTypeFloat 32 | ||
| 347 | %msl_cap_b0 = OpConstant %uint 7 | ||
| 348 | %msl_arr_b0 = OpTypeFloat 16 | ||
| 349 | %msl_ptr_b0 = OpTypeStruct %float | ||
| 350 | %msl_arr_b0_1 = OpConstant %uint 9 | ||
| 351 | %img2d = OpTypeImage %float 2D 0 0 0 1 Unknown | ||
| 352 | %itximg1_0 = OpTypeImage %int 2D 0 0 0 1 Unknown | ||
| 353 | %rt_img = OpTypeRuntimeArray %img2d | ||
| 354 | %ptr_img = OpTypePointer UniformConstant %rt_img | ||
| 355 | %rt_itx = OpTypeRuntimeArray %itximg1_0 | ||
| 356 | %ptr_itx = OpTypePointer UniformConstant %rt_itx | ||
| 357 | %images = OpVariable %ptr_img UniformConstant | ||
| 358 | %itx1_0 = OpVariable %ptr_itx UniformConstant | ||
| 359 | """ | ||
| 360 | out = m.rewrite(module, [4096]) | ||
| 361 | defs, _, _ = _parse_defs_and_order(out) | ||
| 362 | |||
| 363 | # Pre-existing IDs keep their original definitions untouched. | ||
| 364 | self.assertEqual(defs["%msl_cap_b0"], "OpConstant %uint 7") | ||
| 365 | self.assertEqual(defs["%msl_arr_b0"], "OpTypeFloat 16") | ||
| 366 | self.assertEqual(defs["%msl_ptr_b0"], "OpTypeStruct %float") | ||
| 367 | self.assertEqual(defs["%msl_arr_b0_1"], "OpConstant %uint 9") | ||
| 368 | |||
| 369 | # Newly synthesized IDs avoid every existing definition and match each variable's element type. | ||
| 370 | m_img = re.match(r"^OpVariable (%\S+) UniformConstant$", defs["%images"]) | ||
| 371 | m_itx = re.match(r"^OpVariable (%\S+) UniformConstant$", defs["%itx1_0"]) | ||
| 372 | self.assertIsNotNone(m_img) | ||
| 373 | self.assertIsNotNone(m_itx) | ||
| 374 | ptr_img, ptr_itx = m_img.group(1), m_itx.group(1) | ||
| 375 | self.assertNotEqual(ptr_img, ptr_itx) | ||
| 376 | |||
| 377 | arr_img = re.match(r"^OpTypePointer UniformConstant (%\S+)$", defs[ptr_img]).group(1) | ||
| 378 | arr_itx = re.match(r"^OpTypePointer UniformConstant (%\S+)$", defs[ptr_itx]).group(1) | ||
| 379 | cap_img = re.match(r"^OpTypeArray %img2d (%\S+)$", defs[arr_img]).group(1) | ||
| 380 | cap_itx = re.match(r"^OpTypeArray %itximg1_0 (%\S+)$", defs[arr_itx]).group(1) | ||
| 381 | self.assertEqual(cap_img, cap_itx) | ||
| 382 | self.assertEqual(defs[cap_img], "OpConstant %uint 4096") | ||
| 383 | |||
| 384 | |||
| 385 | if __name__ == "__main__": | ||
| 386 | unittest.main() | ||
diff --git a/tests/test_spirv_metal_set0_extra.py b/tests/test_spirv_metal_set0_extra.py new file mode 100644 index 000000000..5b03f429e --- /dev/null +++ b/tests/test_spirv_metal_set0_extra.py | |||
| @@ -0,0 +1,1043 @@ | |||
| 1 | """Expanded stdlib-only unit tests for tools/spirv_metal_set0.py. | ||
| 2 | |||
| 3 | Covers bindless capacity parsing from vulkan_bindless.h and custom headers, | ||
| 4 | metal_ids() layout math, rewrite() across all 26 bindings, non-set-0 / | ||
| 5 | push-constant / non-runtime-array / pre-sized / raw-ID / error branches, | ||
| 6 | synthetic SPIR-V binary word header/magic/endianness/bounds handling, | ||
| 7 | out-of-place vs in-place CLI execution via mocked spirv-dis/spirv-as, | ||
| 8 | --print-layout, invalid argument handling, and __main__ entry guard. | ||
| 9 | |||
| 10 | Standard library only; no spirv-dis/spirv-as/spirv-val binary, no GPU, | ||
| 11 | and no game data. | ||
| 12 | |||
| 13 | python -I tests/test_spirv_metal_set0_extra.py -v | ||
| 14 | """ | ||
| 15 | import contextlib | ||
| 16 | import io | ||
| 17 | import os | ||
| 18 | import re | ||
| 19 | import runpy | ||
| 20 | import struct | ||
| 21 | import subprocess | ||
| 22 | import sys | ||
| 23 | import tempfile | ||
| 24 | import unittest | ||
| 25 | from unittest import mock | ||
| 26 | import warnings | ||
| 27 | |||
| 28 | ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | ||
| 29 | TOOLS_DIR = os.path.join(ROOT, "tools") | ||
| 30 | TOOL_PATH = os.path.join(TOOLS_DIR, "spirv_metal_set0.py") | ||
| 31 | if TOOLS_DIR not in sys.path: | ||
| 32 | sys.path.insert(0, TOOLS_DIR) | ||
| 33 | |||
| 34 | import spirv_metal_set0 as m # noqa: E402 | ||
| 35 | |||
| 36 | |||
| 37 | SPIRV_MAGIC = 0x07230203 | ||
| 38 | SPIRV_VERSION_1_0 = 0x00010000 | ||
| 39 | SPIRV_VERSION_1_5 = 0x00010500 | ||
| 40 | |||
| 41 | OP_MEMORY_MODEL = 14 | ||
| 42 | OP_CAPABILITY = 17 | ||
| 43 | OP_TYPE_VOID = 19 | ||
| 44 | OP_TYPE_INT = 21 | ||
| 45 | OP_TYPE_FLOAT = 22 | ||
| 46 | OP_TYPE_IMAGE = 25 | ||
| 47 | OP_TYPE_SAMPLER = 26 | ||
| 48 | OP_TYPE_ARRAY = 28 | ||
| 49 | OP_TYPE_RUNTIME_ARRAY = 29 | ||
| 50 | OP_TYPE_STRUCT = 30 | ||
| 51 | OP_TYPE_POINTER = 32 | ||
| 52 | OP_CONSTANT = 43 | ||
| 53 | OP_VARIABLE = 59 | ||
| 54 | OP_DECORATE = 71 | ||
| 55 | |||
| 56 | CAP_SHADER = 1 | ||
| 57 | CAP_RUNTIME_DESCRIPTOR_ARRAY = 5301 | ||
| 58 | ADDR_LOGICAL = 0 | ||
| 59 | MEM_GLSL450 = 1 | ||
| 60 | |||
| 61 | DEC_BLOCK = 2 | ||
| 62 | DEC_BINDING = 33 | ||
| 63 | DEC_DESCRIPTOR_SET = 34 | ||
| 64 | |||
| 65 | SC_UNIFORM_CONSTANT = 0 | ||
| 66 | SC_PUSH_CONSTANT = 9 | ||
| 67 | SC_STORAGE_BUFFER = 12 | ||
| 68 | |||
| 69 | STORAGE_CLASS_BY_NAME = { | ||
| 70 | "UniformConstant": SC_UNIFORM_CONSTANT, | ||
| 71 | "PushConstant": SC_PUSH_CONSTANT, | ||
| 72 | "StorageBuffer": SC_STORAGE_BUFFER, | ||
| 73 | } | ||
| 74 | STORAGE_CLASS_BY_CODE = {v: k for k, v in STORAGE_CLASS_BY_NAME.items()} | ||
| 75 | |||
| 76 | DIM_BY_CODE = {0: "1D", 1: "2D", 2: "3D"} | ||
| 77 | DIM_BY_NAME = {v: k for k, v in DIM_BY_CODE.items()} | ||
| 78 | |||
| 79 | FMT_BY_CODE = {0: "Unknown", 33: "R32ui"} | ||
| 80 | FMT_BY_NAME = {v: k for k, v in FMT_BY_CODE.items()} | ||
| 81 | |||
| 82 | |||
| 83 | def _encode_inst(opcode: int, *operands: int) -> list[int]: | ||
| 84 | """Encode one SPIR-V instruction into 32-bit binary words.""" | ||
| 85 | wc = 1 + len(operands) | ||
| 86 | return [(wc << 16) | opcode, *operands] | ||
| 87 | |||
| 88 | |||
| 89 | def _pack_spv( | ||
| 90 | inst_words: list[int], | ||
| 91 | *, | ||
| 92 | version: int = SPIRV_VERSION_1_5, | ||
| 93 | generator: int = 0, | ||
| 94 | bound: int | None = None, | ||
| 95 | schema: int = 0, | ||
| 96 | endian: str = "<", | ||
| 97 | ) -> bytes: | ||
| 98 | """Pack a 5-word SPIR-V header and instruction stream into binary bytes.""" | ||
| 99 | if bound is None: | ||
| 100 | max_id = 0 | ||
| 101 | pos = 0 | ||
| 102 | while pos < len(inst_words): | ||
| 103 | wc = inst_words[pos] >> 16 | ||
| 104 | op = inst_words[pos] & 0xFFFF | ||
| 105 | if wc < 1 or pos + wc > len(inst_words): | ||
| 106 | break | ||
| 107 | ops = inst_words[pos + 1 : pos + wc] | ||
| 108 | if op in (OP_TYPE_VOID, OP_TYPE_INT, OP_TYPE_FLOAT, OP_TYPE_IMAGE, OP_TYPE_SAMPLER, | ||
| 109 | OP_TYPE_ARRAY, OP_TYPE_RUNTIME_ARRAY, OP_TYPE_STRUCT, OP_TYPE_POINTER): | ||
| 110 | max_id = max(max_id, ops[0]) | ||
| 111 | elif op in (OP_CONSTANT, OP_VARIABLE): | ||
| 112 | max_id = max(max_id, ops[1]) | ||
| 113 | elif op == OP_DECORATE: | ||
| 114 | max_id = max(max_id, ops[0]) | ||
| 115 | pos += wc | ||
| 116 | bound = max_id + 1 | ||
| 117 | words = [SPIRV_MAGIC, version, generator, bound, schema, *inst_words] | ||
| 118 | return struct.pack(f"{endian}{len(words)}I", *words) | ||
| 119 | |||
| 120 | |||
| 121 | def _decode_spv(data: bytes) -> tuple[tuple[int, int, int, int, int], list[tuple[int, list[int]]]]: | ||
| 122 | """Validate SPIR-V binary header/endianness/word-bounds and decode instructions.""" | ||
| 123 | if len(data) < 20 or len(data) % 4 != 0: | ||
| 124 | raise ValueError(f"invalid SPIR-V byte length: {len(data)}") | ||
| 125 | words = list(struct.unpack(f"<{len(data) // 4}I", data)) | ||
| 126 | magic, version, generator, bound, schema = words[:5] | ||
| 127 | if magic == 0x03022307: | ||
| 128 | raise ValueError("wrong endianness (big-endian SPIR-V magic)") | ||
| 129 | if magic != SPIRV_MAGIC: | ||
| 130 | raise ValueError(f"bad SPIR-V magic: {magic:#010x}") | ||
| 131 | if bound < 1: | ||
| 132 | raise ValueError(f"invalid SPIR-V ID bound: {bound}") | ||
| 133 | if schema != 0: | ||
| 134 | raise ValueError(f"unsupported non-zero schema: {schema}") | ||
| 135 | insts = [] | ||
| 136 | pos = 5 | ||
| 137 | while pos < len(words): | ||
| 138 | wc = words[pos] >> 16 | ||
| 139 | op = words[pos] & 0xFFFF | ||
| 140 | if wc < 1 or pos + wc > len(words): | ||
| 141 | raise ValueError(f"truncated or zero-length instruction at word {pos}") | ||
| 142 | insts.append((op, words[pos + 1 : pos + wc])) | ||
| 143 | pos += wc | ||
| 144 | return (magic, version, generator, bound, schema), insts | ||
| 145 | |||
| 146 | |||
| 147 | def _synthetic_spv_to_disasm(data: bytes) -> str: | ||
| 148 | """Decode synthetic SPIR-V binary words into spirv-dis-style assembly text.""" | ||
| 149 | header, insts = _decode_spv(data) | ||
| 150 | _, version, generator, bound, schema = header | ||
| 151 | major = (version >> 16) & 0xFF | ||
| 152 | minor = (version >> 8) & 0xFF | ||
| 153 | lines = [ | ||
| 154 | "; SPIR-V", | ||
| 155 | f"; Version: {major}.{minor}", | ||
| 156 | f"; Generator: {generator}", | ||
| 157 | f"; Bound: {bound}", | ||
| 158 | f"; Schema: {schema}", | ||
| 159 | ] | ||
| 160 | indent = " " * 15 | ||
| 161 | def lhs(res_id: int) -> str: | ||
| 162 | return f"%{res_id}".rjust(12) | ||
| 163 | |||
| 164 | for op, ops in insts: | ||
| 165 | if op == OP_CAPABILITY: | ||
| 166 | name = {CAP_SHADER: "Shader", CAP_RUNTIME_DESCRIPTOR_ARRAY: "RuntimeDescriptorArray"}[ops[0]] | ||
| 167 | lines.append(f"{indent}OpCapability {name}") | ||
| 168 | elif op == OP_MEMORY_MODEL: | ||
| 169 | lines.append(f"{indent}OpMemoryModel Logical GLSL450") | ||
| 170 | elif op == OP_DECORATE: | ||
| 171 | if ops[1] == DEC_DESCRIPTOR_SET: | ||
| 172 | lines.append(f"{indent}OpDecorate %{ops[0]} DescriptorSet {ops[2]}") | ||
| 173 | elif ops[1] == DEC_BINDING: | ||
| 174 | lines.append(f"{indent}OpDecorate %{ops[0]} Binding {ops[2]}") | ||
| 175 | elif ops[1] == DEC_BLOCK: | ||
| 176 | lines.append(f"{indent}OpDecorate %{ops[0]} Block") | ||
| 177 | else: | ||
| 178 | raise ValueError(f"unsupported decoration {ops[1]}") | ||
| 179 | elif op == OP_TYPE_VOID: | ||
| 180 | lines.append(f"{lhs(ops[0])} = OpTypeVoid") | ||
| 181 | elif op == OP_TYPE_INT: | ||
| 182 | lines.append(f"{lhs(ops[0])} = OpTypeInt {ops[1]} {ops[2]}") | ||
| 183 | elif op == OP_TYPE_FLOAT: | ||
| 184 | lines.append(f"{lhs(ops[0])} = OpTypeFloat {ops[1]}") | ||
| 185 | elif op == OP_TYPE_IMAGE: | ||
| 186 | dim = DIM_BY_CODE[ops[2]] | ||
| 187 | fmt = FMT_BY_CODE[ops[7]] | ||
| 188 | lines.append( | ||
| 189 | f"{lhs(ops[0])} = OpTypeImage %{ops[1]} {dim} {ops[3]} {ops[4]} {ops[5]} {ops[6]} {fmt}" | ||
| 190 | ) | ||
| 191 | elif op == OP_TYPE_SAMPLER: | ||
| 192 | lines.append(f"{lhs(ops[0])} = OpTypeSampler") | ||
| 193 | elif op == OP_TYPE_ARRAY: | ||
| 194 | lines.append(f"{lhs(ops[0])} = OpTypeArray %{ops[1]} %{ops[2]}") | ||
| 195 | elif op == OP_TYPE_RUNTIME_ARRAY: | ||
| 196 | lines.append(f"{lhs(ops[0])} = OpTypeRuntimeArray %{ops[1]}") | ||
| 197 | elif op == OP_TYPE_STRUCT: | ||
| 198 | members = " ".join(f"%{m_id}" for m_id in ops[1:]) | ||
| 199 | lines.append(f"{lhs(ops[0])} = OpTypeStruct {members}".rstrip()) | ||
| 200 | elif op == OP_TYPE_POINTER: | ||
| 201 | sc = STORAGE_CLASS_BY_CODE[ops[1]] | ||
| 202 | lines.append(f"{lhs(ops[0])} = OpTypePointer {sc} %{ops[2]}") | ||
| 203 | elif op == OP_CONSTANT: | ||
| 204 | lines.append(f"{lhs(ops[1])} = OpConstant %{ops[0]} {ops[2]}") | ||
| 205 | elif op == OP_VARIABLE: | ||
| 206 | sc = STORAGE_CLASS_BY_CODE[ops[2]] | ||
| 207 | lines.append(f"{lhs(ops[1])} = OpVariable %{ops[0]} {sc}") | ||
| 208 | else: | ||
| 209 | raise ValueError(f"unsupported opcode {op}") | ||
| 210 | return "\n".join(lines) + "\n" | ||
| 211 | |||
| 212 | |||
| 213 | def _synthetic_disasm_to_spv(text: str, target_env: str) -> bytes: | ||
| 214 | """Assemble synthetic spirv-dis text (including rewritten %msl_* IDs) into SPIR-V words.""" | ||
| 215 | id_map: dict[str, int] = {} | ||
| 216 | next_id = 1 | ||
| 217 | |||
| 218 | def resolve(tok: str) -> int: | ||
| 219 | nonlocal next_id | ||
| 220 | if tok in id_map: | ||
| 221 | return id_map[tok] | ||
| 222 | if tok[1:].isdigit(): | ||
| 223 | val = int(tok[1:]) | ||
| 224 | id_map[tok] = val | ||
| 225 | next_id = max(next_id, val + 1) | ||
| 226 | return val | ||
| 227 | val = next_id | ||
| 228 | next_id += 1 | ||
| 229 | id_map[tok] = val | ||
| 230 | return val | ||
| 231 | |||
| 232 | # Pre-register numeric IDs so newly synthesized %msl_* names never collide. | ||
| 233 | for tok in re.findall(r"%\S+", text): | ||
| 234 | if tok[1:].isdigit(): | ||
| 235 | resolve(tok) | ||
| 236 | |||
| 237 | inst_words: list[int] = [] | ||
| 238 | for raw in text.splitlines(): | ||
| 239 | line = raw.strip() | ||
| 240 | if not line or line.startswith(";"): | ||
| 241 | continue | ||
| 242 | if line.startswith("OpCapability "): | ||
| 243 | cap = {"Shader": CAP_SHADER, "RuntimeDescriptorArray": CAP_RUNTIME_DESCRIPTOR_ARRAY}[line.split()[1]] | ||
| 244 | inst_words.extend(_encode_inst(OP_CAPABILITY, cap)) | ||
| 245 | elif line == "OpMemoryModel Logical GLSL450": | ||
| 246 | inst_words.extend(_encode_inst(OP_MEMORY_MODEL, ADDR_LOGICAL, MEM_GLSL450)) | ||
| 247 | elif line.startswith("OpDecorate "): | ||
| 248 | parts = line.split() | ||
| 249 | tid = resolve(parts[1]) | ||
| 250 | if parts[2] == "DescriptorSet": | ||
| 251 | inst_words.extend(_encode_inst(OP_DECORATE, tid, DEC_DESCRIPTOR_SET, int(parts[3]))) | ||
| 252 | elif parts[2] == "Binding": | ||
| 253 | inst_words.extend(_encode_inst(OP_DECORATE, tid, DEC_BINDING, int(parts[3]))) | ||
| 254 | elif parts[2] == "Block": | ||
| 255 | inst_words.extend(_encode_inst(OP_DECORATE, tid, DEC_BLOCK)) | ||
| 256 | else: | ||
| 257 | raise ValueError(f"unsupported OpDecorate: {line}") | ||
| 258 | else: | ||
| 259 | lhs, rhs = [p.strip() for p in line.split("=", 1)] | ||
| 260 | rid = resolve(lhs) | ||
| 261 | parts = rhs.split() | ||
| 262 | opname = parts[0] | ||
| 263 | if opname == "OpTypeVoid": | ||
| 264 | inst_words.extend(_encode_inst(OP_TYPE_VOID, rid)) | ||
| 265 | elif opname == "OpTypeInt": | ||
| 266 | inst_words.extend(_encode_inst(OP_TYPE_INT, rid, int(parts[1]), int(parts[2]))) | ||
| 267 | elif opname == "OpTypeFloat": | ||
| 268 | inst_words.extend(_encode_inst(OP_TYPE_FLOAT, rid, int(parts[1]))) | ||
| 269 | elif opname == "OpTypeImage": | ||
| 270 | inst_words.extend(_encode_inst( | ||
| 271 | OP_TYPE_IMAGE, | ||
| 272 | rid, | ||
| 273 | resolve(parts[1]), | ||
| 274 | DIM_BY_NAME[parts[2]], | ||
| 275 | int(parts[3]), | ||
| 276 | int(parts[4]), | ||
| 277 | int(parts[5]), | ||
| 278 | int(parts[6]), | ||
| 279 | FMT_BY_NAME[parts[7]], | ||
| 280 | )) | ||
| 281 | elif opname == "OpTypeSampler": | ||
| 282 | inst_words.extend(_encode_inst(OP_TYPE_SAMPLER, rid)) | ||
| 283 | elif opname == "OpTypeArray": | ||
| 284 | inst_words.extend(_encode_inst(OP_TYPE_ARRAY, rid, resolve(parts[1]), resolve(parts[2]))) | ||
| 285 | elif opname == "OpTypeRuntimeArray": | ||
| 286 | inst_words.extend(_encode_inst(OP_TYPE_RUNTIME_ARRAY, rid, resolve(parts[1]))) | ||
| 287 | elif opname == "OpTypeStruct": | ||
| 288 | inst_words.extend(_encode_inst(OP_TYPE_STRUCT, rid, *[resolve(p) for p in parts[1:]])) | ||
| 289 | elif opname == "OpTypePointer": | ||
| 290 | inst_words.extend(_encode_inst(OP_TYPE_POINTER, rid, STORAGE_CLASS_BY_NAME[parts[1]], resolve(parts[2]))) | ||
| 291 | elif opname == "OpConstant": | ||
| 292 | inst_words.extend(_encode_inst(OP_CONSTANT, resolve(parts[1]), rid, int(parts[2]))) | ||
| 293 | elif opname == "OpVariable": | ||
| 294 | inst_words.extend(_encode_inst(OP_VARIABLE, resolve(parts[1]), rid, STORAGE_CLASS_BY_NAME[parts[2]])) | ||
| 295 | else: | ||
| 296 | raise ValueError(f"unsupported op: {line}") | ||
| 297 | |||
| 298 | ver = SPIRV_VERSION_1_5 if target_env == "spv1.5" else SPIRV_VERSION_1_0 | ||
| 299 | return _pack_spv(inst_words, version=ver, bound=next_id) | ||
| 300 | |||
| 301 | |||
| 302 | def _build_mixed_bindless_spv_words() -> list[int]: | ||
| 303 | """Build synthetic SPIR-V instruction words with set-0, set-1, and PushConstant resources.""" | ||
| 304 | # IDs: | ||
| 305 | # 1=uint, 2=float, 3=img2d, 4=smp, 5=rt_img, 6=rt_smp, 7=ptr_img, 8=ptr_smp | ||
| 306 | # 9=rt_map, 10=struct_map, 11=ptr_map, 12=ptr_pc_u32 | ||
| 307 | # 13=images (set 0, b0), 14=samplers (set 0, b1), 15=desc_map (set 0, b2) | ||
| 308 | # 16=push_consts, 17=set1_var (set 1, b0) | ||
| 309 | words: list[int] = [] | ||
| 310 | words.extend(_encode_inst(OP_CAPABILITY, CAP_SHADER)) | ||
| 311 | words.extend(_encode_inst(OP_CAPABILITY, CAP_RUNTIME_DESCRIPTOR_ARRAY)) | ||
| 312 | words.extend(_encode_inst(OP_MEMORY_MODEL, ADDR_LOGICAL, MEM_GLSL450)) | ||
| 313 | words.extend(_encode_inst(OP_DECORATE, 13, DEC_DESCRIPTOR_SET, 0)) | ||
| 314 | words.extend(_encode_inst(OP_DECORATE, 13, DEC_BINDING, 0)) | ||
| 315 | words.extend(_encode_inst(OP_DECORATE, 14, DEC_DESCRIPTOR_SET, 0)) | ||
| 316 | words.extend(_encode_inst(OP_DECORATE, 14, DEC_BINDING, 1)) | ||
| 317 | words.extend(_encode_inst(OP_DECORATE, 15, DEC_DESCRIPTOR_SET, 0)) | ||
| 318 | words.extend(_encode_inst(OP_DECORATE, 15, DEC_BINDING, 2)) | ||
| 319 | words.extend(_encode_inst(OP_DECORATE, 10, DEC_BLOCK)) | ||
| 320 | words.extend(_encode_inst(OP_DECORATE, 17, DEC_DESCRIPTOR_SET, 1)) | ||
| 321 | words.extend(_encode_inst(OP_DECORATE, 17, DEC_BINDING, 0)) | ||
| 322 | words.extend(_encode_inst(OP_TYPE_INT, 1, 32, 0)) | ||
| 323 | words.extend(_encode_inst(OP_TYPE_FLOAT, 2, 32)) | ||
| 324 | words.extend(_encode_inst(OP_TYPE_IMAGE, 3, 2, 1, 0, 0, 0, 1, 0)) | ||
| 325 | words.extend(_encode_inst(OP_TYPE_SAMPLER, 4)) | ||
| 326 | words.extend(_encode_inst(OP_TYPE_RUNTIME_ARRAY, 5, 3)) | ||
| 327 | words.extend(_encode_inst(OP_TYPE_RUNTIME_ARRAY, 6, 4)) | ||
| 328 | words.extend(_encode_inst(OP_TYPE_POINTER, 7, SC_UNIFORM_CONSTANT, 5)) | ||
| 329 | words.extend(_encode_inst(OP_TYPE_POINTER, 8, SC_UNIFORM_CONSTANT, 6)) | ||
| 330 | words.extend(_encode_inst(OP_TYPE_RUNTIME_ARRAY, 9, 1)) | ||
| 331 | words.extend(_encode_inst(OP_TYPE_STRUCT, 10, 9)) | ||
| 332 | words.extend(_encode_inst(OP_TYPE_POINTER, 11, SC_STORAGE_BUFFER, 10)) | ||
| 333 | words.extend(_encode_inst(OP_TYPE_POINTER, 12, SC_PUSH_CONSTANT, 1)) | ||
| 334 | words.extend(_encode_inst(OP_VARIABLE, 7, 13, SC_UNIFORM_CONSTANT)) | ||
| 335 | words.extend(_encode_inst(OP_VARIABLE, 8, 14, SC_UNIFORM_CONSTANT)) | ||
| 336 | words.extend(_encode_inst(OP_VARIABLE, 11, 15, SC_STORAGE_BUFFER)) | ||
| 337 | words.extend(_encode_inst(OP_VARIABLE, 12, 16, SC_PUSH_CONSTANT)) | ||
| 338 | words.extend(_encode_inst(OP_VARIABLE, 7, 17, SC_UNIFORM_CONSTANT)) | ||
| 339 | return words | ||
| 340 | |||
| 341 | |||
| 342 | def _make_fake_spirv_tools(dis_name="spirv-dis", asm_name="spirv-as"): | ||
| 343 | """Return a subprocess.run replacement backed by the synthetic SPIR-V binary codec.""" | ||
| 344 | calls: list[list[str]] = [] | ||
| 345 | |||
| 346 | def fake_run(cmd, check=False, capture_output=False, text=False, input=None): | ||
| 347 | calls.append(list(cmd)) | ||
| 348 | exe = cmd[0] | ||
| 349 | if exe == dis_name: | ||
| 350 | in_path = cmd[1] | ||
| 351 | try: | ||
| 352 | with open(in_path, "rb") as f: | ||
| 353 | data = f.read() | ||
| 354 | disasm = _synthetic_spv_to_disasm(data) | ||
| 355 | except (OSError, ValueError) as exc: | ||
| 356 | if check: | ||
| 357 | raise subprocess.CalledProcessError(1, cmd, output="", stderr=str(exc)) from exc | ||
| 358 | return subprocess.CompletedProcess(cmd, 1, "", str(exc)) | ||
| 359 | return subprocess.CompletedProcess(cmd, 0, disasm, "") | ||
| 360 | if exe == asm_name: | ||
| 361 | # Expect: [asm, "--target-env", target, "-", "-o", out_path] | ||
| 362 | target_env = cmd[cmd.index("--target-env") + 1] | ||
| 363 | out_path = cmd[cmd.index("-o") + 1] | ||
| 364 | try: | ||
| 365 | out_bytes = _synthetic_disasm_to_spv(input, target_env) | ||
| 366 | with open(out_path, "wb") as f: | ||
| 367 | f.write(out_bytes) | ||
| 368 | except (OSError, ValueError) as exc: | ||
| 369 | if check: | ||
| 370 | raise subprocess.CalledProcessError(1, cmd, output="", stderr=str(exc)) from exc | ||
| 371 | return subprocess.CompletedProcess(cmd, 1, "", str(exc)) | ||
| 372 | return subprocess.CompletedProcess(cmd, 0, "", "") | ||
| 373 | raise AssertionError(f"unexpected subprocess command: {cmd!r}") | ||
| 374 | |||
| 375 | return fake_run, calls | ||
| 376 | |||
| 377 | |||
| 378 | class TestCapacities(unittest.TestCase): | ||
| 379 | def test_default_bindless_header_all_26_entries_and_cross_check(self): | ||
| 380 | counts = m.capacities() | ||
| 381 | expected = [4096, 1024, 1, 1024, 1024] + [256] * 21 | ||
| 382 | self.assertEqual(counts, expected) | ||
| 383 | self.assertEqual(len(counts), 26) | ||
| 384 | self.assertEqual(sum(counts), 12545) | ||
| 385 | |||
| 386 | with open(m.BINDLESS_H, encoding="utf-8") as f: | ||
| 387 | hdr = f.read() | ||
| 388 | self.assertIn("inline constexpr std::uint32_t binding_count = 26;", hdr) | ||
| 389 | self.assertIn("inline constexpr std::array<Binding, 26> bindings =", hdr) | ||
| 390 | |||
| 391 | def test_custom_header_parsing_variants(self): | ||
| 392 | cases = [ | ||
| 393 | ("empty_table", "std::array<Binding, 0> bindings = {{}};\n", []), | ||
| 394 | ( | ||
| 395 | "single_line", | ||
| 396 | "std::array<Binding, 1> bindings = {{{VK_DESCRIPTOR_TYPE_SAMPLER, 7}}};\n", | ||
| 397 | [7], | ||
| 398 | ), | ||
| 399 | ( | ||
| 400 | "multiline_mixed_types_and_comments", | ||
| 401 | """ | ||
| 402 | // unrelated header prefix | ||
| 403 | inline constexpr std::array<Binding, 4> bindings = {{ | ||
| 404 | {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 128}, | ||
| 405 | {VK_DESCRIPTOR_TYPE_SAMPLER, 32}, | ||
| 406 | {VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1}, | ||
| 407 | {VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 64}, | ||
| 408 | }}; | ||
| 409 | """, | ||
| 410 | [128, 32, 1, 64], | ||
| 411 | ), | ||
| 412 | ] | ||
| 413 | with tempfile.TemporaryDirectory() as tmp: | ||
| 414 | for name, body, expected in cases: | ||
| 415 | with self.subTest(case=name): | ||
| 416 | p = os.path.join(tmp, f"{name}.h") | ||
| 417 | with open(p, "w", encoding="utf-8") as f: | ||
| 418 | f.write(body) | ||
| 419 | self.assertEqual(m.capacities(p), expected) | ||
| 420 | |||
| 421 | def test_missing_file_raises_file_not_found(self): | ||
| 422 | with tempfile.TemporaryDirectory() as tmp: | ||
| 423 | missing = os.path.join(tmp, "missing_bindless.h") | ||
| 424 | with self.assertRaises(FileNotFoundError): | ||
| 425 | m.capacities(missing) | ||
| 426 | |||
| 427 | def test_missing_or_mismatched_bindings_table_raises_system_exit(self): | ||
| 428 | bad_headers = [ | ||
| 429 | ("empty_file", "", "no `bindings` table"), | ||
| 430 | ("wrong_type_name", "std::array<int, 1> bindings = {{ {VK_DESCRIPTOR_TYPE_SAMPLER, 4} }};", "no `bindings` table"), | ||
| 431 | ( | ||
| 432 | "too_few_entries", | ||
| 433 | "std::array<Binding, 3> bindings = {{ {VK_DESCRIPTOR_TYPE_SAMPLER, 1}, {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 2} }};", | ||
| 434 | "`bindings` declares 3 entries, found 2", | ||
| 435 | ), | ||
| 436 | ( | ||
| 437 | "too_many_entries", | ||
| 438 | "std::array<Binding, 1> bindings = {{ {VK_DESCRIPTOR_TYPE_SAMPLER, 1}, {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 2} }};", | ||
| 439 | "`bindings` declares 1 entries, found 2", | ||
| 440 | ), | ||
| 441 | ( | ||
| 442 | "unmatched_entry_syntax", | ||
| 443 | "std::array<Binding, 1> bindings = {{ {NOT_A_VK_DESCRIPTOR, 1} }};", | ||
| 444 | "`bindings` declares 1 entries, found 0", | ||
| 445 | ), | ||
| 446 | ] | ||
| 447 | with tempfile.TemporaryDirectory() as tmp: | ||
| 448 | for name, body, msg_part in bad_headers: | ||
| 449 | with self.subTest(case=name): | ||
| 450 | p = os.path.join(tmp, f"{name}.h") | ||
| 451 | with open(p, "w", encoding="utf-8") as f: | ||
| 452 | f.write(body) | ||
| 453 | with self.assertRaises(SystemExit) as ctx: | ||
| 454 | m.capacities(p) | ||
| 455 | self.assertIn(p, str(ctx.exception)) | ||
| 456 | self.assertIn(msg_part, str(ctx.exception)) | ||
| 457 | |||
| 458 | |||
| 459 | class TestMetalIds(unittest.TestCase): | ||
| 460 | def test_empty_single_and_zero_capacities(self): | ||
| 461 | self.assertEqual(m.metal_ids([]), []) | ||
| 462 | self.assertEqual(m.metal_ids([42]), [0]) | ||
| 463 | self.assertEqual(m.metal_ids([10, 0, 5, 0, 1]), [0, 10, 10, 15, 15]) | ||
| 464 | |||
| 465 | def test_vulkan_bindless_ids_contiguous_and_non_overlapping(self): | ||
| 466 | counts = m.capacities() | ||
| 467 | ids = m.metal_ids(counts) | ||
| 468 | self.assertEqual(len(ids), 26) | ||
| 469 | self.assertEqual(ids[0], 0) | ||
| 470 | self.assertEqual(ids[:6], [0, 4096, 5120, 5121, 6145, 7169]) | ||
| 471 | self.assertEqual(ids[8], 7937) | ||
| 472 | self.assertEqual(ids[20], 11009) | ||
| 473 | self.assertEqual(ids[25], 12289) | ||
| 474 | for b in range(len(counts) - 1): | ||
| 475 | self.assertEqual(ids[b + 1], ids[b] + counts[b]) | ||
| 476 | self.assertEqual(ids[-1] + counts[-1], sum(counts)) | ||
| 477 | |||
| 478 | seen_total = 0 | ||
| 479 | for b in range(len(counts)): | ||
| 480 | if b > 0: | ||
| 481 | self.assertGreater(ids[b], ids[b - 1] + counts[b - 1] - 1) | ||
| 482 | seen_total += counts[b] | ||
| 483 | self.assertEqual(seen_total, 12545) | ||
| 484 | |||
| 485 | |||
| 486 | class TestRewrite(unittest.TestCase): | ||
| 487 | def test_all_26_vulkan_bindless_bindings(self): | ||
| 488 | counts = m.capacities() | ||
| 489 | ids = m.metal_ids(counts) | ||
| 490 | lines = [ | ||
| 491 | " OpCapability Shader", | ||
| 492 | " OpCapability RuntimeDescriptorArray", | ||
| 493 | " OpMemoryModel Logical GLSL450", | ||
| 494 | ] | ||
| 495 | for b in range(26): | ||
| 496 | lines.append(f" OpDecorate %v{b} DescriptorSet 0") | ||
| 497 | lines.append(f" OpDecorate %v{b} Binding {b}") | ||
| 498 | lines.extend([ | ||
| 499 | " %uint = OpTypeInt 32 0", | ||
| 500 | " %float = OpTypeFloat 32", | ||
| 501 | " %img2d = OpTypeImage %float 2D 0 0 0 1 Unknown", | ||
| 502 | " %smp = OpTypeSampler", | ||
| 503 | " %rt_map = OpTypeRuntimeArray %uint", | ||
| 504 | " %map = OpTypeStruct %rt_map", | ||
| 505 | " %ptr_map = OpTypePointer StorageBuffer %map", | ||
| 506 | ]) | ||
| 507 | for b in range(26): | ||
| 508 | if b == 2: | ||
| 509 | continue | ||
| 510 | elem = "%smp" if b == 1 else "%img2d" | ||
| 511 | lines.append(f" %rt_b{b} = OpTypeRuntimeArray {elem}") | ||
| 512 | lines.append(f" %ptr_b{b} = OpTypePointer UniformConstant %rt_b{b}") | ||
| 513 | for b in range(26): | ||
| 514 | if b == 2: | ||
| 515 | lines.append(" %v2 = OpVariable %ptr_map StorageBuffer") | ||
| 516 | else: | ||
| 517 | lines.append(f" %v{b} = OpVariable %ptr_b{b} UniformConstant") | ||
| 518 | |||
| 519 | out = m.rewrite("\n".join(lines) + "\n", counts) | ||
| 520 | out_lines = out.splitlines() | ||
| 521 | |||
| 522 | for b in range(26): | ||
| 523 | self.assertIn(f" OpDecorate %v{b} Binding {ids[b]}", out_lines) | ||
| 524 | if b == 2: | ||
| 525 | self.assertIn(" %v2 = OpVariable %ptr_map StorageBuffer", out_lines) | ||
| 526 | self.assertNotIn("%msl_cap_b2 ", out) | ||
| 527 | self.assertNotIn("%msl_arr_b2 ", out) | ||
| 528 | self.assertNotIn("%msl_ptr_b2 ", out) | ||
| 529 | else: | ||
| 530 | elem = "%smp" if b == 1 else "%img2d" | ||
| 531 | cap_line = f"%msl_cap_b{b} = OpConstant %uint {counts[b]}" | ||
| 532 | arr_line = f"%msl_arr_b{b} = OpTypeArray {elem} %msl_cap_b{b}" | ||
| 533 | ptr_line = f"%msl_ptr_b{b} = OpTypePointer UniformConstant %msl_arr_b{b}" | ||
| 534 | orig_ptr_line = f" %ptr_b{b} = OpTypePointer UniformConstant %rt_b{b}" | ||
| 535 | idx = out_lines.index(orig_ptr_line) | ||
| 536 | self.assertEqual(out_lines[idx + 1 : idx + 4], [cap_line, arr_line, ptr_line]) | ||
| 537 | self.assertIn(f" %v{b} = OpVariable %msl_ptr_b{b} UniformConstant", out_lines) | ||
| 538 | |||
| 539 | def test_push_constants_and_other_descriptor_sets_untouched(self): | ||
| 540 | module = """\ | ||
| 541 | OpDecorate %set0_img DescriptorSet 0 | ||
| 542 | OpDecorate %set0_img Binding 0 | ||
| 543 | OpDecorate %set0_smp DescriptorSet 0 | ||
| 544 | OpDecorate %set0_smp Binding 1 | ||
| 545 | OpDecorate %set1_in DescriptorSet 1 | ||
| 546 | OpDecorate %set1_in Binding 0 | ||
| 547 | OpDecorate %set1_high DescriptorSet 1 | ||
| 548 | OpDecorate %set1_high Binding 99 | ||
| 549 | OpDecorate %set2_uc DescriptorSet 2 | ||
| 550 | OpDecorate %set2_uc Binding 0 | ||
| 551 | %uint = OpTypeInt 32 0 | ||
| 552 | %float = OpTypeFloat 32 | ||
| 553 | %img2d = OpTypeImage %float 2D 0 0 0 1 Unknown | ||
| 554 | %smp = OpTypeSampler | ||
| 555 | %rt_img = OpTypeRuntimeArray %img2d | ||
| 556 | %rt_smp = OpTypeRuntimeArray %smp | ||
| 557 | %ptr_img = OpTypePointer UniformConstant %rt_img | ||
| 558 | %ptr_smp = OpTypePointer UniformConstant %rt_smp | ||
| 559 | %ptr_pc = OpTypePointer PushConstant %uint | ||
| 560 | %ptr_s1hi = OpTypePointer UniformConstant %rt_img | ||
| 561 | %ptr_s2uc = OpTypePointer UniformConstant %rt_img | ||
| 562 | %set0_img = OpVariable %ptr_img UniformConstant | ||
| 563 | %set0_smp = OpVariable %ptr_smp UniformConstant | ||
| 564 | %user_data = OpVariable %ptr_pc PushConstant | ||
| 565 | %set1_in = OpVariable %ptr_img StorageBuffer | ||
| 566 | %set1_high = OpVariable %ptr_s1hi UniformConstant | ||
| 567 | %set2_uc = OpVariable %ptr_s2uc UniformConstant | ||
| 568 | """ | ||
| 569 | out = m.rewrite(module, [8, 4]) | ||
| 570 | self.assertIn("OpDecorate %set0_img Binding 0", out) | ||
| 571 | self.assertIn("OpDecorate %set0_smp Binding 8", out) | ||
| 572 | # Set 1 (including binding 99 >= len(counts)), Set 2, and PushConstant stay untouched. | ||
| 573 | self.assertIn("OpDecorate %set1_in DescriptorSet 1", out) | ||
| 574 | self.assertIn("OpDecorate %set1_in Binding 0", out) | ||
| 575 | self.assertIn("OpDecorate %set1_high DescriptorSet 1", out) | ||
| 576 | self.assertIn("OpDecorate %set1_high Binding 99", out) | ||
| 577 | self.assertIn("OpDecorate %set2_uc DescriptorSet 2", out) | ||
| 578 | self.assertIn("OpDecorate %set2_uc Binding 0", out) | ||
| 579 | self.assertIn("%user_data = OpVariable %ptr_pc PushConstant", out) | ||
| 580 | self.assertIn("%set1_in = OpVariable %ptr_img StorageBuffer", out) | ||
| 581 | self.assertIn("%set1_high = OpVariable %ptr_s1hi UniformConstant", out) | ||
| 582 | self.assertIn("%set2_uc = OpVariable %ptr_s2uc UniformConstant", out) | ||
| 583 | |||
| 584 | def test_non_runtime_array_set0_resources_rebind_without_retyping_or_uint32(self): | ||
| 585 | # No OpTypeInt 32 0 is present, yet none of these set-0 bindings use OpTypeRuntimeArray | ||
| 586 | # under OpTypePointer UniformConstant, so rewriting succeeds without raising. | ||
| 587 | module = """\ | ||
| 588 | OpDecorate %single DescriptorSet 0 | ||
| 589 | OpDecorate %single Binding 0 | ||
| 590 | OpDecorate %fixed DescriptorSet 0 | ||
| 591 | OpDecorate %fixed Binding 1 | ||
| 592 | OpDecorate %ubo DescriptorSet 0 | ||
| 593 | OpDecorate %ubo Binding 2 | ||
| 594 | OpDecorate %mismatch DescriptorSet 0 | ||
| 595 | OpDecorate %mismatch Binding 3 | ||
| 596 | OpDecorate %dangling DescriptorSet 0 | ||
| 597 | OpDecorate %dangling Binding 4 | ||
| 598 | %float = OpTypeFloat 32 | ||
| 599 | %img2d = OpTypeImage %float 2D 0 0 0 1 Unknown | ||
| 600 | %sint = OpTypeInt 32 1 | ||
| 601 | %c16 = OpConstant %sint 16 | ||
| 602 | %fixed_arr = OpTypeArray %img2d %c16 | ||
| 603 | %ubo_blk = OpTypeStruct %float | ||
| 604 | %ptr_single = OpTypePointer UniformConstant %img2d | ||
| 605 | %ptr_fixed = OpTypePointer UniformConstant %fixed_arr | ||
| 606 | %ptr_ubo = OpTypePointer Uniform %ubo_blk | ||
| 607 | %ptr_mis_sb = OpTypePointer StorageBuffer %fixed_arr | ||
| 608 | %ptr_dangling = OpTypePointer UniformConstant %missing_pointee | ||
| 609 | %single = OpVariable %ptr_single UniformConstant | ||
| 610 | %fixed = OpVariable %ptr_fixed UniformConstant | ||
| 611 | %ubo = OpVariable %ptr_ubo Uniform | ||
| 612 | %mismatch = OpVariable %ptr_mis_sb UniformConstant | ||
| 613 | %dangling = OpVariable %ptr_dangling UniformConstant | ||
| 614 | """ | ||
| 615 | counts = [10, 20, 1, 5, 2] | ||
| 616 | out = m.rewrite(module, counts) | ||
| 617 | self.assertIn("OpDecorate %single Binding 0", out) | ||
| 618 | self.assertIn("OpDecorate %fixed Binding 10", out) | ||
| 619 | self.assertIn("OpDecorate %ubo Binding 30", out) | ||
| 620 | self.assertIn("OpDecorate %mismatch Binding 31", out) | ||
| 621 | self.assertIn("OpDecorate %dangling Binding 36", out) | ||
| 622 | self.assertIn("%single = OpVariable %ptr_single UniformConstant", out) | ||
| 623 | self.assertIn("%fixed = OpVariable %ptr_fixed UniformConstant", out) | ||
| 624 | self.assertIn("%ubo = OpVariable %ptr_ubo Uniform", out) | ||
| 625 | self.assertIn("%mismatch = OpVariable %ptr_mis_sb UniformConstant", out) | ||
| 626 | self.assertIn("%dangling = OpVariable %ptr_dangling UniformConstant", out) | ||
| 627 | self.assertNotIn("%msl_", out) | ||
| 628 | |||
| 629 | def test_partial_decorations_and_missing_var_def(self): | ||
| 630 | module = """\ | ||
| 631 | OpDecorate %only_set DescriptorSet 0 | ||
| 632 | OpDecorate %only_bind Binding 1 | ||
| 633 | OpDecorate %orphan DescriptorSet 0 | ||
| 634 | OpDecorate %orphan Binding 1 | ||
| 635 | %u = OpTypeInt 32 0 | ||
| 636 | """ | ||
| 637 | out = m.rewrite(module, [5, 7]) | ||
| 638 | self.assertIn("OpDecorate %only_set DescriptorSet 0", out) | ||
| 639 | self.assertIn("OpDecorate %only_bind Binding 1", out) | ||
| 640 | self.assertIn("OpDecorate %orphan Binding 5", out) | ||
| 641 | self.assertNotIn("%msl_", out) | ||
| 642 | |||
| 643 | def test_raw_numeric_ids_custom_uint_and_crlf_and_shared_pointer(self): | ||
| 644 | module = ( | ||
| 645 | "; Header comment\r\n" | ||
| 646 | "OpName %10 \"images\"\r\n" | ||
| 647 | "OpDecorate %10 DescriptorSet 0\r\n" | ||
| 648 | "OpDecorate %10 Binding 1\r\n" | ||
| 649 | "OpDecorate %11 DescriptorSet 0\r\n" | ||
| 650 | "OpDecorate %11 Binding 0\r\n" | ||
| 651 | "%1 = OpTypeVoid\r\n" | ||
| 652 | "%2 = OpTypeInt 32 1\r\n" | ||
| 653 | "%3 = OpTypeInt 64 0\r\n" | ||
| 654 | "%4 = OpTypeInt 32 0\r\n" | ||
| 655 | "%5 = OpTypeFloat 32\r\n" | ||
| 656 | "%6 = OpTypeImage %5 2D 0 0 0 1 Unknown\r\n" | ||
| 657 | "%7 = OpTypeRuntimeArray %6\r\n" | ||
| 658 | "%8 = OpTypePointer UniformConstant %7\r\n" | ||
| 659 | "%9 = OpTypePointer Function %5\r\n" | ||
| 660 | "%10 = OpVariable %8 UniformConstant\r\n" | ||
| 661 | "%11 = OpVariable %8 UniformConstant\r\n" | ||
| 662 | ) | ||
| 663 | out = m.rewrite(module, [16, 8]) | ||
| 664 | self.assertNotIn("\r\n", out) | ||
| 665 | self.assertTrue(out.endswith("\n")) | ||
| 666 | self.assertIn("OpDecorate %11 Binding 0", out) | ||
| 667 | self.assertIn("OpDecorate %10 Binding 16", out) | ||
| 668 | # First OpTypeInt 32 0 is %4 (not %2 signed or %3 64-bit). | ||
| 669 | self.assertIn("%msl_cap_b0 = OpConstant %4 16", out) | ||
| 670 | self.assertIn("%msl_cap_b1 = OpConstant %4 8", out) | ||
| 671 | self.assertIn("%11 = OpVariable %msl_ptr_b0 UniformConstant", out) | ||
| 672 | self.assertIn("%10 = OpVariable %msl_ptr_b1 UniformConstant", out) | ||
| 673 | # Sorted binding order (b0 then b1) inserted immediately after %8, not after %9. | ||
| 674 | lines = out.splitlines() | ||
| 675 | idx8 = lines.index("%8 = OpTypePointer UniformConstant %7") | ||
| 676 | self.assertEqual(lines[idx8 + 1 : idx8 + 7], [ | ||
| 677 | "%msl_cap_b0 = OpConstant %4 16", | ||
| 678 | "%msl_arr_b0 = OpTypeArray %6 %msl_cap_b0", | ||
| 679 | "%msl_ptr_b0 = OpTypePointer UniformConstant %msl_arr_b0", | ||
| 680 | "%msl_cap_b1 = OpConstant %4 8", | ||
| 681 | "%msl_arr_b1 = OpTypeArray %6 %msl_cap_b1", | ||
| 682 | "%msl_ptr_b1 = OpTypePointer UniformConstant %msl_arr_b1", | ||
| 683 | ]) | ||
| 684 | idx9 = lines.index("%9 = OpTypePointer Function %5") | ||
| 685 | self.assertEqual(lines[idx9 + 1], "%10 = OpVariable %msl_ptr_b1 UniformConstant") | ||
| 686 | |||
| 687 | def test_empty_and_no_set0_modules(self): | ||
| 688 | self.assertEqual(m.rewrite("", [4]), "\n") | ||
| 689 | plain = "OpCapability Shader\nOpMemoryModel Logical GLSL450\n" | ||
| 690 | self.assertEqual(m.rewrite(plain, [4]), plain) | ||
| 691 | |||
| 692 | def test_out_of_bounds_set0_binding_raises_system_exit(self): | ||
| 693 | for b, counts in ((2, [10, 20]), (26, m.capacities()), (100, m.capacities())): | ||
| 694 | with self.subTest(binding=b, count_len=len(counts)): | ||
| 695 | text = f"OpDecorate %bad DescriptorSet 0\nOpDecorate %bad Binding {b}\n" | ||
| 696 | with self.assertRaises(SystemExit) as ctx: | ||
| 697 | m.rewrite(text, counts) | ||
| 698 | self.assertIn("%bad", str(ctx.exception)) | ||
| 699 | self.assertIn(f"binding {b}", str(ctx.exception)) | ||
| 700 | |||
| 701 | def test_missing_uint32_type_raises_when_runtime_array_rewritten(self): | ||
| 702 | base = """\ | ||
| 703 | OpDecorate %images DescriptorSet 0 | ||
| 704 | OpDecorate %images Binding 0 | ||
| 705 | {int_decl} | ||
| 706 | %float = OpTypeFloat 32 | ||
| 707 | %img2d = OpTypeImage %float 2D 0 0 0 1 Unknown | ||
| 708 | %rt_img = OpTypeRuntimeArray %img2d | ||
| 709 | %ptr_img = OpTypePointer UniformConstant %rt_img | ||
| 710 | %images = OpVariable %ptr_img UniformConstant | ||
| 711 | """ | ||
| 712 | for label, int_decl in ( | ||
| 713 | ("no_int", ""), | ||
| 714 | ("signed_32", "%s32 = OpTypeInt 32 1"), | ||
| 715 | ("unsigned_64", "%u64 = OpTypeInt 64 0"), | ||
| 716 | ): | ||
| 717 | with self.subTest(case=label): | ||
| 718 | with self.assertRaises(SystemExit) as ctx: | ||
| 719 | m.rewrite(base.format(int_decl=int_decl), [4096]) | ||
| 720 | self.assertIn("no 32-bit uint type", str(ctx.exception)) | ||
| 721 | |||
| 722 | |||
| 723 | class TestMainAndCli(unittest.TestCase): | ||
| 724 | def _call_main(self, argv): | ||
| 725 | out, err = io.StringIO(), io.StringIO() | ||
| 726 | # tools/spirv_metal_set0.py:31 uses open(path).read() without a context manager, which emits | ||
| 727 | # ResourceWarning under unittest's default filter on redirected stderr; isolate tool stderr here. | ||
| 728 | with warnings.catch_warnings(): | ||
| 729 | warnings.simplefilter("ignore", ResourceWarning) | ||
| 730 | with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): | ||
| 731 | code = m.main(argv) | ||
| 732 | return code, out.getvalue(), err.getvalue() | ||
| 733 | |||
| 734 | def test_print_layout_outputs_26_formatted_ranges_without_subprocess(self): | ||
| 735 | with mock.patch.object(m.subprocess, "run") as run_mock: | ||
| 736 | code, out, err = self._call_main(["spirv_metal_set0.py", "--print-layout"]) | ||
| 737 | run_mock.assert_not_called() | ||
| 738 | self.assertEqual(code, 0) | ||
| 739 | self.assertEqual(err, "") | ||
| 740 | lines = out.splitlines() | ||
| 741 | self.assertEqual(len(lines), 26) | ||
| 742 | self.assertEqual(lines[0], "binding 0: 4096 descriptors at IDs 0..4095") | ||
| 743 | self.assertEqual(lines[1], "binding 1: 1024 descriptors at IDs 4096..5119") | ||
| 744 | self.assertEqual(lines[2], "binding 2: 1 descriptors at IDs 5120..5120") | ||
| 745 | self.assertEqual(lines[3], "binding 3: 1024 descriptors at IDs 5121..6144") | ||
| 746 | self.assertEqual(lines[4], "binding 4: 1024 descriptors at IDs 6145..7168") | ||
| 747 | self.assertEqual(lines[25], "binding 25: 256 descriptors at IDs 12289..12544") | ||
| 748 | |||
| 749 | def test_print_layout_uses_capacities_table(self): | ||
| 750 | with mock.patch.object(m, "capacities", return_value=[3, 1, 2]): | ||
| 751 | code, out, err = self._call_main(["spirv_metal_set0.py", "--print-layout"]) | ||
| 752 | self.assertEqual(code, 0) | ||
| 753 | self.assertEqual(err, "") | ||
| 754 | self.assertEqual(out.splitlines(), [ | ||
| 755 | "binding 0: 3 descriptors at IDs 0..2", | ||
| 756 | "binding 1: 1 descriptors at IDs 3..3", | ||
| 757 | "binding 2: 2 descriptors at IDs 4..5", | ||
| 758 | ]) | ||
| 759 | |||
| 760 | def test_invalid_argc_returns_2_and_prints_usage_to_stderr(self): | ||
| 761 | bad_argvs = [ | ||
| 762 | [], | ||
| 763 | ["spirv_metal_set0.py"], | ||
| 764 | ["spirv_metal_set0.py", "in.spv"], | ||
| 765 | ["spirv_metal_set0.py", "--unknown"], | ||
| 766 | ["spirv_metal_set0.py", "--print-layout", "in.spv", "out.spv"], | ||
| 767 | ["spirv_metal_set0.py", "in.spv", "out.spv", "extra"], | ||
| 768 | ] | ||
| 769 | for argv in bad_argvs: | ||
| 770 | with self.subTest(argv=argv), mock.patch.object(m.subprocess, "run") as run_mock: | ||
| 771 | code, out, err = self._call_main(argv) | ||
| 772 | run_mock.assert_not_called() | ||
| 773 | self.assertEqual(code, 2) | ||
| 774 | self.assertEqual(out, "") | ||
| 775 | self.assertIn("Usage: spirv_metal_set0.py in.spv out.spv", err) | ||
| 776 | self.assertIn("--print-layout", err) | ||
| 777 | |||
| 778 | def test_print_layout_with_extra_arg_falls_through_to_two_arg_mode(self): | ||
| 779 | with mock.patch.object( | ||
| 780 | m.subprocess, | ||
| 781 | "run", | ||
| 782 | side_effect=[ | ||
| 783 | subprocess.CompletedProcess([], 0, "OpCapability Shader\n", ""), | ||
| 784 | subprocess.CompletedProcess([], 0, "", ""), | ||
| 785 | ], | ||
| 786 | ) as run_mock: | ||
| 787 | code, out, err = self._call_main(["spirv_metal_set0.py", "--print-layout", "out.spv"]) | ||
| 788 | self.assertEqual((code, out, err), (0, "", "")) | ||
| 789 | self.assertEqual(run_mock.call_args_list[0].args[0], ["spirv-dis", "--print-layout"]) | ||
| 790 | self.assertEqual( | ||
| 791 | run_mock.call_args_list[1].args[0], | ||
| 792 | ["spirv-as", "--target-env", "vulkan1.2", "-", "-o", "out.spv"], | ||
| 793 | ) | ||
| 794 | |||
| 795 | def test_cli_subprocess_isolated_print_layout_and_bad_args(self): | ||
| 796 | r_layout = subprocess.run( | ||
| 797 | [sys.executable, "-I", TOOL_PATH, "--print-layout"], | ||
| 798 | capture_output=True, | ||
| 799 | text=True, | ||
| 800 | cwd=ROOT, | ||
| 801 | ) | ||
| 802 | self.assertEqual(r_layout.returncode, 0, r_layout.stderr) | ||
| 803 | self.assertEqual(r_layout.stderr, "") | ||
| 804 | self.assertEqual(len(r_layout.stdout.splitlines()), 26) | ||
| 805 | self.assertEqual(r_layout.stdout.splitlines()[0], "binding 0: 4096 descriptors at IDs 0..4095") | ||
| 806 | |||
| 807 | for args in ([], ["only_one.spv"], ["a.spv", "b.spv", "c.spv"]): | ||
| 808 | with self.subTest(args=args): | ||
| 809 | r = subprocess.run( | ||
| 810 | [sys.executable, "-I", TOOL_PATH, *args], | ||
| 811 | capture_output=True, | ||
| 812 | text=True, | ||
| 813 | cwd=ROOT, | ||
| 814 | ) | ||
| 815 | self.assertEqual(r.returncode, 2) | ||
| 816 | self.assertEqual(r.stdout, "") | ||
| 817 | self.assertIn("Usage: spirv_metal_set0.py in.spv out.spv", r.stderr) | ||
| 818 | self.assertNotIn("Traceback", r.stderr) | ||
| 819 | |||
| 820 | def test_synthetic_spv_out_of_place_and_in_place_binary_round_trip(self): | ||
| 821 | in_bytes = _pack_spv(_build_mixed_bindless_spv_words(), version=SPIRV_VERSION_1_5) | ||
| 822 | fake_run, calls = _make_fake_spirv_tools() | ||
| 823 | |||
| 824 | with tempfile.TemporaryDirectory() as tmp: | ||
| 825 | unicode_dir = os.path.join(tmp, "dir-\u00e9-\u2603") | ||
| 826 | os.makedirs(unicode_dir) | ||
| 827 | in_path = os.path.join(unicode_dir, "in.spv") | ||
| 828 | out_path = os.path.join(unicode_dir, "out.spv") | ||
| 829 | with open(in_path, "wb") as f: | ||
| 830 | f.write(in_bytes) | ||
| 831 | |||
| 832 | with mock.patch.dict(os.environ, {}, clear=False), \ | ||
| 833 | mock.patch.object(m.subprocess, "run", side_effect=fake_run): | ||
| 834 | os.environ.pop("SPIRV_DIS", None) | ||
| 835 | os.environ.pop("SPIRV_AS", None) | ||
| 836 | code, out, err = self._call_main(["spirv_metal_set0.py", in_path, out_path]) | ||
| 837 | |||
| 838 | self.assertEqual(code, 0) | ||
| 839 | self.assertEqual(out, "") | ||
| 840 | self.assertEqual(err, "") | ||
| 841 | self.assertEqual(calls, [ | ||
| 842 | ["spirv-dis", in_path], | ||
| 843 | ["spirv-as", "--target-env", "spv1.5", "-", "-o", out_path], | ||
| 844 | ]) | ||
| 845 | |||
| 846 | # Original input file is preserved untouched for out-of-place conversion. | ||
| 847 | with open(in_path, "rb") as f: | ||
| 848 | self.assertEqual(f.read(), in_bytes) | ||
| 849 | |||
| 850 | with open(out_path, "rb") as f: | ||
| 851 | out_bytes = f.read() | ||
| 852 | header, insts = _decode_spv(out_bytes) | ||
| 853 | self.assertEqual(header[0], SPIRV_MAGIC) | ||
| 854 | self.assertEqual(header[1], SPIRV_VERSION_1_5) | ||
| 855 | self.assertEqual(header[4], 0) | ||
| 856 | |||
| 857 | decs = [ops for op, ops in insts if op == OP_DECORATE] | ||
| 858 | bindings_by_id = {ops[0]: ops[2] for ops in decs if ops[1] == DEC_BINDING} | ||
| 859 | sets_by_id = {ops[0]: ops[2] for ops in decs if ops[1] == DEC_DESCRIPTOR_SET} | ||
| 860 | self.assertEqual(sets_by_id, {13: 0, 14: 0, 15: 0, 17: 1}) | ||
| 861 | # Set-0 bindings rewritten per vulkan_bindless.h; set-1 binding 0 stays 0. | ||
| 862 | self.assertEqual(bindings_by_id, {13: 0, 14: 4096, 15: 5120, 17: 0}) | ||
| 863 | |||
| 864 | consts = {ops[1]: ops[2] for op, ops in insts if op == OP_CONSTANT} | ||
| 865 | arrays = {ops[0]: (ops[1], consts[ops[2]]) for op, ops in insts if op == OP_TYPE_ARRAY} | ||
| 866 | ptrs = {ops[0]: (ops[1], ops[2]) for op, ops in insts if op == OP_TYPE_POINTER} | ||
| 867 | vars_by_id = {ops[1]: (ops[0], ops[2]) for op, ops in insts if op == OP_VARIABLE} | ||
| 868 | |||
| 869 | # %13 (images) and %14 (samplers) are retyped to sized arrays [4096] and [1024]; | ||
| 870 | # %15 (desc_map StorageBuffer), %16 (PushConstant), and %17 (set 1) keep original types. | ||
| 871 | self.assertEqual(arrays[ptrs[vars_by_id[13][0]][1]], (3, 4096)) | ||
| 872 | self.assertEqual(arrays[ptrs[vars_by_id[14][0]][1]], (4, 1024)) | ||
| 873 | self.assertEqual(vars_by_id[15], (11, SC_STORAGE_BUFFER)) | ||
| 874 | self.assertEqual(vars_by_id[16], (12, SC_PUSH_CONSTANT)) | ||
| 875 | self.assertEqual(vars_by_id[17], (7, SC_UNIFORM_CONSTANT)) | ||
| 876 | |||
| 877 | # In-place conversion: argv[1] == argv[2]. | ||
| 878 | inplace_path = os.path.join(unicode_dir, "inplace.spv") | ||
| 879 | with open(inplace_path, "wb") as f: | ||
| 880 | f.write(in_bytes) | ||
| 881 | calls.clear() | ||
| 882 | with mock.patch.object(m.subprocess, "run", side_effect=fake_run): | ||
| 883 | code, out, err = self._call_main(["spirv_metal_set0.py", inplace_path, inplace_path]) | ||
| 884 | self.assertEqual(code, 0) | ||
| 885 | self.assertEqual(out, "") | ||
| 886 | self.assertEqual(err, "") | ||
| 887 | self.assertEqual(calls, [ | ||
| 888 | ["spirv-dis", inplace_path], | ||
| 889 | ["spirv-as", "--target-env", "spv1.5", "-", "-o", inplace_path], | ||
| 890 | ]) | ||
| 891 | with open(inplace_path, "rb") as f: | ||
| 892 | self.assertEqual(f.read(), out_bytes) | ||
| 893 | |||
| 894 | def test_target_env_extraction_and_env_var_overrides(self): | ||
| 895 | cases = [ | ||
| 896 | ("; Version: 1.0\n", "spv1.0"), | ||
| 897 | ("; SPIR-V\n; Version: 1.5\n", "spv1.5"), | ||
| 898 | ("; Version: 1.6\n", "spv1.6"), | ||
| 899 | ("; SPIR-V without version comment\n", "vulkan1.2"), | ||
| 900 | ] | ||
| 901 | for header_text, expected_target in cases: | ||
| 902 | with self.subTest(expected_target=expected_target): | ||
| 903 | disasm = header_text + "OpCapability Shader\n" | ||
| 904 | seen_cmds = [] | ||
| 905 | |||
| 906 | def run_stub(cmd, check=False, capture_output=False, text=False, input=None): | ||
| 907 | seen_cmds.append((list(cmd), check, capture_output, text, input)) | ||
| 908 | if len(seen_cmds) == 1: | ||
| 909 | return subprocess.CompletedProcess(cmd, 0, disasm, "") | ||
| 910 | return subprocess.CompletedProcess(cmd, 0, "", "") | ||
| 911 | |||
| 912 | with mock.patch.dict(os.environ, {"SPIRV_DIS": "/opt/bin/dis", "SPIRV_AS": "/opt/bin/as"}), \ | ||
| 913 | mock.patch.object(m.subprocess, "run", side_effect=run_stub): | ||
| 914 | code, out, err = self._call_main(["spirv_metal_set0.py", "in.spv", "out.spv"]) | ||
| 915 | |||
| 916 | self.assertEqual((code, out, err), (0, "", "")) | ||
| 917 | self.assertEqual(seen_cmds[0][0], ["/opt/bin/dis", "in.spv"]) | ||
| 918 | self.assertTrue(seen_cmds[0][1]) | ||
| 919 | self.assertTrue(seen_cmds[0][2]) | ||
| 920 | self.assertTrue(seen_cmds[0][3]) | ||
| 921 | self.assertEqual(seen_cmds[1][0], ["/opt/bin/as", "--target-env", expected_target, "-", "-o", "out.spv"]) | ||
| 922 | self.assertTrue(seen_cmds[1][1]) | ||
| 923 | self.assertTrue(seen_cmds[1][3]) | ||
| 924 | self.assertEqual(seen_cmds[1][4], disasm) | ||
| 925 | |||
| 926 | def test_invalid_spirv_binary_words_and_missing_or_directory_paths(self): | ||
| 927 | fake_run, calls = _make_fake_spirv_tools() | ||
| 928 | valid_words = _build_mixed_bindless_spv_words() | ||
| 929 | |||
| 930 | bad_inputs = [ | ||
| 931 | ("empty_file", b""), | ||
| 932 | ("truncated_header_8B", struct.pack("<2I", SPIRV_MAGIC, SPIRV_VERSION_1_5)), | ||
| 933 | ("unaligned_21B", _pack_spv([], bound=1) + b"\x00"), | ||
| 934 | ("big_endian_magic", struct.pack(">5I", SPIRV_MAGIC, SPIRV_VERSION_1_5, 0, 2, 0)), | ||
| 935 | ("wrong_magic", struct.pack("<5I", 0xDEADBEEF, SPIRV_VERSION_1_5, 0, 2, 0)), | ||
| 936 | ("non_zero_schema", _pack_spv([], bound=1, schema=1)), | ||
| 937 | ("zero_bound", _pack_spv([], bound=0)), | ||
| 938 | ("zero_word_count_inst", _pack_spv([OP_CAPABILITY], bound=2)), | ||
| 939 | ("truncated_inst_bounds", _pack_spv(valid_words[:-1], bound=18)), | ||
| 940 | ] | ||
| 941 | with tempfile.TemporaryDirectory() as tmp: | ||
| 942 | for label, blob in bad_inputs: | ||
| 943 | with self.subTest(case=label): | ||
| 944 | calls.clear() | ||
| 945 | in_path = os.path.join(tmp, f"{label}.spv") | ||
| 946 | out_path = os.path.join(tmp, f"{label}.out.spv") | ||
| 947 | with open(in_path, "wb") as f: | ||
| 948 | f.write(blob) | ||
| 949 | with mock.patch.object(m.subprocess, "run", side_effect=fake_run): | ||
| 950 | with self.assertRaises(subprocess.CalledProcessError): | ||
| 951 | m.main(["spirv_metal_set0.py", in_path, out_path]) | ||
| 952 | self.assertEqual(calls, [["spirv-dis", in_path]]) | ||
| 953 | self.assertFalse(os.path.exists(out_path)) | ||
| 954 | |||
| 955 | # Missing input file and directory passed as input file both fail at spirv-dis. | ||
| 956 | missing_in = os.path.join(tmp, "does_not_exist.spv") | ||
| 957 | dir_in = os.path.join(tmp, "a_directory") | ||
| 958 | os.makedirs(dir_in) | ||
| 959 | for label, bad_path in (("missing_file", missing_in), ("directory_input", dir_in)): | ||
| 960 | with self.subTest(case=label): | ||
| 961 | calls.clear() | ||
| 962 | out_path = os.path.join(tmp, f"{label}.out.spv") | ||
| 963 | with mock.patch.object(m.subprocess, "run", side_effect=fake_run): | ||
| 964 | with self.assertRaises(subprocess.CalledProcessError): | ||
| 965 | m.main(["spirv_metal_set0.py", bad_path, out_path]) | ||
| 966 | self.assertEqual(calls, [["spirv-dis", bad_path]]) | ||
| 967 | self.assertFalse(os.path.exists(out_path)) | ||
| 968 | |||
| 969 | def test_spirv_as_failure_missing_executable_and_rewrite_abort(self): | ||
| 970 | with tempfile.TemporaryDirectory() as tmp: | ||
| 971 | in_path = os.path.join(tmp, "in.spv") | ||
| 972 | out_path = os.path.join(tmp, "out.spv") | ||
| 973 | with open(in_path, "wb") as f: | ||
| 974 | f.write(_pack_spv(_build_mixed_bindless_spv_words())) | ||
| 975 | |||
| 976 | # 1. Missing spirv-dis binary raises FileNotFoundError before calling spirv-as. | ||
| 977 | with mock.patch.object(m.subprocess, "run", side_effect=FileNotFoundError("no spirv-dis")) as run_mock: | ||
| 978 | with self.assertRaises(FileNotFoundError): | ||
| 979 | m.main(["spirv_metal_set0.py", in_path, out_path]) | ||
| 980 | self.assertEqual(run_mock.call_count, 1) | ||
| 981 | self.assertFalse(os.path.exists(out_path)) | ||
| 982 | |||
| 983 | # 2. rewrite() SystemExit aborts before spirv-as is invoked. | ||
| 984 | bad_spv = _pack_spv([ | ||
| 985 | *_encode_inst(OP_DECORATE, 2, DEC_DESCRIPTOR_SET, 0), | ||
| 986 | *_encode_inst(OP_DECORATE, 2, DEC_BINDING, 99), | ||
| 987 | ], bound=3) | ||
| 988 | with open(in_path, "wb") as f: | ||
| 989 | f.write(bad_spv) | ||
| 990 | fake_run, calls = _make_fake_spirv_tools() | ||
| 991 | with mock.patch.object(m.subprocess, "run", side_effect=fake_run): | ||
| 992 | with self.assertRaises(SystemExit) as ctx: | ||
| 993 | m.main(["spirv_metal_set0.py", in_path, out_path]) | ||
| 994 | self.assertIn("binding 99", str(ctx.exception)) | ||
| 995 | self.assertEqual(calls, [["spirv-dis", in_path]]) | ||
| 996 | self.assertFalse(os.path.exists(out_path)) | ||
| 997 | |||
| 998 | # 3. spirv-as failure raises CalledProcessError. | ||
| 999 | dis_ok = subprocess.CompletedProcess(["spirv-dis", in_path], 0, "; Version: 1.5\nOpCapability Shader\n", "") | ||
| 1000 | asm_fail = subprocess.CalledProcessError(1, ["spirv-as"], stderr="bad asm") | ||
| 1001 | with mock.patch.object(m.subprocess, "run", side_effect=[dis_ok, asm_fail]) as run_mock: | ||
| 1002 | with self.assertRaises(subprocess.CalledProcessError): | ||
| 1003 | m.main(["spirv_metal_set0.py", in_path, out_path]) | ||
| 1004 | self.assertEqual(run_mock.call_count, 2) | ||
| 1005 | |||
| 1006 | def test_main_guard_handles_stdout_reconfigure_errors_and_exit_codes(self): | ||
| 1007 | class _Stream(io.StringIO): | ||
| 1008 | def __init__(self, exc): | ||
| 1009 | super().__init__() | ||
| 1010 | self._exc = exc | ||
| 1011 | |||
| 1012 | def reconfigure(self, **_kwargs): | ||
| 1013 | raise self._exc | ||
| 1014 | |||
| 1015 | for exc in (AttributeError("no reconfigure"), ValueError("bad"), OSError("io")): | ||
| 1016 | with self.subTest(exc=type(exc).__name__): | ||
| 1017 | out_stream = _Stream(exc) | ||
| 1018 | err_stream = io.StringIO() | ||
| 1019 | with warnings.catch_warnings(): | ||
| 1020 | warnings.simplefilter("ignore", ResourceWarning) | ||
| 1021 | with mock.patch.object(sys, "argv", ["spirv_metal_set0.py", "--print-layout"]), \ | ||
| 1022 | mock.patch.object(sys, "stdout", out_stream), \ | ||
| 1023 | mock.patch.object(sys, "stderr", err_stream): | ||
| 1024 | with self.assertRaises(SystemExit) as ctx: | ||
| 1025 | runpy.run_path(TOOL_PATH, run_name="__main__") | ||
| 1026 | self.assertEqual(ctx.exception.code, 0) | ||
| 1027 | self.assertEqual(err_stream.getvalue(), "") | ||
| 1028 | self.assertEqual(len(out_stream.getvalue().splitlines()), 26) | ||
| 1029 | |||
| 1030 | err_stream = io.StringIO() | ||
| 1031 | with warnings.catch_warnings(): | ||
| 1032 | warnings.simplefilter("ignore", ResourceWarning) | ||
| 1033 | with mock.patch.object(sys, "argv", ["spirv_metal_set0.py"]), \ | ||
| 1034 | mock.patch.object(sys, "stdout", io.StringIO()), \ | ||
| 1035 | mock.patch.object(sys, "stderr", err_stream): | ||
| 1036 | with self.assertRaises(SystemExit) as ctx: | ||
| 1037 | runpy.run_path(TOOL_PATH, run_name="__main__") | ||
| 1038 | self.assertEqual(ctx.exception.code, 2) | ||
| 1039 | self.assertIn("Usage: spirv_metal_set0.py in.spv out.spv", err_stream.getvalue()) | ||
| 1040 | |||
| 1041 | |||
| 1042 | if __name__ == "__main__": | ||
| 1043 | unittest.main() | ||
diff --git a/tests/test_text_tables.py b/tests/test_text_tables.py index 670b92df6..2714d2b90 100644 --- a/tests/test_text_tables.py +++ b/tests/test_text_tables.py | |||
| @@ -178,6 +178,62 @@ class TestCli(unittest.TestCase): | |||
| 178 | with open(outs["strings"], encoding="utf-8", newline="") as fh: | 178 | with open(outs["strings"], encoding="utf-8", newline="") as fh: |
| 179 | strings = list(csv.DictReader(fh)) | 179 | strings = list(csv.DictReader(fh)) |
| 180 | self.assertIn(("ZZ_MENU_TITLE", "das Menü"), {(s["label"], s["text"]) for s in strings}) | 180 | self.assertIn(("ZZ_MENU_TITLE", "das Menü"), {(s["label"], s["text"]) for s in strings}) |
| 181 | self.assertFalse([f for f in os.listdir(tmp) if f.startswith(".text_tables-")], | ||
| 182 | "staging files must not be left behind") | ||
| 183 | |||
| 184 | def test_failed_later_write_leaves_earlier_reports_intact(self): | ||
| 185 | with tempfile.TemporaryDirectory() as tmp: | ||
| 186 | src = os.path.join(tmp, "src") | ||
| 187 | os.mkdir(src) | ||
| 188 | write(os.path.join(src, "conv.pso"), CONV) | ||
| 189 | dialogue = os.path.join(tmp, "dialogue.csv") | ||
| 190 | old = "OLD GOOD REPORT\n" | ||
| 191 | with open(dialogue, "w", encoding="utf-8") as fh: | ||
| 192 | fh.write(old) | ||
| 193 | tables = os.path.join(tmp, "tables.csv") | ||
| 194 | os.mkdir(tables) # a later output that cannot be written | ||
| 195 | with contextlib.redirect_stderr(io.StringIO()) as err: | ||
| 196 | self.assertEqual(T.main([src, "--dialogue", dialogue, "--tables", tables]), 2) | ||
| 197 | self.assertIn("cannot write", err.getvalue()) | ||
| 198 | with open(dialogue, encoding="utf-8") as fh: | ||
| 199 | self.assertEqual(fh.read(), old) | ||
| 200 | self.assertFalse([f for f in os.listdir(tmp) if f.startswith(".text_tables-")]) | ||
| 201 | |||
| 202 | @unittest.skipUnless(os.name == "nt", "Windows denies os.replace on a file held open by a reader") | ||
| 203 | def test_reader_holding_a_later_report_keeps_all_reports(self): | ||
| 204 | with tempfile.TemporaryDirectory() as tmp: | ||
| 205 | src = os.path.join(tmp, "src") | ||
| 206 | os.mkdir(src) | ||
| 207 | write(os.path.join(src, "conv.pso"), CONV) | ||
| 208 | dialogue = os.path.join(tmp, "dialogue.csv") | ||
| 209 | tables = os.path.join(tmp, "tables.csv") | ||
| 210 | old_dialogue, old_tables = "OLD DIALOGUE\n", "OLD TABLES\n" | ||
| 211 | for path, text in ((dialogue, old_dialogue), (tables, old_tables)): | ||
| 212 | with open(path, "w", encoding="utf-8") as fh: | ||
| 213 | fh.write(text) | ||
| 214 | with open(tables, "rb"): # a reader keeps the second output open | ||
| 215 | with contextlib.redirect_stderr(io.StringIO()) as err: | ||
| 216 | self.assertEqual(T.main([src, "--dialogue", dialogue, "--tables", tables]), 2) | ||
| 217 | self.assertIn("cannot write", err.getvalue()) | ||
| 218 | with open(dialogue, encoding="utf-8") as fh: | ||
| 219 | self.assertEqual(fh.read(), old_dialogue) | ||
| 220 | with open(tables, encoding="utf-8") as fh: | ||
| 221 | self.assertEqual(fh.read(), old_tables) | ||
| 222 | self.assertFalse([f for f in os.listdir(tmp) if f.startswith(".text_tables-")], | ||
| 223 | "staging and backup files must not be left behind") | ||
| 224 | |||
| 225 | def test_two_outputs_naming_one_file_are_refused(self): | ||
| 226 | with tempfile.TemporaryDirectory() as tmp: | ||
| 227 | src = os.path.join(tmp, "src") | ||
| 228 | os.mkdir(src) | ||
| 229 | write(os.path.join(src, "conv.pso"), CONV) | ||
| 230 | out = os.path.join(tmp, "same.csv") | ||
| 231 | with contextlib.redirect_stderr(io.StringIO()) as err: | ||
| 232 | with self.assertRaises(SystemExit) as cm: | ||
| 233 | T.main([src, "--dialogue", out, "--tables", out]) | ||
| 234 | self.assertEqual(cm.exception.code, 2) | ||
| 235 | self.assertIn("distinct", err.getvalue()) | ||
| 236 | self.assertFalse(os.path.exists(out), "no report may be written before the check") | ||
| 181 | 237 | ||
| 182 | def test_missing_input(self): | 238 | def test_missing_input(self): |
| 183 | with contextlib.redirect_stderr(io.StringIO()): | 239 | with contextlib.redirect_stderr(io.StringIO()): |
diff --git a/tests/test_text_write_line_endings.py b/tests/test_text_write_line_endings.py new file mode 100644 index 000000000..e8be2944b --- /dev/null +++ b/tests/test_text_write_line_endings.py | |||
| @@ -0,0 +1,88 @@ | |||
| 1 | """Every text-mode file write in the Python tools names its line ending (BUILD-468). | ||
| 2 | |||
| 3 | `open(path, "w")` with no `newline=` turns each "\\n" into "\\r\\n" on Windows, so the same JSON report, manifest or | ||
| 4 | assembly listing is CRLF there and LF on Linux and macOS: the same input gives byte-different output per platform | ||
| 5 | (checksums and diffs differ). The CSV writers were fixed in #1573; this covers the other text writers. This test reads | ||
| 6 | the source with `ast` (standard library, no game data, no GPU) and fails for any `open` / `os.fdopen` in a text write | ||
| 7 | mode (`w`, `a`, `x`) or any `Path.write_text` under tools/, scripts/, make_game.py and runtime/test/shaders/ that has | ||
| 8 | no `newline=` argument. Pass `newline="\\n"` for LF output (or `newline=""` when the text carries its own line ends, | ||
| 9 | like a csv writer). | ||
| 10 | """ | ||
| 11 | import ast | ||
| 12 | import os | ||
| 13 | import sys | ||
| 14 | import unittest | ||
| 15 | |||
| 16 | HERE = os.path.dirname(os.path.abspath(__file__)) | ||
| 17 | ROOT = os.path.dirname(HERE) | ||
| 18 | SCAN = ("tools", "scripts", "make_game.py", os.path.join("runtime", "test", "shaders")) | ||
| 19 | |||
| 20 | |||
| 21 | def python_files(): | ||
| 22 | for entry in SCAN: | ||
| 23 | path = os.path.join(ROOT, entry) | ||
| 24 | if os.path.isfile(path): | ||
| 25 | yield path | ||
| 26 | continue | ||
| 27 | for base, dirs, files in os.walk(path): | ||
| 28 | dirs[:] = [d for d in dirs if d not in ("__pycache__", "build") and not d.startswith(".")] | ||
| 29 | for name in sorted(files): | ||
| 30 | if name.endswith(".py"): | ||
| 31 | yield os.path.join(base, name) | ||
| 32 | |||
| 33 | |||
| 34 | def unpinned_text_writes(source: str): | ||
| 35 | """Line numbers of text-mode writes in `source` that pass no `newline=`.""" | ||
| 36 | found = [] | ||
| 37 | for node in ast.walk(ast.parse(source)): | ||
| 38 | if not isinstance(node, ast.Call): | ||
| 39 | continue | ||
| 40 | func = node.func | ||
| 41 | name = getattr(func, "attr", getattr(func, "id", None)) | ||
| 42 | if any(k.arg == "newline" for k in node.keywords): | ||
| 43 | continue | ||
| 44 | if name in ("open", "fdopen"): | ||
| 45 | mode = None | ||
| 46 | if len(node.args) >= 2 and isinstance(node.args[1], ast.Constant): | ||
| 47 | mode = node.args[1].value | ||
| 48 | for k in node.keywords: | ||
| 49 | if k.arg == "mode" and isinstance(k.value, ast.Constant): | ||
| 50 | mode = k.value.value | ||
| 51 | if isinstance(mode, str) and "b" not in mode and any(c in mode for c in "wax"): | ||
| 52 | found.append(node.lineno) | ||
| 53 | elif name == "write_text": | ||
| 54 | found.append(node.lineno) | ||
| 55 | return found | ||
| 56 | |||
| 57 | |||
| 58 | class TextWriteLineEndings(unittest.TestCase): | ||
| 59 | def test_detector_finds_the_unpinned_forms(self): | ||
| 60 | src = ( | ||
| 61 | "open('a', 'w')\n" # 1 | ||
| 62 | "open('a', 'w', encoding='utf-8')\n" # 2 | ||
| 63 | "open('a', mode='a')\n" # 3 | ||
| 64 | "os.fdopen(3, 'w', encoding='utf-8')\n" # 4 | ||
| 65 | "p.write_text('x', encoding='utf-8')\n" # 5 | ||
| 66 | "open('a', 'w', newline='\\n')\n" # pinned | ||
| 67 | "open('a', 'w', newline='')\n" # pinned | ||
| 68 | "open('a', 'wb')\n" # binary | ||
| 69 | "open('a')\n" # read | ||
| 70 | "open('a', 'r', encoding='utf-8')\n" # read | ||
| 71 | "p.write_text('x', newline='\\n')\n" # pinned | ||
| 72 | ) | ||
| 73 | self.assertEqual(unpinned_text_writes(src), [1, 2, 3, 4, 5]) | ||
| 74 | |||
| 75 | def test_every_text_write_pins_its_newline(self): | ||
| 76 | bad = [] | ||
| 77 | count = 0 | ||
| 78 | for path in python_files(): | ||
| 79 | count += 1 | ||
| 80 | with open(path, encoding="utf-8") as f: | ||
| 81 | for line in unpinned_text_writes(f.read()): | ||
| 82 | bad.append(f"{os.path.relpath(path, ROOT)}:{line}") | ||
| 83 | self.assertGreater(count, 50, "the scan found almost no Python files; is the layout different?") | ||
| 84 | self.assertEqual(bad, [], "text writes without newline= (CRLF on Windows, LF elsewhere): " + ", ".join(bad)) | ||
| 85 | |||
| 86 | |||
| 87 | if __name__ == "__main__": | ||
| 88 | unittest.main() | ||
diff --git a/tests/test_tool_startup.py b/tests/test_tool_startup.py new file mode 100644 index 000000000..6933ad597 --- /dev/null +++ b/tests/test_tool_startup.py | |||
| @@ -0,0 +1,72 @@ | |||
| 1 | """Every tool that imports a sibling module starts under the project's own `python -I` convention. | ||
| 2 | |||
| 3 | `-I` implies `-P`, so the script's directory is not put on `sys.path`; a tool that imports the module next to it | ||
| 4 | has to add that directory itself (the pattern in `tools/anim_clips.py:40`). Two tools did not and died with | ||
| 5 | `ModuleNotFoundError` before `main()` — `calibrated_texture.py` and `ttpf_assets.py` — which this test caught. | ||
| 6 | |||
| 7 | The tool list is derived from the sources rather than written down, so a new tool with a sibling import is covered | ||
| 8 | without touching this file. `--help` is used because it reaches the argument parser without game files or a GPU; | ||
| 9 | the three module-only tools (`bcpack`, `calibrated_texture`, `cf_ref`) have no `__main__` and simply exit 0 on the | ||
| 10 | import. Tools that need numpy are skipped where it is not installed, as the texture tools are allowed to use it. | ||
| 11 | """ | ||
| 12 | import ast | ||
| 13 | import glob | ||
| 14 | import importlib.util | ||
| 15 | import os | ||
| 16 | import subprocess | ||
| 17 | import sys | ||
| 18 | import unittest | ||
| 19 | |||
| 20 | HERE = os.path.dirname(os.path.abspath(__file__)) | ||
| 21 | ROOT = os.path.dirname(HERE) | ||
| 22 | TOOLS = os.path.join(ROOT, "tools") | ||
| 23 | TOOL_NAMES = {os.path.splitext(os.path.basename(path))[0] for path in glob.glob(os.path.join(TOOLS, "*.py"))} | ||
| 24 | NUMERIC = {"amd_swizzle", "calibrated_texture", "swizzle_search", "tex_export", "tex_mode_probe", "tile_probe"} | ||
| 25 | |||
| 26 | # One process per tool is a few seconds in total; a hung import is a failure, not an infinite test. | ||
| 27 | TIMEOUT = 120 | ||
| 28 | |||
| 29 | |||
| 30 | def imports(path): | ||
| 31 | """The module names `path` imports at top level, relative imports excluded.""" | ||
| 32 | names = set() | ||
| 33 | for node in ast.walk(ast.parse(open(path, encoding="utf-8").read())): | ||
| 34 | if isinstance(node, ast.Import): | ||
| 35 | names |= {alias.name.split(".")[0] for alias in node.names} | ||
| 36 | elif isinstance(node, ast.ImportFrom) and node.level == 0 and node.module: | ||
| 37 | names.add(node.module.split(".")[0]) | ||
| 38 | return names | ||
| 39 | |||
| 40 | |||
| 41 | def sibling_importers(): | ||
| 42 | found = [] | ||
| 43 | for path in sorted(glob.glob(os.path.join(TOOLS, "*.py"))): | ||
| 44 | own = os.path.splitext(os.path.basename(path))[0] | ||
| 45 | if imports(path) & (TOOL_NAMES - {own}): | ||
| 46 | found.append(path) | ||
| 47 | return found | ||
| 48 | |||
| 49 | |||
| 50 | class ToolStartupTests(unittest.TestCase): | ||
| 51 | def test_each_sibling_importing_tool_starts(self): | ||
| 52 | paths = sibling_importers() | ||
| 53 | self.assertGreater(len(paths), 20, "the sibling-import scan found almost nothing") | ||
| 54 | have_numpy = importlib.util.find_spec("numpy") is not None | ||
| 55 | for path in paths: | ||
| 56 | name = os.path.splitext(os.path.basename(path))[0] | ||
| 57 | if name in NUMERIC and not have_numpy: | ||
| 58 | continue | ||
| 59 | with self.subTest(tool=name): | ||
| 60 | proc = subprocess.run([sys.executable, "-I", path, "--help"], capture_output=True, text=True, | ||
| 61 | timeout=TIMEOUT, errors="replace") | ||
| 62 | self.assertEqual(proc.returncode, 0, proc.stderr[-2000:]) | ||
| 63 | self.assertNotIn("Traceback", proc.stderr) | ||
| 64 | |||
| 65 | def test_the_two_fixed_tools_are_in_the_scan(self): | ||
| 66 | names = {os.path.splitext(os.path.basename(path))[0] for path in sibling_importers()} | ||
| 67 | self.assertIn("calibrated_texture", names) | ||
| 68 | self.assertIn("ttpf_assets", names) | ||
| 69 | |||
| 70 | |||
| 71 | if __name__ == "__main__": | ||
| 72 | unittest.main() | ||
diff --git a/tests/test_user_sgpr_census.py b/tests/test_user_sgpr_census.py index 4a94ff372..2c52fbe46 100644 --- a/tests/test_user_sgpr_census.py +++ b/tests/test_user_sgpr_census.py | |||
| @@ -1,7 +1,12 @@ | |||
| 1 | """tools/user_sgpr_census.py on hand-written index.json data (no game files, no GPU).""" | 1 | """tools/user_sgpr_census.py on hand-written index.json data (no game files, no GPU).""" |
| 2 | import json | 2 | import json |
| 3 | import os | 3 | import os |
| 4 | from pathlib import Path | ||
| 5 | import subprocess | ||
| 4 | import sys | 6 | import sys |
| 7 | import tempfile | ||
| 8 | |||
| 9 | import pytest | ||
| 5 | 10 | ||
| 6 | ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | 11 | ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) |
| 7 | sys.path.insert(0, os.path.join(ROOT, "tools")) | 12 | sys.path.insert(0, os.path.join(ROOT, "tools")) |
| @@ -73,9 +78,62 @@ def test_the_two_packing_models_are_told_apart(): | |||
| 73 | assert b["below_base"] == {"s1:const32": 1} | 78 | assert b["below_base"] == {"s1:const32": 1} |
| 74 | 79 | ||
| 75 | 80 | ||
| 81 | @pytest.mark.parametrize("output_kind", ["same-path", "relative-alias", "hard-link"]) | ||
| 82 | def test_json_report_refuses_to_overwrite_index(tmp_path, capsys, output_kind): | ||
| 83 | index = tmp_path / "index.json" | ||
| 84 | original = json.dumps(INDEX).encode("utf-8") | ||
| 85 | index.write_bytes(original) | ||
| 86 | output = index | ||
| 87 | if output_kind == "relative-alias": | ||
| 88 | subdir = tmp_path / "subdir" | ||
| 89 | subdir.mkdir() | ||
| 90 | output = subdir / ".." / index.name | ||
| 91 | elif output_kind == "hard-link": | ||
| 92 | output = tmp_path / "alias.json" | ||
| 93 | try: | ||
| 94 | output.hardlink_to(index) | ||
| 95 | except OSError as err: | ||
| 96 | pytest.skip(f"hard links unavailable: {err}") | ||
| 97 | |||
| 98 | with pytest.raises(SystemExit) as exc: | ||
| 99 | usc.main([str(index), "--json", str(output)]) | ||
| 100 | |||
| 101 | assert exc.value.code == 2 | ||
| 102 | assert "--json must not overwrite the input index" in capsys.readouterr().err | ||
| 103 | assert index.read_bytes() == original | ||
| 104 | |||
| 105 | |||
| 106 | def test_json_report_accepts_a_separate_output(tmp_path): | ||
| 107 | index = tmp_path / "index.json" | ||
| 108 | output = tmp_path / "summary.json" | ||
| 109 | index.write_text(json.dumps(INDEX), encoding="utf-8") | ||
| 110 | |||
| 111 | assert usc.main([str(index), "--json", str(output)]) == 0 | ||
| 112 | assert json.loads(output.read_text(encoding="utf-8"))["ps"]["lowest_pointer_sgpr"] == {"s8": 2, "s9": 1} | ||
| 113 | assert json.loads(index.read_text(encoding="utf-8")) == INDEX | ||
| 114 | |||
| 115 | |||
| 76 | def test_expect_passes_and_fails(tmp_path, capsys): | 116 | def test_expect_passes_and_fails(tmp_path, capsys): |
| 77 | p = tmp_path / "index.json" | 117 | p = tmp_path / "index.json" |
| 78 | p.write_text(json.dumps(INDEX), encoding="utf-8") | 118 | p.write_text(json.dumps(INDEX), encoding="utf-8") |
| 79 | assert usc.main([str(p), "--expect", "ps=8", "cs=4"]) == 0 | 119 | assert usc.main([str(p), "--expect", "ps=8", "cs=4"]) == 0 |
| 80 | assert usc.main([str(p), "--expect", "ps=0"]) == 1 | 120 | assert usc.main([str(p), "--expect", "ps=0"]) == 1 |
| 81 | assert "expected s0, got s8" in capsys.readouterr().err | 121 | assert "expected s0, got s8" in capsys.readouterr().err |
| 122 | |||
| 123 | |||
| 124 | def test_cli_rejects_malformed_stage_assignment(): | ||
| 125 | with tempfile.TemporaryDirectory() as tmp: | ||
| 126 | index = Path(tmp, "index.json") | ||
| 127 | report = Path(tmp, "report.json") | ||
| 128 | index.write_text(json.dumps(INDEX), encoding="utf-8") | ||
| 129 | tool = os.path.join(ROOT, "tools", "user_sgpr_census.py") | ||
| 130 | for option in ("--base", "--expect"): | ||
| 131 | for assignment in ("ps", "ps=bad", "=8", "ps=-1"): | ||
| 132 | result = subprocess.run( | ||
| 133 | [sys.executable, "-I", tool, str(index), "--json", str(report), option, assignment], | ||
| 134 | capture_output=True, text=True, | ||
| 135 | ) | ||
| 136 | assert result.returncode == 2, result.stderr | ||
| 137 | assert "expected STAGE=SGPR" in result.stderr | ||
| 138 | assert "Traceback" not in result.stderr | ||
| 139 | assert not report.exists() | ||
diff --git a/tests/test_viewer_streaming.cjs b/tests/test_viewer_streaming.cjs index 596caaa19..666bd9ffc 100644 --- a/tests/test_viewer_streaming.cjs +++ b/tests/test_viewer_streaming.cjs | |||
| @@ -6,6 +6,7 @@ const { test } = require('node:test'); | |||
| 6 | 6 | ||
| 7 | // Exercise the viewer's actual loading and streaming code without WebGL, a network or game data. | 7 | // Exercise the viewer's actual loading and streaming code without WebGL, a network or game data. |
| 8 | const html = readFileSync(join(__dirname, '..', 'viewer', 'index.html'), 'utf8'); | 8 | const html = readFileSync(join(__dirname, '..', 'viewer', 'index.html'), 'utf8'); |
| 9 | const viewerModule = html.match(/<script type="module">([\s\S]*?)<\/script>/)[1].replace(/^import .*;$/gm, ''); | ||
| 9 | const worldBegin = html.indexOf('// ---------- world description ----------'); | 10 | const worldBegin = html.indexOf('// ---------- world description ----------'); |
| 10 | const worldEnd = html.indexOf('// Deterministic test terrain:', worldBegin); | 11 | const worldEnd = html.indexOf('// Deterministic test terrain:', worldBegin); |
| 11 | assert(worldBegin >= 0 && worldEnd > worldBegin, 'viewer world description section must exist'); | 12 | assert(worldBegin >= 0 && worldEnd > worldBegin, 'viewer world description section must exist'); |
| @@ -69,8 +70,21 @@ test('test mode, a missing manifest, and an unreadable manifest have distinct me | |||
| 69 | assert.match(unreachable.reason, /could not be loaded/); | 70 | assert.match(unreachable.reason, /could not be loaded/); |
| 70 | }); | 71 | }); |
| 71 | 72 | ||
| 73 | test('a WebGL startup error replaces the fly prompt and preserves the original error', async () => { | ||
| 74 | const error = new Error('Error creating WebGL context.'); | ||
| 75 | const attributes = new Map(); | ||
| 76 | const start = { textContent: 'Click to fly', style: {}, setAttribute: (name, value) => attributes.set(name, value) }; | ||
| 77 | const startup = vm.runInNewContext(`(async () => { ${viewerModule} })()`, { | ||
| 78 | THREE: { WebGLRenderer: class { constructor() { throw error; } } }, | ||
| 79 | document: { getElementById: id => { assert.equal(id, 'start'); return start; } }, | ||
| 80 | }); | ||
| 81 | await assert.rejects(startup, actual => actual === error); | ||
| 82 | assert.match(start.textContent, /Could not start WebGL/); | ||
| 83 | assert.equal(start.style.cursor, 'default'); | ||
| 84 | assert.equal(attributes.get('role'), 'alert'); | ||
| 85 | }); | ||
| 86 | |||
| 72 | test('the bounds overlay creates helpers on the first G press and reuses them', async () => { | 87 | test('the bounds overlay creates helpers on the first G press and reuses them', async () => { |
| 73 | const viewerModule = html.match(/<script type="module">([\s\S]*?)<\/script>/)[1].replace(/^import .*;$/gm, ''); | ||
| 74 | const chunks = [worldChunk, { id: 'other', url: 'other.glb', bounds: [5, 6, 7, 8, 9, 10] }]; | 88 | const chunks = [worldChunk, { id: 'other', url: 'other.glb', bounds: [5, 6, 7, 8, 9, 10] }]; |
| 75 | const handlers = new Map(); | 89 | const handlers = new Map(); |
| 76 | const boundsGroup = await vm.runInNewContext(`(async () => { ${viewerModule}\nreturn boundsGroup; })()`, { | 90 | const boundsGroup = await vm.runInNewContext(`(async () => { ${viewerModule}\nreturn boundsGroup; })()`, { |
diff --git a/tests/test_vk_pipeline_check_index.py b/tests/test_vk_pipeline_check_index.py new file mode 100644 index 000000000..a94023c80 --- /dev/null +++ b/tests/test_vk_pipeline_check_index.py | |||
| @@ -0,0 +1,65 @@ | |||
| 1 | """vk_pipeline_check: a missing, unreadable or empty index.json is an error, not an empty corpus (TEST-257). | ||
| 2 | |||
| 3 | It used to exit 0 after checking nothing. The index is read before Vulkan is loaded, so the failing cases need no GPU | ||
| 4 | and no game data. A valid `{}` stays an intentionally empty index: it gets past the index (the run may then stop at | ||
| 5 | Vulkan on a machine without a device, which is not what is checked here). Skips when vk_pipeline_check isn't built. | ||
| 6 | Set LEONIDA_VK_PIPELINE_CHECK to use a binary elsewhere. | ||
| 7 | """ | ||
| 8 | import os | ||
| 9 | import subprocess | ||
| 10 | import tempfile | ||
| 11 | import unittest | ||
| 12 | from pathlib import Path | ||
| 13 | |||
| 14 | ROOT = Path(__file__).resolve().parent.parent | ||
| 15 | |||
| 16 | |||
| 17 | def find_binary(): | ||
| 18 | env = os.environ.get("LEONIDA_VK_PIPELINE_CHECK") | ||
| 19 | if env: | ||
| 20 | return Path(env) if Path(env).is_file() else None | ||
| 21 | build = ROOT / "runtime" / "build" | ||
| 22 | for p in (build / "linux" / "vk_pipeline_check", build / "vk_pipeline_check", build / "Release" / "vk_pipeline_check.exe"): | ||
| 23 | if p.is_file(): | ||
| 24 | return p | ||
| 25 | return None | ||
| 26 | |||
| 27 | |||
| 28 | class IndexTest(unittest.TestCase): | ||
| 29 | @classmethod | ||
| 30 | def setUpClass(cls): | ||
| 31 | cls.exe = find_binary() | ||
| 32 | if cls.exe is None: | ||
| 33 | raise unittest.SkipTest("vk_pipeline_check isn't built (cmake -S runtime -B runtime/build/linux)") | ||
| 34 | |||
| 35 | def run_tool(self, index_text): | ||
| 36 | with tempfile.TemporaryDirectory() as d: | ||
| 37 | if index_text is not None: | ||
| 38 | Path(d, "index.json").write_text(index_text, encoding="utf-8") | ||
| 39 | return subprocess.run([str(self.exe), d], capture_output=True, text=True, timeout=60) | ||
| 40 | |||
| 41 | def assert_index_error(self, r): | ||
| 42 | self.assertEqual(r.returncode, 2, r.stderr) | ||
| 43 | self.assertIn("cannot use", r.stderr) | ||
| 44 | self.assertIn("index.json", r.stderr) | ||
| 45 | |||
| 46 | def test_missing_index_is_an_error(self): | ||
| 47 | self.assert_index_error(self.run_tool(None)) | ||
| 48 | |||
| 49 | def test_empty_index_is_an_error(self): | ||
| 50 | self.assert_index_error(self.run_tool("")) | ||
| 51 | |||
| 52 | def test_whitespace_only_index_is_an_error(self): | ||
| 53 | self.assert_index_error(self.run_tool(" \n\t \n")) | ||
| 54 | |||
| 55 | def test_malformed_index_is_still_an_error(self): | ||
| 56 | self.assert_index_error(self.run_tool('{"a": ')) | ||
| 57 | |||
| 58 | def test_valid_empty_object_is_an_empty_corpus(self): | ||
| 59 | r = self.run_tool("{}") | ||
| 60 | self.assertNotIn("cannot use", r.stderr) | ||
| 61 | self.assertIn("0 shaders in index", r.stderr) | ||
| 62 | |||
| 63 | |||
| 64 | if __name__ == "__main__": | ||
| 65 | unittest.main() | ||
diff --git a/tests/test_vk_pipeline_check_isolate.py b/tests/test_vk_pipeline_check_isolate.py new file mode 100644 index 000000000..38147cbeb --- /dev/null +++ b/tests/test_vk_pipeline_check_isolate.py | |||
| @@ -0,0 +1,129 @@ | |||
| 1 | """vk_pipeline_check --isolate: a module that kills the driver is recorded as failed and the pass goes on. | ||
| 2 | |||
| 3 | No game data: five tiny compute shaders are assembled here with spirv-as. The crash is simulated with the tool's test | ||
| 4 | hook VK_PIPELINE_CHECK_SIMULATE_CRASH (a signal raised just before the pipeline of the named module), so no crashing | ||
| 5 | driver is needed. Skips (not fails) when vk_pipeline_check isn't built, spirv-as is missing, the platform is not POSIX | ||
| 6 | or there is no usable Vulkan device. Pin a GPU with VK_LOADER_DRIVERS_SELECT / LEONIDA_VK_DEVICE as for the other | ||
| 7 | Vulkan tools. Set LEONIDA_VK_PIPELINE_CHECK to use a binary elsewhere. | ||
| 8 | """ | ||
| 9 | import json | ||
| 10 | import os | ||
| 11 | import shutil | ||
| 12 | import subprocess | ||
| 13 | import tempfile | ||
| 14 | import unittest | ||
| 15 | from pathlib import Path | ||
| 16 | |||
| 17 | ROOT = Path(__file__).resolve().parent.parent | ||
| 18 | NAMES = ["m_alpha", "m_bravo", "m_charlie", "m_delta", "m_echo"] | ||
| 19 | CRASHER = "m_charlie" | ||
| 20 | |||
| 21 | ASM = """OpCapability Shader | ||
| 22 | OpMemoryModel Logical GLSL450 | ||
| 23 | OpEntryPoint GLCompute %main "main" | ||
| 24 | OpExecutionMode %main LocalSize {size} 1 1 | ||
| 25 | %void = OpTypeVoid | ||
| 26 | %fn = OpTypeFunction %void | ||
| 27 | %main = OpFunction %void None %fn | ||
| 28 | %entry = OpLabel | ||
| 29 | OpReturn | ||
| 30 | OpFunctionEnd | ||
| 31 | """ | ||
| 32 | |||
| 33 | |||
| 34 | def find_binary(): | ||
| 35 | env = os.environ.get("LEONIDA_VK_PIPELINE_CHECK") | ||
| 36 | if env: | ||
| 37 | return Path(env) if Path(env).is_file() else None | ||
| 38 | build = ROOT / "runtime" / "build" | ||
| 39 | for p in (build / "linux" / "vk_pipeline_check", build / "vk_pipeline_check"): | ||
| 40 | if p.is_file(): | ||
| 41 | return p | ||
| 42 | return None | ||
| 43 | |||
| 44 | |||
| 45 | class IsolateTest(unittest.TestCase): | ||
| 46 | @classmethod | ||
| 47 | def setUpClass(cls): | ||
| 48 | if os.name != "posix": | ||
| 49 | raise unittest.SkipTest("--isolate is POSIX only") | ||
| 50 | cls.exe = find_binary() | ||
| 51 | if cls.exe is None: | ||
| 52 | raise unittest.SkipTest("vk_pipeline_check isn't built (cmake -S runtime -B runtime/build/linux)") | ||
| 53 | spirv_as = shutil.which("spirv-as") | ||
| 54 | if not spirv_as: | ||
| 55 | raise unittest.SkipTest("spirv-as not found") | ||
| 56 | cls.tmp = tempfile.TemporaryDirectory() | ||
| 57 | cls.addClassCleanup(cls.tmp.cleanup) | ||
| 58 | cls.dir = Path(cls.tmp.name) / "spirv" | ||
| 59 | cls.dir.mkdir() | ||
| 60 | index = {} | ||
| 61 | for i, name in enumerate(NAMES): | ||
| 62 | asm = Path(cls.tmp.name) / (name + ".spvasm") | ||
| 63 | asm.write_text(ASM.format(size=1 << i)) | ||
| 64 | subprocess.run([spirv_as, "--target-env", "vulkan1.1", str(asm), "-o", str(cls.dir / (name + ".spv"))], | ||
| 65 | check=True) | ||
| 66 | index[name] = {"stage": "cs", "subgroup_size": None, "features": []} | ||
| 67 | (cls.dir / "index.json").write_text(json.dumps(index)) | ||
| 68 | probe = cls.run_tool([], cache=Path(cls.tmp.name) / "probe.cache") | ||
| 69 | if probe.returncode != 0 or "cs pipelines: 5 ok, 0 failed" not in probe.stdout: | ||
| 70 | raise unittest.SkipTest("no usable Vulkan device (exit %d): %s" % (probe.returncode, probe.stderr.strip()[-300:])) | ||
| 71 | |||
| 72 | @classmethod | ||
| 73 | def run_tool(cls, args, crash=None, cache=None): | ||
| 74 | env = dict(os.environ) | ||
| 75 | env.pop("VK_PIPELINE_CHECK_SIMULATE_CRASH", None) | ||
| 76 | if crash: | ||
| 77 | env["VK_PIPELINE_CHECK_SIMULATE_CRASH"] = crash | ||
| 78 | cmd = [str(cls.exe), str(cls.dir)] + ([str(cache)] if cache else []) + ["--jobs", "2"] + args | ||
| 79 | return subprocess.run(cmd, env=env, capture_output=True, text=True, timeout=300) | ||
| 80 | |||
| 81 | def cache(self, name): | ||
| 82 | return Path(self.tmp.name) / name | ||
| 83 | |||
| 84 | def test_normal_run_passes(self): | ||
| 85 | r = self.run_tool([], cache=self.cache("normal.cache")) | ||
| 86 | self.assertEqual(r.returncode, 0, r.stdout + r.stderr) | ||
| 87 | self.assertIn("cs: 5 modules ok, 0 failed", r.stdout) | ||
| 88 | self.assertIn("cs pipelines: 5 ok, 0 failed, 0 skipped", r.stdout) | ||
| 89 | |||
| 90 | def test_isolate_without_a_crash_matches_normal_counts(self): | ||
| 91 | r = self.run_tool(["--isolate", "--isolate-batch", "2"], cache=self.cache("iso_clean.cache")) | ||
| 92 | self.assertEqual(r.returncode, 0, r.stdout + r.stderr) | ||
| 93 | self.assertIn("cs: 5 modules ok, 0 failed", r.stdout) | ||
| 94 | self.assertIn("cs pipelines: 5 ok, 0 failed, 0 skipped", r.stdout) | ||
| 95 | self.assertNotIn("CRASH", r.stdout) | ||
| 96 | |||
| 97 | def test_without_isolate_the_driver_crash_ends_the_process(self): | ||
| 98 | r = self.run_tool([], crash=CRASHER, cache=self.cache("dies.cache")) | ||
| 99 | self.assertEqual(r.returncode, -8, r.stdout + r.stderr) # killed by SIGFPE: no summary, no exit status | ||
| 100 | |||
| 101 | def test_isolate_records_the_crashed_module_and_goes_on(self): | ||
| 102 | cache = self.cache("iso.cache") | ||
| 103 | for batch in ("5", "2", "1"): # one batch bisected down, several batches, one module at a time | ||
| 104 | with self.subTest(batch=batch): | ||
| 105 | r = self.run_tool(["--isolate", "--isolate-batch", batch], crash=CRASHER + ":SIGFPE", cache=cache) | ||
| 106 | self.assertNotEqual(r.returncode, 0, r.stdout + r.stderr) | ||
| 107 | self.assertGreater(r.returncode, 0, "the parent itself must not die: " + r.stdout + r.stderr) | ||
| 108 | self.assertIn("MODULE CRASH %s (cs, driver crashed: SIGFPE)" % CRASHER, r.stdout) | ||
| 109 | self.assertEqual(r.stdout.count("MODULE CRASH"), 1, r.stdout) | ||
| 110 | self.assertIn("cs: 4 modules ok, 0 failed", r.stdout) | ||
| 111 | self.assertIn("cs pipelines: 4 ok, 1 failed, 0 skipped", r.stdout) | ||
| 112 | self.assertIn("cs crashed the driver: 1", r.stdout) | ||
| 113 | for name in NAMES: | ||
| 114 | if name != CRASHER: | ||
| 115 | self.assertNotIn("FAIL " + name, r.stdout) | ||
| 116 | self.assertTrue(cache.is_file(), "the shared pipeline cache must survive the crash") | ||
| 117 | |||
| 118 | def test_other_signal(self): | ||
| 119 | r = self.run_tool(["--isolate"], crash=CRASHER + ":SEGV") | ||
| 120 | self.assertEqual(r.returncode, 1, r.stdout + r.stderr) | ||
| 121 | self.assertIn("MODULE CRASH %s (cs, driver crashed: SIGSEGV)" % CRASHER, r.stdout) | ||
| 122 | |||
| 123 | def test_isolate_rejects_stats(self): | ||
| 124 | r = self.run_tool(["--isolate", "--stats", str(self.cache("s.csv"))]) | ||
| 125 | self.assertEqual(r.returncode, 2) | ||
| 126 | |||
| 127 | |||
| 128 | if __name__ == "__main__": | ||
| 129 | unittest.main() | ||
diff --git a/tests/test_vk_subgroup_info.py b/tests/test_vk_subgroup_info.py index a6fce5ea4..d8ca4ed0f 100644 --- a/tests/test_vk_subgroup_info.py +++ b/tests/test_vk_subgroup_info.py | |||
| @@ -525,6 +525,67 @@ class QueryTest(unittest.TestCase): | |||
| 525 | self.assertEqual(res["device"], expected_name) | 525 | self.assertEqual(res["device"], expected_name) |
| 526 | self.assertEqual(vk.destroyed_instances, [FakeVulkan.INSTANCE_HANDLE]) | 526 | self.assertEqual(vk.destroyed_instances, [FakeVulkan.INSTANCE_HANDLE]) |
| 527 | 527 | ||
| 528 | def test_leonida_vk_device_filters_case_insensitively_and_fails_on_no_match(self): | ||
| 529 | igpu = FakeDevice( | ||
| 530 | name="AMD Radeon(TM) 780M Graphics", | ||
| 531 | device_type=1, | ||
| 532 | subgroup_size=64, | ||
| 533 | min_subgroup_size=32, | ||
| 534 | max_subgroup_size=64, | ||
| 535 | ) | ||
| 536 | dgpu = FakeDevice( | ||
| 537 | name="NVIDIA GeForce RTX 4070", | ||
| 538 | device_type=vk_info.VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU, | ||
| 539 | subgroup_size=32, | ||
| 540 | min_subgroup_size=32, | ||
| 541 | max_subgroup_size=32, | ||
| 542 | ) | ||
| 543 | other_dgpu = FakeDevice( | ||
| 544 | name="AMD Radeon RX 7900 XTX", | ||
| 545 | device_type=vk_info.VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU, | ||
| 546 | subgroup_size=64, | ||
| 547 | min_subgroup_size=32, | ||
| 548 | max_subgroup_size=64, | ||
| 549 | ) | ||
| 550 | old_match = FakeDevice( | ||
| 551 | name="Legacy Radeon 1.2", | ||
| 552 | api_version=(1 << 22) | (2 << 12), | ||
| 553 | ) | ||
| 554 | |||
| 555 | # Unset or empty selects the last discrete GPU as usual. | ||
| 556 | for empty in ("",): | ||
| 557 | with mock.patch.dict(vk_info.os.environ, {"LEONIDA_VK_DEVICE": empty}): | ||
| 558 | res, _ = self._run_query(igpu, dgpu) | ||
| 559 | self.assertEqual(res["device"], "NVIDIA GeForce RTX 4070") | ||
| 560 | self.assertFalse(res["native64"]) | ||
| 561 | |||
| 562 | # Case-insensitive substring can select the integrated GPU over a later discrete GPU. | ||
| 563 | for filt in ("780m", "RADEON(tm) 780M", "amd radeon"): | ||
| 564 | with self.subTest(filter=filt), mock.patch.dict(vk_info.os.environ, {"LEONIDA_VK_DEVICE": filt}): | ||
| 565 | res, vk = self._run_query(igpu, dgpu) | ||
| 566 | self.assertEqual(res["device"], "AMD Radeon(TM) 780M Graphics") | ||
| 567 | self.assertTrue(res["native64"]) | ||
| 568 | # Non-matching discrete GPU was skipped before feature/queue queries. | ||
| 569 | self.assertEqual(vk.features_calls, [vk._device_handles[0]]) | ||
| 570 | self.assertEqual(vk.queue_calls, [vk._device_handles[0], vk._device_handles[0]]) | ||
| 571 | |||
| 572 | # Among multiple matching devices, the runtime's discrete/last-discrete rule still applies. | ||
| 573 | with mock.patch.dict(vk_info.os.environ, {"LEONIDA_VK_DEVICE": "radeon"}): | ||
| 574 | res, _ = self._run_query(igpu, dgpu, other_dgpu) | ||
| 575 | self.assertEqual(res["device"], "AMD Radeon RX 7900 XTX") | ||
| 576 | with mock.patch.dict(vk_info.os.environ, {"LEONIDA_VK_DEVICE": "geforce"}): | ||
| 577 | res, _ = self._run_query(igpu, dgpu, other_dgpu) | ||
| 578 | self.assertEqual(res["device"], "NVIDIA GeForce RTX 4070") | ||
| 579 | |||
| 580 | # A filter that matches no device (or only an unsuitable device) raises RuntimeError and destroys the instance. | ||
| 581 | for filt, devs in (("nomatch", (igpu, dgpu)), ("legacy", (old_match, dgpu))): | ||
| 582 | with self.subTest(no_match=filt), mock.patch.dict(vk_info.os.environ, {"LEONIDA_VK_DEVICE": filt}): | ||
| 583 | vk = FakeVulkan(devices=devs) | ||
| 584 | with mock.patch.object(vk_info, "load_vulkan", return_value=vk): | ||
| 585 | with self.assertRaisesRegex(RuntimeError, rf"LEONIDA_VK_DEVICE={filt}"): | ||
| 586 | vk_info.query() | ||
| 587 | self.assertEqual(vk.destroyed_instances, [FakeVulkan.INSTANCE_HANDLE]) | ||
| 588 | |||
| 528 | def test_native64_conditions_and_boundaries(self): | 589 | def test_native64_conditions_and_boundaries(self): |
| 529 | both = vk_info.VK_SHADER_STAGE_COMPUTE_BIT | vk_info.VK_SHADER_STAGE_MESH_BIT_EXT | 590 | both = vk_info.VK_SHADER_STAGE_COMPUTE_BIT | vk_info.VK_SHADER_STAGE_MESH_BIT_EXT |
| 530 | cases = [ | 591 | cases = [ |
diff --git a/tests/test_wave64_graphics_scan.py b/tests/test_wave64_graphics_scan.py index 45945cd29..1aff7139e 100644 --- a/tests/test_wave64_graphics_scan.py +++ b/tests/test_wave64_graphics_scan.py | |||
| @@ -140,6 +140,15 @@ class ScanTests(unittest.TestCase): | |||
| 140 | 140 | ||
| 141 | 141 | ||
| 142 | class CliTests(unittest.TestCase): | 142 | class CliTests(unittest.TestCase): |
| 143 | def test_scan_ignores_shader_named_directories(self): | ||
| 144 | with tempfile.TemporaryDirectory() as src: | ||
| 145 | os.mkdir(os.path.join(src, "cache.s")) | ||
| 146 | name, text = PS_W64_SENSITIVE | ||
| 147 | with open(os.path.join(src, name), "w", encoding="utf-8") as f: | ||
| 148 | f.write(text) | ||
| 149 | report = scan.scan_directory(src) | ||
| 150 | self.assertEqual(report["per_stage"]["ps"]["shaders"], 1) | ||
| 151 | |||
| 143 | def test_missing_source_directory_raises_error(self): | 152 | def test_missing_source_directory_raises_error(self): |
| 144 | with self.assertRaises(SystemExit) as cm: | 153 | with self.assertRaises(SystemExit) as cm: |
| 145 | with contextlib.redirect_stderr(io.StringIO()): | 154 | with contextlib.redirect_stderr(io.StringIO()): |
diff --git a/tests/test_wave64_halves_fixtures.py b/tests/test_wave64_halves_fixtures.py index 8d0fbe584..7cf045ec9 100644 --- a/tests/test_wave64_halves_fixtures.py +++ b/tests/test_wave64_halves_fixtures.py | |||
| @@ -1,9 +1,11 @@ | |||
| 1 | """SHADER-10: the hand-written ps_w64_* fixtures get the tier their header names, and the census counts tiers. | 1 | """SHADER-10: the hand-written ps_w64_* and vs_w64_* fixtures get the tier their header names, and the census counts |
| 2 | 2 | tiers. | |
| 3 | The fixtures (runtime/test/shaders/ps_w64_{a,b,c}_*.asm) are the GPU tests of w64_graphics.py: each was drawn on an | 3 | |
| 4 | AMD Radeon 880M with the fragment subgroup size required to 64 and to 32. Tier A and B fixtures gave identical images | 4 | The fixtures (runtime/test/shaders/{ps,vs}_w64_{a,b,c}_*.asm) are the GPU tests of w64_graphics.py: each pixel fixture |
| 5 | (and the words their header derives), tier C fixtures differed, so this test pins the translator's detector to what | 5 | was drawn on an AMD Radeon 880M with the fragment subgroup size required to 64 and to 32, each vertex fixture (TEST-251) |
| 6 | the hardware showed. Needs llvm-mc with the AMDGPU target and spirv-as / spirv-val, like the other tests that build | 6 | on an RX 9070 XT and a Ryzen 9800X3D iGPU (RADV) with the VS stage at wave64 and at wave32 (RADV_PERFTEST=gewave32). |
| 7 | Tier A and B fixtures gave identical words (and the words their header derives), tier C fixtures differed, so this | ||
| 8 | test pins the translator's detector to what the hardware showed. Needs llvm-mc with the AMDGPU target and spirv-as / spirv-val, like the other tests that build | ||
| 7 | shaders; the pure-Python parts run without them. | 9 | shaders; the pure-Python parts run without them. |
| 8 | """ | 10 | """ |
| 9 | import json | 11 | import json |
| @@ -38,11 +40,18 @@ EXPECT = { | |||
| 38 | "ps_w64_c_vote_else": ("C", ["unsafe-vote-branch"], None), | 40 | "ps_w64_c_vote_else": ("C", ["unsafe-vote-branch"], None), |
| 39 | "ps_w64_c_scc_vote": ("C", ["cross-lane"], None), | 41 | "ps_w64_c_scc_vote": ("C", ["cross-lane"], None), |
| 40 | "ps_w64_c_execz_sgpr": ("C", ["stale-scalar", "unsafe-execz-branch"], None), | 42 | "ps_w64_c_execz_sgpr": ("C", ["stale-scalar", "unsafe-execz-branch"], None), |
| 43 | "vs_w64_a_skip": ("A", [], []), | ||
| 44 | "vs_w64_b_waterfall": ("B", [], ["waterfall"]), | ||
| 45 | "vs_w64_b_readlane_uniform": ("B", [], ["readfirstlane-uniform", "readlane-uniform"]), | ||
| 46 | "vs_w64_b_ballot_atomic": ("B", [], ["aggregated-atomic", "elected-lane"]), | ||
| 47 | "vs_w64_c_bcnt_export": ("C", ["lane-count"], None), | ||
| 48 | "vs_w64_c_readlane": ("C", ["cross-lane"], None), | ||
| 49 | "vs_w64_c_lane_id": ("C", ["lane-id"], None), | ||
| 41 | } | 50 | } |
| 42 | 51 | ||
| 43 | 52 | ||
| 44 | def test_every_fixture_has_a_tier_and_a_gpu_check(): | 53 | def test_every_fixture_has_a_tier_and_a_gpu_check(): |
| 45 | asm = {f[:-4] for f in os.listdir(SHADERS) if f.startswith("ps_w64_") and f.endswith(".asm")} | 54 | asm = {f[:-4] for f in os.listdir(SHADERS) if f.startswith(("ps_w64_", "vs_w64_")) and f.endswith(".asm")} |
| 46 | assert asm == set(EXPECT) == set(w64_graphics.FIXTURES) | 55 | assert asm == set(EXPECT) == set(w64_graphics.FIXTURES) |
| 47 | for name, (tier, _, _) in EXPECT.items(): | 56 | for name, (tier, _, _) in EXPECT.items(): |
| 48 | assert w64_graphics.FIXTURES[name][0] == tier | 57 | assert w64_graphics.FIXTURES[name][0] == tier |
| @@ -125,3 +134,15 @@ def test_expected_words_of_the_gpu_fixtures(): | |||
| 125 | assert w64_graphics._a_skip(6 + 64 * 2) == (1006, 0, 2000 + 2 + 9, 3) | 134 | assert w64_graphics._a_skip(6 + 64 * 2) == (1006, 0, 2000 + 2 + 9, 3) |
| 126 | assert w64_graphics._b_waterfall(5 + 64 * 6) == (17 * ((5 & 3) + 4 * (6 & 3)) + 5, (5 & 3) + 4 * (6 & 3), 0, 0) | 135 | assert w64_graphics._b_waterfall(5 + 64 * 6) == (17 * ((5 & 3) + 4 * (6 & 3)) + 5, (5 & 3) + 4 * (6 & 3), 0, 0) |
| 127 | assert w64_graphics._b_readfirstlane(10) == (133, 277, 0, 0) | 136 | assert w64_graphics._b_readfirstlane(10) == (133, 277, 0, 0) |
| 137 | assert w64_graphics._vs_a_skip(1 + 64 * 3) == (7 * 3 + 1, 1, 2000 + 3, 2) # no whole-quad word in r1 | ||
| 138 | assert w64_graphics._vs_a_skip(6 + 64 * 2) == (1006, 0, 2000 + 2 + 9, 3) | ||
| 139 | assert w64_graphics._vs_b_readlane_uniform(70) == (6 + 123, 200, 6 + 123, 277) | ||
| 140 | assert w64_graphics._vs_c_lane_id(700) == (None, None, 700, 0) | ||
| 141 | |||
| 142 | |||
| 143 | def test_vs_probe_and_radv_perftest(monkeypatch): | ||
| 144 | monkeypatch.setenv("RADV_PERFTEST", "gewave32,nggc") | ||
| 145 | assert w64_graphics._radv_perftest(64) == "nggc" # the user's other flags stay, gewave32 goes | ||
| 146 | assert w64_graphics._radv_perftest(32) == "nggc,gewave32" | ||
| 147 | assert w64_graphics.FIXTURES[w64_graphics.VS_PROBE][0] == "C" | ||
| 148 | assert w64_graphics.VS_RECORDS * 4 >= 0x100 + 4 * w64_graphics.VS_VERTICES # the atomic's slots end below the records | ||
diff --git a/tests/test_world_index.py b/tests/test_world_index.py index 7f6d39569..93ca58e68 100644 --- a/tests/test_world_index.py +++ b/tests/test_world_index.py | |||
| @@ -609,6 +609,22 @@ class WorldIndexTest(unittest.TestCase): | |||
| 609 | rows, _ = WI.scan_path(self.carve([blob[:0x150], blob[0x150:]], gap=0x10)) | 609 | rows, _ = WI.scan_path(self.carve([blob[:0x150], blob[0x150:]], gap=0x10)) |
| 610 | self.assertEqual(rows, []) | 610 | self.assertEqual(rows, []) |
| 611 | 611 | ||
| 612 | def test_carved_file_inflate_cap_matches_directory_scan(self): | ||
| 613 | resource = make_resource() | ||
| 614 | path = os.path.join(self.dir, "sample.bin") | ||
| 615 | with open(path, "wb") as f: | ||
| 616 | f.write(resource) | ||
| 617 | |||
| 618 | for source in (path, self.dir): | ||
| 619 | for cap, expected in ((len(resource) - 1, 0), (len(resource), 1)): | ||
| 620 | with self.subTest(source=source, cap=cap): | ||
| 621 | entities = [] | ||
| 622 | rows, stats = WI.scan_path(source, max_inflate=cap, collect=entities) | ||
| 623 | self.assertEqual(len(rows), expected) | ||
| 624 | self.assertEqual(len(entities), expected) | ||
| 625 | self.assertEqual(stats["files"], expected) | ||
| 626 | self.assertEqual(stats["scanned_bytes"], expected * len(resource)) | ||
| 627 | |||
| 612 | def test_directory_inflate_cap_does_not_exclude_large_archives(self): | 628 | def test_directory_inflate_cap_does_not_exclude_large_archives(self): |
| 613 | resource = make_resource() | 629 | resource = make_resource() |
| 614 | cap = len(resource) | 630 | cap = len(resource) |
diff --git a/tests/test_world_lights_paths.py b/tests/test_world_lights_paths.py index 2ca8d6052..7ab8a665d 100644 --- a/tests/test_world_lights_paths.py +++ b/tests/test_world_lights_paths.py | |||
| @@ -371,6 +371,16 @@ class ScanTest(unittest.TestCase): | |||
| 371 | two = T.summarize(T.scan(self.rpf, jobs=2)) | 371 | two = T.summarize(T.scan(self.rpf, jobs=2)) |
| 372 | self.assertEqual(one, two) | 372 | self.assertEqual(one, two) |
| 373 | 373 | ||
| 374 | def test_cli_rejects_shared_report_destination(self): | ||
| 375 | out = os.path.join(self.tmp.name, "lights.json") | ||
| 376 | alias = os.path.join(self.tmp.name, ".", "lights.json") | ||
| 377 | err = io.StringIO() | ||
| 378 | with contextlib.redirect_stderr(err), self.assertRaises(SystemExit) as cm: | ||
| 379 | T.main([self.rpf, "--out", out, "--lights-out", alias]) | ||
| 380 | self.assertEqual(cm.exception.code, 2) | ||
| 381 | self.assertIn("--out and --lights-out must use different paths", err.getvalue()) | ||
| 382 | self.assertFalse(os.path.exists(out)) | ||
| 383 | |||
| 374 | def test_cli_writes_summary_and_placed_lights(self): | 384 | def test_cli_writes_summary_and_placed_lights(self): |
| 375 | out = os.path.join(self.tmp.name, "summary.json") | 385 | out = os.path.join(self.tmp.name, "summary.json") |
| 376 | lights = os.path.join(self.tmp.name, "lights.jsonl") | 386 | lights = os.path.join(self.tmp.name, "lights.jsonl") |
diff --git a/tests/test_world_names.py b/tests/test_world_names.py index 772e1b1d4..08b80483a 100644 --- a/tests/test_world_names.py +++ b/tests/test_world_names.py | |||
| @@ -337,7 +337,7 @@ class CliTest(unittest.TestCase): | |||
| 337 | err = io.StringIO() | 337 | err = io.StringIO() |
| 338 | with contextlib.redirect_stderr(err), contextlib.redirect_stdout(io.StringIO()): | 338 | with contextlib.redirect_stderr(err), contextlib.redirect_stdout(io.StringIO()): |
| 339 | self.assertNotEqual(WN.main(["resolve", *prefix, "--out", source]), 0) | 339 | self.assertNotEqual(WN.main(["resolve", *prefix, "--out", source]), 0) |
| 340 | self.assertIn(repr(source), err.getvalue()) | 340 | self.assertIn(f"would overwrite input {source}", err.getvalue()) |
| 341 | with open(source, "rb") as handle: | 341 | with open(source, "rb") as handle: |
| 342 | self.assertEqual(handle.read(), original) | 342 | self.assertEqual(handle.read(), original) |
| 343 | 343 | ||